blob: 8319996727a7745c5eb549fa0ce786ab91e7a019 [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
650 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
651 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
652
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
885 // Strip the noreturn off the type we're converting from; noreturn can
886 // safely be removed.
887 FromType = Context.getNoReturnType(FromType, false);
888 if (!Context.hasSameUnqualifiedType(FromType, ToType))
889 return false;
890
891 ResultTy = FromType;
892 return true;
893}
Douglas Gregor46188682010-05-18 22:42:18 +0000894
895/// \brief Determine whether the conversion from FromType to ToType is a valid
896/// vector conversion.
897///
898/// \param ICK Will be set to the vector conversion kind, if this is a vector
899/// conversion.
900static bool IsVectorConversion(ASTContext &Context, QualType FromType,
901 QualType ToType, ImplicitConversionKind &ICK) {
902 // We need at least one of these types to be a vector type to have a vector
903 // conversion.
904 if (!ToType->isVectorType() && !FromType->isVectorType())
905 return false;
906
907 // Identical types require no conversions.
908 if (Context.hasSameUnqualifiedType(FromType, ToType))
909 return false;
910
911 // There are no conversions between extended vector types, only identity.
912 if (ToType->isExtVectorType()) {
913 // There are no conversions between extended vector types other than the
914 // identity conversion.
915 if (FromType->isExtVectorType())
916 return false;
917
918 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000919 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000920 ICK = ICK_Vector_Splat;
921 return true;
922 }
923 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000924
925 // We can perform the conversion between vector types in the following cases:
926 // 1)vector types are equivalent AltiVec and GCC vector types
927 // 2)lax vector conversions are permitted and the vector types are of the
928 // same size
929 if (ToType->isVectorType() && FromType->isVectorType()) {
930 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000931 (Context.getLangOptions().LaxVectorConversions &&
932 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000933 ICK = ICK_Vector_Conversion;
934 return true;
935 }
Douglas Gregor46188682010-05-18 22:42:18 +0000936 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000937
Douglas Gregor46188682010-05-18 22:42:18 +0000938 return false;
939}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000940
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000941/// IsStandardConversion - Determines whether there is a standard
942/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
943/// expression From to the type ToType. Standard conversion sequences
944/// only consider non-class types; for conversions that involve class
945/// types, use TryImplicitConversion. If a conversion exists, SCS will
946/// contain the standard conversion sequence required to perform this
947/// conversion and this routine will return true. Otherwise, this
948/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000949static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
950 bool InOverloadResolution,
951 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000952 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000953
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000954 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000955 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000956 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000957 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000958 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000959 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000960
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000961 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000962 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000963 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000964 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000965 return false;
966
Mike Stump11289f42009-09-09 15:08:12 +0000967 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000968 }
969
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000970 // The first conversion can be an lvalue-to-rvalue conversion,
971 // array-to-pointer conversion, or function-to-pointer conversion
972 // (C++ 4p1).
973
John McCall5c32be02010-08-24 20:38:10 +0000974 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000975 DeclAccessPair AccessPair;
976 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000977 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
978 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000979 // We were able to resolve the address of the overloaded function,
980 // so we can convert to the type of that function.
981 FromType = Fn->getType();
982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
983 if (!Method->isStatic()) {
984 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000985 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
986 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000987 }
988 }
989
990 // If the "from" expression takes the address of the overloaded
991 // function, update the type of the resulting expression accordingly.
992 if (FromType->getAs<FunctionType>())
993 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000994 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000995 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000996
997 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000998 assert(S.Context.hasSameType(FromType,
999 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001000 } else {
1001 return false;
1002 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005 // An lvalue (3.10) of a non-function, non-array type T can be
1006 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001007 bool argIsLValue = From->isLValue();
1008 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001009 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001010 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001011 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012
1013 // If T is a non-class type, the type of the rvalue is the
1014 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001015 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1016 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001017 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001018 } else if (FromType->isArrayType()) {
1019 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001020 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001021
1022 // An lvalue or rvalue of type "array of N T" or "array of unknown
1023 // bound of T" can be converted to an rvalue of type "pointer to
1024 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001025 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001026
John McCall5c32be02010-08-24 20:38:10 +00001027 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001029 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001030
1031 // For the purpose of ranking in overload resolution
1032 // (13.3.3.1.1), this conversion is considered an
1033 // array-to-pointer conversion followed by a qualification
1034 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001035 SCS.Second = ICK_Identity;
1036 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001037 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001038 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039 }
John McCall086a4642010-11-24 05:12:34 +00001040 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001041 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001042 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043
1044 // An lvalue of function type T can be converted to an rvalue of
1045 // type "pointer to T." The result is a pointer to the
1046 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001047 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001048 } else {
1049 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001050 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001052 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001053
1054 // The second conversion can be an integral promotion, floating
1055 // point promotion, integral conversion, floating point conversion,
1056 // floating-integral conversion, pointer conversion,
1057 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 // For overloading in C, this can also be a "compatible-type"
1059 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001060 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001061 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001062 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 // The unqualified versions of the types are the same: there's no
1064 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001065 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001066 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001067 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001068 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001070 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001071 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001072 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001074 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001075 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001076 SCS.Second = ICK_Complex_Promotion;
1077 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001078 } else if (ToType->isBooleanType() &&
1079 (FromType->isArithmeticType() ||
1080 FromType->isAnyPointerType() ||
1081 FromType->isBlockPointerType() ||
1082 FromType->isMemberPointerType() ||
1083 FromType->isNullPtrType())) {
1084 // Boolean conversions (C++ 4.12).
1085 SCS.Second = ICK_Boolean_Conversion;
1086 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001087 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001088 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001089 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001090 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001091 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001092 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001093 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001094 SCS.Second = ICK_Complex_Conversion;
1095 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001096 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1097 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001098 // Complex-real conversions (C99 6.3.1.7)
1099 SCS.Second = ICK_Complex_Real;
1100 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001101 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001102 // Floating point conversions (C++ 4.8).
1103 SCS.Second = ICK_Floating_Conversion;
1104 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001105 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001106 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001107 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001108 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001109 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001110 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001112 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1113 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001114 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001115 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001116 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001117 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1118 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001119 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001120 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001121 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001122 SCS.Second = SecondICK;
1123 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001124 } else if (!S.getLangOptions().CPlusPlus &&
1125 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001126 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001127 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001128 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001129 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001130 // Treat a conversion that strips "noreturn" as an identity conversion.
1131 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 } else {
1133 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001134 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001136 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001138 QualType CanonFrom;
1139 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001141 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001142 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001143 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001144 CanonFrom = S.Context.getCanonicalType(FromType);
1145 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001146 } else {
1147 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001148 SCS.Third = ICK_Identity;
1149
Mike Stump11289f42009-09-09 15:08:12 +00001150 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 // [...] Any difference in top-level cv-qualification is
1152 // subsumed by the initialization itself and does not constitute
1153 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001154 CanonFrom = S.Context.getCanonicalType(FromType);
1155 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001156 if (CanonFrom.getLocalUnqualifiedType()
1157 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001158 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1159 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001160 FromType = ToType;
1161 CanonFrom = CanonTo;
1162 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001164 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165
1166 // If we have not converted the argument type to the parameter type,
1167 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001168 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001169 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001171 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001172}
1173
1174/// IsIntegralPromotion - Determines whether the conversion from the
1175/// expression From (whose potentially-adjusted type is FromType) to
1176/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1177/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001178bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001179 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001180 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001181 if (!To) {
1182 return false;
1183 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184
1185 // An rvalue of type char, signed char, unsigned char, short int, or
1186 // unsigned short int can be converted to an rvalue of type int if
1187 // int can represent all the values of the source type; otherwise,
1188 // the source rvalue can be converted to an rvalue of type unsigned
1189 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001190 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1191 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001192 if (// We can promote any signed, promotable integer type to an int
1193 (FromType->isSignedIntegerType() ||
1194 // We can promote any unsigned integer type whose size is
1195 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001196 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001197 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001198 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001199 }
1200
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001201 return To->getKind() == BuiltinType::UInt;
1202 }
1203
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001204 // C++0x [conv.prom]p3:
1205 // A prvalue of an unscoped enumeration type whose underlying type is not
1206 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1207 // following types that can represent all the values of the enumeration
1208 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1209 // unsigned int, long int, unsigned long int, long long int, or unsigned
1210 // long long int. If none of the types in that list can represent all the
1211 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1212 // type can be converted to an rvalue a prvalue of the extended integer type
1213 // with lowest integer conversion rank (4.13) greater than the rank of long
1214 // long in which all the values of the enumeration can be represented. If
1215 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001216 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1217 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1218 // provided for a scoped enumeration.
1219 if (FromEnumType->getDecl()->isScoped())
1220 return false;
1221
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001222 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001223 if (ToType->isIntegerType() &&
1224 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001225 return Context.hasSameUnqualifiedType(ToType,
1226 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001227 }
John McCall56774992009-12-09 09:09:27 +00001228
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001229 // C++0x [conv.prom]p2:
1230 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1231 // to an rvalue a prvalue of the first of the following types that can
1232 // represent all the values of its underlying type: int, unsigned int,
1233 // long int, unsigned long int, long long int, or unsigned long long int.
1234 // If none of the types in that list can represent all the values of its
1235 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1236 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1237 // type.
1238 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1239 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 // Determine whether the type we're converting from is signed or
1241 // unsigned.
1242 bool FromIsSigned;
1243 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001244
1245 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1246 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001247
1248 // The types we'll try to promote to, in the appropriate
1249 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001250 QualType PromoteTypes[6] = {
1251 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001252 Context.LongTy, Context.UnsignedLongTy ,
1253 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001255 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001256 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1257 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001258 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1260 // We found the type that we can promote to. If this is the
1261 // type we wanted, we have a promotion. Otherwise, no
1262 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001263 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264 }
1265 }
1266 }
1267
1268 // An rvalue for an integral bit-field (9.6) can be converted to an
1269 // rvalue of type int if int can represent all the values of the
1270 // bit-field; otherwise, it can be converted to unsigned int if
1271 // unsigned int can represent all the values of the bit-field. If
1272 // the bit-field is larger yet, no integral promotion applies to
1273 // it. If the bit-field has an enumerated type, it is treated as any
1274 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001275 // FIXME: We should delay checking of bit-fields until we actually perform the
1276 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001277 using llvm::APSInt;
1278 if (From)
1279 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001280 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001281 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001282 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1283 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1284 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001285
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001286 // Are we promoting to an int from a bitfield that fits in an int?
1287 if (BitWidth < ToSize ||
1288 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1289 return To->getKind() == BuiltinType::Int;
1290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001292 // Are we promoting to an unsigned int from an unsigned bitfield
1293 // that fits into an unsigned int?
1294 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1295 return To->getKind() == BuiltinType::UInt;
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001298 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 // An rvalue of type bool can be converted to an rvalue of type int,
1303 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001304 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001306 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001307
1308 return false;
1309}
1310
1311/// IsFloatingPointPromotion - Determines whether the conversion from
1312/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1313/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001314bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001315 /// An rvalue of type float can be converted to an rvalue of type
1316 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001317 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1318 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 if (FromBuiltin->getKind() == BuiltinType::Float &&
1320 ToBuiltin->getKind() == BuiltinType::Double)
1321 return true;
1322
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001323 // C99 6.3.1.5p1:
1324 // When a float is promoted to double or long double, or a
1325 // double is promoted to long double [...].
1326 if (!getLangOptions().CPlusPlus &&
1327 (FromBuiltin->getKind() == BuiltinType::Float ||
1328 FromBuiltin->getKind() == BuiltinType::Double) &&
1329 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1330 return true;
1331 }
1332
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333 return false;
1334}
1335
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001336/// \brief Determine if a conversion is a complex promotion.
1337///
1338/// A complex promotion is defined as a complex -> complex conversion
1339/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001340/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001341bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001342 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001343 if (!FromComplex)
1344 return false;
1345
John McCall9dd450b2009-09-21 23:43:11 +00001346 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001347 if (!ToComplex)
1348 return false;
1349
1350 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001351 ToComplex->getElementType()) ||
1352 IsIntegralPromotion(0, FromComplex->getElementType(),
1353 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001354}
1355
Douglas Gregor237f96c2008-11-26 23:31:11 +00001356/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1357/// the pointer type FromPtr to a pointer to type ToPointee, with the
1358/// same type qualifiers as FromPtr has on its pointee type. ToType,
1359/// if non-empty, will be a pointer to ToType that may or may not have
1360/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001361static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001362BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001363 QualType ToPointee, QualType ToType,
1364 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001365 assert((FromPtr->getTypeClass() == Type::Pointer ||
1366 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1367 "Invalid similarly-qualified pointer type");
1368 QualType CanonFromPointee
1369 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001370 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001371 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001372
1373 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001374 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001375 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001376 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001377 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001378
1379 // Build a pointer to ToPointee. It has the right qualifiers
1380 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001381 if (isa<ObjCObjectPointerType>(ToType))
1382 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001383 return Context.getPointerType(ToPointee);
1384 }
1385
1386 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001387 QualType QualifiedCanonToPointee
1388 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001389
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001390 if (isa<ObjCObjectPointerType>(ToType))
1391 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1392 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001393}
1394
Mike Stump11289f42009-09-09 15:08:12 +00001395static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001396 bool InOverloadResolution,
1397 ASTContext &Context) {
1398 // Handle value-dependent integral null pointer constants correctly.
1399 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1400 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001401 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001402 return !InOverloadResolution;
1403
Douglas Gregor56751b52009-09-25 04:25:58 +00001404 return Expr->isNullPointerConstant(Context,
1405 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1406 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001407}
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409/// IsPointerConversion - Determines whether the conversion of the
1410/// expression From, which has the (possibly adjusted) type FromType,
1411/// can be converted to the type ToType via a pointer conversion (C++
1412/// 4.10). If so, returns true and places the converted type (that
1413/// might differ from ToType in its cv-qualifiers at some level) into
1414/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001415///
Douglas Gregora29dc052008-11-27 01:19:21 +00001416/// This routine also supports conversions to and from block pointers
1417/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1418/// pointers to interfaces. FIXME: Once we've determined the
1419/// appropriate overloading rules for Objective-C, we may want to
1420/// split the Objective-C checks into a different routine; however,
1421/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001422/// conversions, so for now they live here. IncompatibleObjC will be
1423/// set if the conversion is an allowed Objective-C conversion that
1424/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001425bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001426 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001427 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001428 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001429 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001430 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1431 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001432
Mike Stump11289f42009-09-09 15:08:12 +00001433 // Conversion from a null pointer constant to any Objective-C pointer type.
1434 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001435 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001436 ConvertedType = ToType;
1437 return true;
1438 }
1439
Douglas Gregor231d1c62008-11-27 00:15:41 +00001440 // Blocks: Block pointers can be converted to void*.
1441 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001442 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001443 ConvertedType = ToType;
1444 return true;
1445 }
1446 // Blocks: A null pointer constant can be converted to a block
1447 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001448 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001449 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001450 ConvertedType = ToType;
1451 return true;
1452 }
1453
Sebastian Redl576fd422009-05-10 18:38:11 +00001454 // If the left-hand-side is nullptr_t, the right side can be a null
1455 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001456 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001457 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001458 ConvertedType = ToType;
1459 return true;
1460 }
1461
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001462 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001463 if (!ToTypePtr)
1464 return false;
1465
1466 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001467 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001468 ConvertedType = ToType;
1469 return true;
1470 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001471
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001472 // Beyond this point, both types need to be pointers
1473 // , including objective-c pointers.
1474 QualType ToPointeeType = ToTypePtr->getPointeeType();
1475 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001476 ConvertedType = BuildSimilarlyQualifiedPointerType(
1477 FromType->getAs<ObjCObjectPointerType>(),
1478 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001479 ToType, Context);
1480 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001481 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001482 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001483 if (!FromTypePtr)
1484 return false;
1485
1486 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001487
Douglas Gregorfb640862010-08-18 21:25:30 +00001488 // If the unqualified pointee types are the same, this can't be a
1489 // pointer conversion, so don't do all of the work below.
1490 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1491 return false;
1492
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493 // An rvalue of type "pointer to cv T," where T is an object type,
1494 // can be converted to an rvalue of type "pointer to cv void" (C++
1495 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001496 if (FromPointeeType->isIncompleteOrObjectType() &&
1497 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001498 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001499 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001500 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 return true;
1502 }
1503
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001504 // When we're overloading in C, we allow a special kind of pointer
1505 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001506 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001507 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001508 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001509 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001510 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001511 return true;
1512 }
1513
Douglas Gregor5c407d92008-10-23 00:40:37 +00001514 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001515 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001516 // An rvalue of type "pointer to cv D," where D is a class type,
1517 // can be converted to an rvalue of type "pointer to cv B," where
1518 // B is a base class (clause 10) of D. If B is an inaccessible
1519 // (clause 11) or ambiguous (10.2) base class of D, a program that
1520 // necessitates this conversion is ill-formed. The result of the
1521 // conversion is a pointer to the base class sub-object of the
1522 // derived class object. The null pointer value is converted to
1523 // the null pointer value of the destination type.
1524 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001525 // Note that we do not check for ambiguity or inaccessibility
1526 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001527 if (getLangOptions().CPlusPlus &&
1528 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001529 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001530 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001531 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001532 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001533 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001534 ToType, Context);
1535 return true;
1536 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001537
Douglas Gregora119f102008-12-19 19:13:09 +00001538 return false;
1539}
1540
1541/// isObjCPointerConversion - Determines whether this is an
1542/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1543/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001544bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001545 QualType& ConvertedType,
1546 bool &IncompatibleObjC) {
1547 if (!getLangOptions().ObjC1)
1548 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001549
Steve Naroff7cae42b2009-07-10 23:34:53 +00001550 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001551 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001552 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001553 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001554
Steve Naroff7cae42b2009-07-10 23:34:53 +00001555 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001556 // If the pointee types are the same (ignoring qualifications),
1557 // then this is not a pointer conversion.
1558 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1559 FromObjCPtr->getPointeeType()))
1560 return false;
1561
Steve Naroff1329fa02009-07-15 18:40:39 +00001562 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001563 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001564 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001565 ConvertedType = ToType;
1566 return true;
1567 }
1568 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001569 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001570 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001571 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001572 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001573 ConvertedType = ToType;
1574 return true;
1575 }
1576 // Objective C++: We're able to convert from a pointer to an
1577 // interface to a pointer to a different interface.
1578 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001579 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1580 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1581 if (getLangOptions().CPlusPlus && LHS && RHS &&
1582 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1583 FromObjCPtr->getPointeeType()))
1584 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001585 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1586 ToObjCPtr->getPointeeType(),
1587 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001588 return true;
1589 }
1590
1591 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1592 // Okay: this is some kind of implicit downcast of Objective-C
1593 // interfaces, which is permitted. However, we're going to
1594 // complain about it.
1595 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001596 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1597 ToObjCPtr->getPointeeType(),
1598 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001599 return true;
1600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001602 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001603 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001604 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001605 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001606 else if (const BlockPointerType *ToBlockPtr =
1607 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001608 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001609 // to a block pointer type.
1610 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1611 ConvertedType = ToType;
1612 return true;
1613 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001614 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001615 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001616 else if (FromType->getAs<BlockPointerType>() &&
1617 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1618 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001619 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001620 ConvertedType = ToType;
1621 return true;
1622 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001623 else
Douglas Gregora119f102008-12-19 19:13:09 +00001624 return false;
1625
Douglas Gregor033f56d2008-12-23 00:53:59 +00001626 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001627 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001628 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001629 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001630 FromPointeeType = FromBlockPtr->getPointeeType();
1631 else
Douglas Gregora119f102008-12-19 19:13:09 +00001632 return false;
1633
Douglas Gregora119f102008-12-19 19:13:09 +00001634 // If we have pointers to pointers, recursively check whether this
1635 // is an Objective-C conversion.
1636 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1637 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1638 IncompatibleObjC)) {
1639 // We always complain about this conversion.
1640 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001641 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001642 return true;
1643 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001644 // Allow conversion of pointee being objective-c pointer to another one;
1645 // as in I* to id.
1646 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1647 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1648 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1649 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001650 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001651 return true;
1652 }
1653
Douglas Gregor033f56d2008-12-23 00:53:59 +00001654 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001655 // differences in the argument and result types are in Objective-C
1656 // pointer conversions. If so, we permit the conversion (but
1657 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001658 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001659 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001660 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001661 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001662 if (FromFunctionType && ToFunctionType) {
1663 // If the function types are exactly the same, this isn't an
1664 // Objective-C pointer conversion.
1665 if (Context.getCanonicalType(FromPointeeType)
1666 == Context.getCanonicalType(ToPointeeType))
1667 return false;
1668
1669 // Perform the quick checks that will tell us whether these
1670 // function types are obviously different.
1671 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1672 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1673 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1674 return false;
1675
1676 bool HasObjCConversion = false;
1677 if (Context.getCanonicalType(FromFunctionType->getResultType())
1678 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1679 // Okay, the types match exactly. Nothing to do.
1680 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1681 ToFunctionType->getResultType(),
1682 ConvertedType, IncompatibleObjC)) {
1683 // Okay, we have an Objective-C pointer conversion.
1684 HasObjCConversion = true;
1685 } else {
1686 // Function types are too different. Abort.
1687 return false;
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Douglas Gregora119f102008-12-19 19:13:09 +00001690 // Check argument types.
1691 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1692 ArgIdx != NumArgs; ++ArgIdx) {
1693 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1694 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1695 if (Context.getCanonicalType(FromArgType)
1696 == Context.getCanonicalType(ToArgType)) {
1697 // Okay, the types match exactly. Nothing to do.
1698 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1699 ConvertedType, IncompatibleObjC)) {
1700 // Okay, we have an Objective-C pointer conversion.
1701 HasObjCConversion = true;
1702 } else {
1703 // Argument types are too different. Abort.
1704 return false;
1705 }
1706 }
1707
1708 if (HasObjCConversion) {
1709 // We had an Objective-C conversion. Allow this pointer
1710 // conversion, but complain about it.
1711 ConvertedType = ToType;
1712 IncompatibleObjC = true;
1713 return true;
1714 }
1715 }
1716
Sebastian Redl72b597d2009-01-25 19:43:20 +00001717 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001719
1720/// FunctionArgTypesAreEqual - This routine checks two function proto types
1721/// for equlity of their argument types. Caller has already checked that
1722/// they have same number of arguments. This routine assumes that Objective-C
1723/// pointer types which only differ in their protocol qualifiers are equal.
1724bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1725 FunctionProtoType* NewType){
1726 if (!getLangOptions().ObjC1)
1727 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1728 NewType->arg_type_begin());
1729
1730 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1731 N = NewType->arg_type_begin(),
1732 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1733 QualType ToType = (*O);
1734 QualType FromType = (*N);
1735 if (ToType != FromType) {
1736 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1737 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001738 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1739 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1740 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1741 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001742 continue;
1743 }
John McCall8b07ec22010-05-15 11:32:37 +00001744 else if (const ObjCObjectPointerType *PTTo =
1745 ToType->getAs<ObjCObjectPointerType>()) {
1746 if (const ObjCObjectPointerType *PTFr =
1747 FromType->getAs<ObjCObjectPointerType>())
1748 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1749 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001750 }
1751 return false;
1752 }
1753 }
1754 return true;
1755}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756
Douglas Gregor39c16d42008-10-24 04:54:22 +00001757/// CheckPointerConversion - Check the pointer conversion from the
1758/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001759/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001760/// conversions for which IsPointerConversion has already returned
1761/// true. It returns true and produces a diagnostic if there was an
1762/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001763bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001764 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001765 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001766 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001767 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001768 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001769
John McCall8cb679e2010-11-15 09:13:47 +00001770 Kind = CK_BitCast;
1771
Douglas Gregor4038cf42010-06-08 17:35:15 +00001772 if (CXXBoolLiteralExpr* LitBool
1773 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001774 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001775 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1776 << ToType;
1777
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001778 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1779 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001780 QualType FromPointeeType = FromPtrType->getPointeeType(),
1781 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001782
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001783 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1784 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001785 // We must have a derived-to-base conversion. Check an
1786 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001787 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1788 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001789 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001790 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001791 return true;
1792
1793 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001794 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001795 }
1796 }
Mike Stump11289f42009-09-09 15:08:12 +00001797 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001798 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001799 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001800 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001801 // Objective-C++ conversions are always okay.
1802 // FIXME: We should have a different class of conversions for the
1803 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001804 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001805 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001806 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001807 }
John McCall8cb679e2010-11-15 09:13:47 +00001808
1809 // We shouldn't fall into this case unless it's valid for other
1810 // reasons.
1811 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1812 Kind = CK_NullToPointer;
1813
Douglas Gregor39c16d42008-10-24 04:54:22 +00001814 return false;
1815}
1816
Sebastian Redl72b597d2009-01-25 19:43:20 +00001817/// IsMemberPointerConversion - Determines whether the conversion of the
1818/// expression From, which has the (possibly adjusted) type FromType, can be
1819/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1820/// If so, returns true and places the converted type (that might differ from
1821/// ToType in its cv-qualifiers at some level) into ConvertedType.
1822bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001823 QualType ToType,
1824 bool InOverloadResolution,
1825 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001826 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001827 if (!ToTypePtr)
1828 return false;
1829
1830 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001831 if (From->isNullPointerConstant(Context,
1832 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1833 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001834 ConvertedType = ToType;
1835 return true;
1836 }
1837
1838 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001839 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001840 if (!FromTypePtr)
1841 return false;
1842
1843 // A pointer to member of B can be converted to a pointer to member of D,
1844 // where D is derived from B (C++ 4.11p2).
1845 QualType FromClass(FromTypePtr->getClass(), 0);
1846 QualType ToClass(ToTypePtr->getClass(), 0);
1847 // FIXME: What happens when these are dependent? Is this function even called?
1848
1849 if (IsDerivedFrom(ToClass, FromClass)) {
1850 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1851 ToClass.getTypePtr());
1852 return true;
1853 }
1854
1855 return false;
1856}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001857
Sebastian Redl72b597d2009-01-25 19:43:20 +00001858/// CheckMemberPointerConversion - Check the member pointer conversion from the
1859/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001860/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001861/// for which IsMemberPointerConversion has already returned true. It returns
1862/// true and produces a diagnostic if there was an error, or returns false
1863/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001864bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001865 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001866 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001867 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001868 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001869 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001870 if (!FromPtrType) {
1871 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001872 assert(From->isNullPointerConstant(Context,
1873 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001874 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001875 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001876 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001877 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001878
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001879 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001880 assert(ToPtrType && "No member pointer cast has a target type "
1881 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001882
Sebastian Redled8f2002009-01-28 18:33:18 +00001883 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1884 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001885
Sebastian Redled8f2002009-01-28 18:33:18 +00001886 // FIXME: What about dependent types?
1887 assert(FromClass->isRecordType() && "Pointer into non-class.");
1888 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001889
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001890 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001891 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001892 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1893 assert(DerivationOkay &&
1894 "Should not have been called if derivation isn't OK.");
1895 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001896
Sebastian Redled8f2002009-01-28 18:33:18 +00001897 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1898 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001899 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1900 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1901 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1902 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001903 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001904
Douglas Gregor89ee6822009-02-28 01:32:25 +00001905 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001906 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1907 << FromClass << ToClass << QualType(VBase, 0)
1908 << From->getSourceRange();
1909 return true;
1910 }
1911
John McCall5b0829a2010-02-10 09:31:12 +00001912 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001913 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1914 Paths.front(),
1915 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001916
Anders Carlssond7923c62009-08-22 23:33:40 +00001917 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001918 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001919 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001920 return false;
1921}
1922
Douglas Gregor9a657932008-10-21 23:43:52 +00001923/// IsQualificationConversion - Determines whether the conversion from
1924/// an rvalue of type FromType to ToType is a qualification conversion
1925/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001926bool
1927Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001928 FromType = Context.getCanonicalType(FromType);
1929 ToType = Context.getCanonicalType(ToType);
1930
1931 // If FromType and ToType are the same type, this is not a
1932 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001933 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001934 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001935
Douglas Gregor9a657932008-10-21 23:43:52 +00001936 // (C++ 4.4p4):
1937 // A conversion can add cv-qualifiers at levels other than the first
1938 // in multi-level pointers, subject to the following rules: [...]
1939 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001940 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001941 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001942 // Within each iteration of the loop, we check the qualifiers to
1943 // determine if this still looks like a qualification
1944 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001945 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001946 // until there are no more pointers or pointers-to-members left to
1947 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001948 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001949
1950 // -- for every j > 0, if const is in cv 1,j then const is in cv
1951 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001952 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001953 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregor9a657932008-10-21 23:43:52 +00001955 // -- if the cv 1,j and cv 2,j are different, then const is in
1956 // every cv for 0 < k < j.
1957 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001958 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001959 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001960
Douglas Gregor9a657932008-10-21 23:43:52 +00001961 // Keep track of whether all prior cv-qualifiers in the "to" type
1962 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001963 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001964 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001965 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001966
1967 // We are left with FromType and ToType being the pointee types
1968 // after unwrapping the original FromType and ToType the same number
1969 // of types. If we unwrapped any pointers, and if FromType and
1970 // ToType have the same unqualified type (since we checked
1971 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001972 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001973}
1974
Douglas Gregor576e98c2009-01-30 23:27:23 +00001975/// Determines whether there is a user-defined conversion sequence
1976/// (C++ [over.ics.user]) that converts expression From to the type
1977/// ToType. If such a conversion exists, User will contain the
1978/// user-defined conversion sequence that performs such a conversion
1979/// and this routine will return true. Otherwise, this routine returns
1980/// false and User is unspecified.
1981///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001982/// \param AllowExplicit true if the conversion should consider C++0x
1983/// "explicit" conversion functions as well as non-explicit conversion
1984/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001985static OverloadingResult
1986IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1987 UserDefinedConversionSequence& User,
1988 OverloadCandidateSet& CandidateSet,
1989 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001990 // Whether we will only visit constructors.
1991 bool ConstructorsOnly = false;
1992
1993 // If the type we are conversion to is a class type, enumerate its
1994 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001995 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001996 // C++ [over.match.ctor]p1:
1997 // When objects of class type are direct-initialized (8.5), or
1998 // copy-initialized from an expression of the same or a
1999 // derived class type (8.5), overload resolution selects the
2000 // constructor. [...] For copy-initialization, the candidate
2001 // functions are all the converting constructors (12.3.1) of
2002 // that class. The argument list is the expression-list within
2003 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002004 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002005 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002006 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002007 ConstructorsOnly = true;
2008
John McCall5c32be02010-08-24 20:38:10 +00002009 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002010 // We're not going to find any constructors.
2011 } else if (CXXRecordDecl *ToRecordDecl
2012 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002013 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002014 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002015 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002016 NamedDecl *D = *Con;
2017 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2018
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002019 // Find the constructor (which may be a template).
2020 CXXConstructorDecl *Constructor = 0;
2021 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002022 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002023 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002024 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002025 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2026 else
John McCalla0296f72010-03-19 07:35:19 +00002027 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002028
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002029 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002030 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002031 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002032 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2033 /*ExplicitArgs*/ 0,
2034 &From, 1, CandidateSet,
2035 /*SuppressUserConversions=*/
2036 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002037 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002038 // Allow one user-defined conversion when user specifies a
2039 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002040 S.AddOverloadCandidate(Constructor, FoundDecl,
2041 &From, 1, CandidateSet,
2042 /*SuppressUserConversions=*/
2043 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002044 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002045 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002046 }
2047 }
2048
Douglas Gregor5ab11652010-04-17 22:01:05 +00002049 // Enumerate conversion functions, if we're allowed to.
2050 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002051 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2052 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002053 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002054 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002055 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002056 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002057 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2058 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002059 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002060 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002061 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002062 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002063 DeclAccessPair FoundDecl = I.getPair();
2064 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002065 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2066 if (isa<UsingShadowDecl>(D))
2067 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2068
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002069 CXXConversionDecl *Conv;
2070 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002071 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2072 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002073 else
John McCallda4458e2010-03-31 01:36:47 +00002074 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002075
2076 if (AllowExplicit || !Conv->isExplicit()) {
2077 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002078 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2079 ActingContext, From, ToType,
2080 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002081 else
John McCall5c32be02010-08-24 20:38:10 +00002082 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2083 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002084 }
2085 }
2086 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002087 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002088
2089 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002090 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002091 case OR_Success:
2092 // Record the standard conversion we used and the conversion function.
2093 if (CXXConstructorDecl *Constructor
2094 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2095 // C++ [over.ics.user]p1:
2096 // If the user-defined conversion is specified by a
2097 // constructor (12.3.1), the initial standard conversion
2098 // sequence converts the source type to the type required by
2099 // the argument of the constructor.
2100 //
2101 QualType ThisType = Constructor->getThisType(S.Context);
2102 if (Best->Conversions[0].isEllipsis())
2103 User.EllipsisConversion = true;
2104 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002105 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002106 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002107 }
John McCall5c32be02010-08-24 20:38:10 +00002108 User.ConversionFunction = Constructor;
2109 User.After.setAsIdentityConversion();
2110 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2111 User.After.setAllToTypes(ToType);
2112 return OR_Success;
2113 } else if (CXXConversionDecl *Conversion
2114 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2115 // C++ [over.ics.user]p1:
2116 //
2117 // [...] If the user-defined conversion is specified by a
2118 // conversion function (12.3.2), the initial standard
2119 // conversion sequence converts the source type to the
2120 // implicit object parameter of the conversion function.
2121 User.Before = Best->Conversions[0].Standard;
2122 User.ConversionFunction = Conversion;
2123 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002124
John McCall5c32be02010-08-24 20:38:10 +00002125 // C++ [over.ics.user]p2:
2126 // The second standard conversion sequence converts the
2127 // result of the user-defined conversion to the target type
2128 // for the sequence. Since an implicit conversion sequence
2129 // is an initialization, the special rules for
2130 // initialization by user-defined conversion apply when
2131 // selecting the best user-defined conversion for a
2132 // user-defined conversion sequence (see 13.3.3 and
2133 // 13.3.3.1).
2134 User.After = Best->FinalConversion;
2135 return OR_Success;
2136 } else {
2137 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002138 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002139 }
2140
John McCall5c32be02010-08-24 20:38:10 +00002141 case OR_No_Viable_Function:
2142 return OR_No_Viable_Function;
2143 case OR_Deleted:
2144 // No conversion here! We're done.
2145 return OR_Deleted;
2146
2147 case OR_Ambiguous:
2148 return OR_Ambiguous;
2149 }
2150
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002151 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002152}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002153
2154bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002155Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002156 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002157 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002158 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002159 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002160 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002161 if (OvResult == OR_Ambiguous)
2162 Diag(From->getSourceRange().getBegin(),
2163 diag::err_typecheck_ambiguous_condition)
2164 << From->getType() << ToType << From->getSourceRange();
2165 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2166 Diag(From->getSourceRange().getBegin(),
2167 diag::err_typecheck_nonviable_condition)
2168 << From->getType() << ToType << From->getSourceRange();
2169 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002170 return false;
John McCall5c32be02010-08-24 20:38:10 +00002171 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002172 return true;
2173}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002174
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002175/// CompareImplicitConversionSequences - Compare two implicit
2176/// conversion sequences to determine whether one is better than the
2177/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002178static ImplicitConversionSequence::CompareKind
2179CompareImplicitConversionSequences(Sema &S,
2180 const ImplicitConversionSequence& ICS1,
2181 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002182{
2183 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2184 // conversion sequences (as defined in 13.3.3.1)
2185 // -- a standard conversion sequence (13.3.3.1.1) is a better
2186 // conversion sequence than a user-defined conversion sequence or
2187 // an ellipsis conversion sequence, and
2188 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2189 // conversion sequence than an ellipsis conversion sequence
2190 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002191 //
John McCall0d1da222010-01-12 00:44:57 +00002192 // C++0x [over.best.ics]p10:
2193 // For the purpose of ranking implicit conversion sequences as
2194 // described in 13.3.3.2, the ambiguous conversion sequence is
2195 // treated as a user-defined sequence that is indistinguishable
2196 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002197 if (ICS1.getKindRank() < ICS2.getKindRank())
2198 return ImplicitConversionSequence::Better;
2199 else if (ICS2.getKindRank() < ICS1.getKindRank())
2200 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002201
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002202 // The following checks require both conversion sequences to be of
2203 // the same kind.
2204 if (ICS1.getKind() != ICS2.getKind())
2205 return ImplicitConversionSequence::Indistinguishable;
2206
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207 // Two implicit conversion sequences of the same form are
2208 // indistinguishable conversion sequences unless one of the
2209 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002210 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002211 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002212 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002213 // User-defined conversion sequence U1 is a better conversion
2214 // sequence than another user-defined conversion sequence U2 if
2215 // they contain the same user-defined conversion function or
2216 // constructor and if the second standard conversion sequence of
2217 // U1 is better than the second standard conversion sequence of
2218 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002219 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002220 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002221 return CompareStandardConversionSequences(S,
2222 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002223 ICS2.UserDefined.After);
2224 }
2225
2226 return ImplicitConversionSequence::Indistinguishable;
2227}
2228
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002229static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2230 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2231 Qualifiers Quals;
2232 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2233 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2234 }
2235
2236 return Context.hasSameUnqualifiedType(T1, T2);
2237}
2238
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002239// Per 13.3.3.2p3, compare the given standard conversion sequences to
2240// determine if one is a proper subset of the other.
2241static ImplicitConversionSequence::CompareKind
2242compareStandardConversionSubsets(ASTContext &Context,
2243 const StandardConversionSequence& SCS1,
2244 const StandardConversionSequence& SCS2) {
2245 ImplicitConversionSequence::CompareKind Result
2246 = ImplicitConversionSequence::Indistinguishable;
2247
Douglas Gregore87561a2010-05-23 22:10:15 +00002248 // the identity conversion sequence is considered to be a subsequence of
2249 // any non-identity conversion sequence
2250 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2251 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2252 return ImplicitConversionSequence::Better;
2253 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2254 return ImplicitConversionSequence::Worse;
2255 }
2256
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002257 if (SCS1.Second != SCS2.Second) {
2258 if (SCS1.Second == ICK_Identity)
2259 Result = ImplicitConversionSequence::Better;
2260 else if (SCS2.Second == ICK_Identity)
2261 Result = ImplicitConversionSequence::Worse;
2262 else
2263 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002264 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002265 return ImplicitConversionSequence::Indistinguishable;
2266
2267 if (SCS1.Third == SCS2.Third) {
2268 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2269 : ImplicitConversionSequence::Indistinguishable;
2270 }
2271
2272 if (SCS1.Third == ICK_Identity)
2273 return Result == ImplicitConversionSequence::Worse
2274 ? ImplicitConversionSequence::Indistinguishable
2275 : ImplicitConversionSequence::Better;
2276
2277 if (SCS2.Third == ICK_Identity)
2278 return Result == ImplicitConversionSequence::Better
2279 ? ImplicitConversionSequence::Indistinguishable
2280 : ImplicitConversionSequence::Worse;
2281
2282 return ImplicitConversionSequence::Indistinguishable;
2283}
2284
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002285/// CompareStandardConversionSequences - Compare two standard
2286/// conversion sequences to determine whether one is better than the
2287/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002288static ImplicitConversionSequence::CompareKind
2289CompareStandardConversionSequences(Sema &S,
2290 const StandardConversionSequence& SCS1,
2291 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292{
2293 // Standard conversion sequence S1 is a better conversion sequence
2294 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2295
2296 // -- S1 is a proper subsequence of S2 (comparing the conversion
2297 // sequences in the canonical form defined by 13.3.3.1.1,
2298 // excluding any Lvalue Transformation; the identity conversion
2299 // sequence is considered to be a subsequence of any
2300 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002301 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002302 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002303 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002304
2305 // -- the rank of S1 is better than the rank of S2 (by the rules
2306 // defined below), or, if not that,
2307 ImplicitConversionRank Rank1 = SCS1.getRank();
2308 ImplicitConversionRank Rank2 = SCS2.getRank();
2309 if (Rank1 < Rank2)
2310 return ImplicitConversionSequence::Better;
2311 else if (Rank2 < Rank1)
2312 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002313
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002314 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2315 // are indistinguishable unless one of the following rules
2316 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002318 // A conversion that is not a conversion of a pointer, or
2319 // pointer to member, to bool is better than another conversion
2320 // that is such a conversion.
2321 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2322 return SCS2.isPointerConversionToBool()
2323 ? ImplicitConversionSequence::Better
2324 : ImplicitConversionSequence::Worse;
2325
Douglas Gregor5c407d92008-10-23 00:40:37 +00002326 // C++ [over.ics.rank]p4b2:
2327 //
2328 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002329 // conversion of B* to A* is better than conversion of B* to
2330 // void*, and conversion of A* to void* is better than conversion
2331 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002332 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002333 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002334 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002335 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002336 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2337 // Exactly one of the conversion sequences is a conversion to
2338 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002339 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2340 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2342 // Neither conversion sequence converts to a void pointer; compare
2343 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002344 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002345 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002346 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002347 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2348 // Both conversion sequences are conversions to void
2349 // pointers. Compare the source types to determine if there's an
2350 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002351 QualType FromType1 = SCS1.getFromType();
2352 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002353
2354 // Adjust the types we're converting from via the array-to-pointer
2355 // conversion, if we need to.
2356 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002357 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002358 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002359 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002360
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002361 QualType FromPointee1
2362 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2363 QualType FromPointee2
2364 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002365
John McCall5c32be02010-08-24 20:38:10 +00002366 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002367 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002368 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002369 return ImplicitConversionSequence::Worse;
2370
2371 // Objective-C++: If one interface is more specific than the
2372 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002373 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2374 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002375 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002376 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002377 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002378 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002379 return ImplicitConversionSequence::Worse;
2380 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002381 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002382
2383 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2384 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002385 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002386 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002387 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002388
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002389 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002390 // C++0x [over.ics.rank]p3b4:
2391 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2392 // implicit object parameter of a non-static member function declared
2393 // without a ref-qualifier, and S1 binds an rvalue reference to an
2394 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002395 // FIXME: We don't know if we're dealing with the implicit object parameter,
2396 // or if the member function in this case has a ref qualifier.
2397 // (Of course, we don't have ref qualifiers yet.)
2398 if (SCS1.RRefBinding != SCS2.RRefBinding)
2399 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2400 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002401
2402 // C++ [over.ics.rank]p3b4:
2403 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2404 // which the references refer are the same type except for
2405 // top-level cv-qualifiers, and the type to which the reference
2406 // initialized by S2 refers is more cv-qualified than the type
2407 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002408 QualType T1 = SCS1.getToType(2);
2409 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002410 T1 = S.Context.getCanonicalType(T1);
2411 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002412 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002413 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2414 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002415 if (UnqualT1 == UnqualT2) {
2416 // If the type is an array type, promote the element qualifiers to the type
2417 // for comparison.
2418 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002419 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002420 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002421 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002422 if (T2.isMoreQualifiedThan(T1))
2423 return ImplicitConversionSequence::Better;
2424 else if (T1.isMoreQualifiedThan(T2))
2425 return ImplicitConversionSequence::Worse;
2426 }
2427 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002428
2429 return ImplicitConversionSequence::Indistinguishable;
2430}
2431
2432/// CompareQualificationConversions - Compares two standard conversion
2433/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002434/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2435ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002436CompareQualificationConversions(Sema &S,
2437 const StandardConversionSequence& SCS1,
2438 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002439 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002440 // -- S1 and S2 differ only in their qualification conversion and
2441 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2442 // cv-qualification signature of type T1 is a proper subset of
2443 // the cv-qualification signature of type T2, and S1 is not the
2444 // deprecated string literal array-to-pointer conversion (4.2).
2445 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2446 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2447 return ImplicitConversionSequence::Indistinguishable;
2448
2449 // FIXME: the example in the standard doesn't use a qualification
2450 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002451 QualType T1 = SCS1.getToType(2);
2452 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002453 T1 = S.Context.getCanonicalType(T1);
2454 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002455 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002456 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2457 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002458
2459 // If the types are the same, we won't learn anything by unwrapped
2460 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002461 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002462 return ImplicitConversionSequence::Indistinguishable;
2463
Chandler Carruth607f38e2009-12-29 07:16:59 +00002464 // If the type is an array type, promote the element qualifiers to the type
2465 // for comparison.
2466 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002467 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002468 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002469 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002470
Mike Stump11289f42009-09-09 15:08:12 +00002471 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002472 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002473 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002474 // Within each iteration of the loop, we check the qualifiers to
2475 // determine if this still looks like a qualification
2476 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002477 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002478 // until there are no more pointers or pointers-to-members left
2479 // to unwrap. This essentially mimics what
2480 // IsQualificationConversion does, but here we're checking for a
2481 // strict subset of qualifiers.
2482 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2483 // The qualifiers are the same, so this doesn't tell us anything
2484 // about how the sequences rank.
2485 ;
2486 else if (T2.isMoreQualifiedThan(T1)) {
2487 // T1 has fewer qualifiers, so it could be the better sequence.
2488 if (Result == ImplicitConversionSequence::Worse)
2489 // Neither has qualifiers that are a subset of the other's
2490 // qualifiers.
2491 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002493 Result = ImplicitConversionSequence::Better;
2494 } else if (T1.isMoreQualifiedThan(T2)) {
2495 // T2 has fewer qualifiers, so it could be the better sequence.
2496 if (Result == ImplicitConversionSequence::Better)
2497 // Neither has qualifiers that are a subset of the other's
2498 // qualifiers.
2499 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002500
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002501 Result = ImplicitConversionSequence::Worse;
2502 } else {
2503 // Qualifiers are disjoint.
2504 return ImplicitConversionSequence::Indistinguishable;
2505 }
2506
2507 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002508 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002509 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002510 }
2511
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002512 // Check that the winning standard conversion sequence isn't using
2513 // the deprecated string literal array to pointer conversion.
2514 switch (Result) {
2515 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002516 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002517 Result = ImplicitConversionSequence::Indistinguishable;
2518 break;
2519
2520 case ImplicitConversionSequence::Indistinguishable:
2521 break;
2522
2523 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002524 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002525 Result = ImplicitConversionSequence::Indistinguishable;
2526 break;
2527 }
2528
2529 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002530}
2531
Douglas Gregor5c407d92008-10-23 00:40:37 +00002532/// CompareDerivedToBaseConversions - Compares two standard conversion
2533/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002534/// various kinds of derived-to-base conversions (C++
2535/// [over.ics.rank]p4b3). As part of these checks, we also look at
2536/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002537ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002538CompareDerivedToBaseConversions(Sema &S,
2539 const StandardConversionSequence& SCS1,
2540 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002541 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002542 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002543 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002544 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002545
2546 // Adjust the types we're converting from via the array-to-pointer
2547 // conversion, if we need to.
2548 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002549 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002550 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002551 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002552
2553 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002554 FromType1 = S.Context.getCanonicalType(FromType1);
2555 ToType1 = S.Context.getCanonicalType(ToType1);
2556 FromType2 = S.Context.getCanonicalType(FromType2);
2557 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002558
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002559 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002560 //
2561 // If class B is derived directly or indirectly from class A and
2562 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002563 //
2564 // For Objective-C, we let A, B, and C also be Objective-C
2565 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002566
2567 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002568 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002569 SCS2.Second == ICK_Pointer_Conversion &&
2570 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2571 FromType1->isPointerType() && FromType2->isPointerType() &&
2572 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002573 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002574 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002575 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002576 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002577 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002578 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002579 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002580 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002581
John McCall8b07ec22010-05-15 11:32:37 +00002582 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2583 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2584 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2585 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002586
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002587 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002588 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002589 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002590 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002591 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002592 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002593
2594 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002595 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002596 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002597 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002598 return ImplicitConversionSequence::Worse;
2599 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002600 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002601
2602 // -- conversion of B* to A* is better than conversion of C* to A*,
2603 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002604 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002605 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002606 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002607 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002608
Douglas Gregor237f96c2008-11-26 23:31:11 +00002609 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002610 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002611 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002612 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002613 return ImplicitConversionSequence::Worse;
2614 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002615 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002616 }
2617
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002618 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002619 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2620 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2621 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2622 const MemberPointerType * FromMemPointer1 =
2623 FromType1->getAs<MemberPointerType>();
2624 const MemberPointerType * ToMemPointer1 =
2625 ToType1->getAs<MemberPointerType>();
2626 const MemberPointerType * FromMemPointer2 =
2627 FromType2->getAs<MemberPointerType>();
2628 const MemberPointerType * ToMemPointer2 =
2629 ToType2->getAs<MemberPointerType>();
2630 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2631 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2632 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2633 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2634 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2635 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2636 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2637 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002638 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002639 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002640 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002641 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002642 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002643 return ImplicitConversionSequence::Better;
2644 }
2645 // conversion of B::* to C::* is better than conversion of A::* to C::*
2646 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002647 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002648 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002649 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002650 return ImplicitConversionSequence::Worse;
2651 }
2652 }
2653
Douglas Gregor5ab11652010-04-17 22:01:05 +00002654 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002655 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002656 // -- binding of an expression of type C to a reference of type
2657 // B& is better than binding an expression of type C to a
2658 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002659 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2660 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2661 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002662 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002663 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002664 return ImplicitConversionSequence::Worse;
2665 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002666
Douglas Gregor2fe98832008-11-03 19:09:14 +00002667 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002668 // -- binding of an expression of type B to a reference of type
2669 // A& is better than binding an expression of type C to a
2670 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002671 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2672 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2673 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002674 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002675 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002676 return ImplicitConversionSequence::Worse;
2677 }
2678 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002679
Douglas Gregor5c407d92008-10-23 00:40:37 +00002680 return ImplicitConversionSequence::Indistinguishable;
2681}
2682
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002683/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2684/// determine whether they are reference-related,
2685/// reference-compatible, reference-compatible with added
2686/// qualification, or incompatible, for use in C++ initialization by
2687/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2688/// type, and the first type (T1) is the pointee type of the reference
2689/// type being initialized.
2690Sema::ReferenceCompareResult
2691Sema::CompareReferenceRelationship(SourceLocation Loc,
2692 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002693 bool &DerivedToBase,
2694 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002695 assert(!OrigT1->isReferenceType() &&
2696 "T1 must be the pointee type of the reference type");
2697 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2698
2699 QualType T1 = Context.getCanonicalType(OrigT1);
2700 QualType T2 = Context.getCanonicalType(OrigT2);
2701 Qualifiers T1Quals, T2Quals;
2702 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2703 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2704
2705 // C++ [dcl.init.ref]p4:
2706 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2707 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2708 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002709 DerivedToBase = false;
2710 ObjCConversion = false;
2711 if (UnqualT1 == UnqualT2) {
2712 // Nothing to do.
2713 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002714 IsDerivedFrom(UnqualT2, UnqualT1))
2715 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002716 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2717 UnqualT2->isObjCObjectOrInterfaceType() &&
2718 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2719 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002720 else
2721 return Ref_Incompatible;
2722
2723 // At this point, we know that T1 and T2 are reference-related (at
2724 // least).
2725
2726 // If the type is an array type, promote the element qualifiers to the type
2727 // for comparison.
2728 if (isa<ArrayType>(T1) && T1Quals)
2729 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2730 if (isa<ArrayType>(T2) && T2Quals)
2731 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2732
2733 // C++ [dcl.init.ref]p4:
2734 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2735 // reference-related to T2 and cv1 is the same cv-qualification
2736 // as, or greater cv-qualification than, cv2. For purposes of
2737 // overload resolution, cases for which cv1 is greater
2738 // cv-qualification than cv2 are identified as
2739 // reference-compatible with added qualification (see 13.3.3.2).
2740 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2741 return Ref_Compatible;
2742 else if (T1.isMoreQualifiedThan(T2))
2743 return Ref_Compatible_With_Added_Qualification;
2744 else
2745 return Ref_Related;
2746}
2747
Douglas Gregor836a7e82010-08-11 02:15:33 +00002748/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002749/// with DeclType. Return true if something definite is found.
2750static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002751FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2752 QualType DeclType, SourceLocation DeclLoc,
2753 Expr *Init, QualType T2, bool AllowRvalues,
2754 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002755 assert(T2->isRecordType() && "Can only find conversions of record types.");
2756 CXXRecordDecl *T2RecordDecl
2757 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2758
Douglas Gregor836a7e82010-08-11 02:15:33 +00002759 QualType ToType
2760 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2761 : DeclType;
2762
Sebastian Redld92badf2010-06-30 18:13:39 +00002763 OverloadCandidateSet CandidateSet(DeclLoc);
2764 const UnresolvedSetImpl *Conversions
2765 = T2RecordDecl->getVisibleConversionFunctions();
2766 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2767 E = Conversions->end(); I != E; ++I) {
2768 NamedDecl *D = *I;
2769 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2770 if (isa<UsingShadowDecl>(D))
2771 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2772
2773 FunctionTemplateDecl *ConvTemplate
2774 = dyn_cast<FunctionTemplateDecl>(D);
2775 CXXConversionDecl *Conv;
2776 if (ConvTemplate)
2777 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2778 else
2779 Conv = cast<CXXConversionDecl>(D);
2780
Douglas Gregor836a7e82010-08-11 02:15:33 +00002781 // If this is an explicit conversion, and we're not allowed to consider
2782 // explicit conversions, skip it.
2783 if (!AllowExplicit && Conv->isExplicit())
2784 continue;
2785
2786 if (AllowRvalues) {
2787 bool DerivedToBase = false;
2788 bool ObjCConversion = false;
2789 if (!ConvTemplate &&
2790 S.CompareReferenceRelationship(DeclLoc,
2791 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2792 DeclType.getNonReferenceType().getUnqualifiedType(),
2793 DerivedToBase, ObjCConversion)
2794 == Sema::Ref_Incompatible)
2795 continue;
2796 } else {
2797 // If the conversion function doesn't return a reference type,
2798 // it can't be considered for this conversion. An rvalue reference
2799 // is only acceptable if its referencee is a function type.
2800
2801 const ReferenceType *RefType =
2802 Conv->getConversionType()->getAs<ReferenceType>();
2803 if (!RefType ||
2804 (!RefType->isLValueReferenceType() &&
2805 !RefType->getPointeeType()->isFunctionType()))
2806 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002807 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002808
2809 if (ConvTemplate)
2810 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2811 Init, ToType, CandidateSet);
2812 else
2813 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2814 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002815 }
2816
2817 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002818 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002819 case OR_Success:
2820 // C++ [over.ics.ref]p1:
2821 //
2822 // [...] If the parameter binds directly to the result of
2823 // applying a conversion function to the argument
2824 // expression, the implicit conversion sequence is a
2825 // user-defined conversion sequence (13.3.3.1.2), with the
2826 // second standard conversion sequence either an identity
2827 // conversion or, if the conversion function returns an
2828 // entity of a type that is a derived class of the parameter
2829 // type, a derived-to-base Conversion.
2830 if (!Best->FinalConversion.DirectBinding)
2831 return false;
2832
2833 ICS.setUserDefined();
2834 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2835 ICS.UserDefined.After = Best->FinalConversion;
2836 ICS.UserDefined.ConversionFunction = Best->Function;
2837 ICS.UserDefined.EllipsisConversion = false;
2838 assert(ICS.UserDefined.After.ReferenceBinding &&
2839 ICS.UserDefined.After.DirectBinding &&
2840 "Expected a direct reference binding!");
2841 return true;
2842
2843 case OR_Ambiguous:
2844 ICS.setAmbiguous();
2845 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2846 Cand != CandidateSet.end(); ++Cand)
2847 if (Cand->Viable)
2848 ICS.Ambiguous.addConversion(Cand->Function);
2849 return true;
2850
2851 case OR_No_Viable_Function:
2852 case OR_Deleted:
2853 // There was no suitable conversion, or we found a deleted
2854 // conversion; continue with other checks.
2855 return false;
2856 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002857
2858 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002859}
2860
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002861/// \brief Compute an implicit conversion sequence for reference
2862/// initialization.
2863static ImplicitConversionSequence
2864TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2865 SourceLocation DeclLoc,
2866 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002867 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002868 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2869
2870 // Most paths end in a failed conversion.
2871 ImplicitConversionSequence ICS;
2872 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2873
2874 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2875 QualType T2 = Init->getType();
2876
2877 // If the initializer is the address of an overloaded function, try
2878 // to resolve the overloaded function. If all goes well, T2 is the
2879 // type of the resulting function.
2880 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2881 DeclAccessPair Found;
2882 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2883 false, Found))
2884 T2 = Fn->getType();
2885 }
2886
2887 // Compute some basic properties of the types and the initializer.
2888 bool isRValRef = DeclType->isRValueReferenceType();
2889 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002890 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002891 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002892 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002893 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2894 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002895
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002896
Sebastian Redld92badf2010-06-30 18:13:39 +00002897 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002898 // A reference to type "cv1 T1" is initialized by an expression
2899 // of type "cv2 T2" as follows:
2900
Sebastian Redld92badf2010-06-30 18:13:39 +00002901 // -- If reference is an lvalue reference and the initializer expression
2902 // The next bullet point (T1 is a function) is pretty much equivalent to this
2903 // one, so it's handled here.
2904 if (!isRValRef || T1->isFunctionType()) {
2905 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2906 // reference-compatible with "cv2 T2," or
2907 //
2908 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2909 if (InitCategory.isLValue() &&
2910 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002911 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002912 // When a parameter of reference type binds directly (8.5.3)
2913 // to an argument expression, the implicit conversion sequence
2914 // is the identity conversion, unless the argument expression
2915 // has a type that is a derived class of the parameter type,
2916 // in which case the implicit conversion sequence is a
2917 // derived-to-base Conversion (13.3.3.1).
2918 ICS.setStandard();
2919 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002920 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2921 : ObjCConversion? ICK_Compatible_Conversion
2922 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002923 ICS.Standard.Third = ICK_Identity;
2924 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2925 ICS.Standard.setToType(0, T2);
2926 ICS.Standard.setToType(1, T1);
2927 ICS.Standard.setToType(2, T1);
2928 ICS.Standard.ReferenceBinding = true;
2929 ICS.Standard.DirectBinding = true;
2930 ICS.Standard.RRefBinding = isRValRef;
2931 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002932
Sebastian Redld92badf2010-06-30 18:13:39 +00002933 // Nothing more to do: the inaccessibility/ambiguity check for
2934 // derived-to-base conversions is suppressed when we're
2935 // computing the implicit conversion sequence (C++
2936 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002937 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002938 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002939
Sebastian Redld92badf2010-06-30 18:13:39 +00002940 // -- has a class type (i.e., T2 is a class type), where T1 is
2941 // not reference-related to T2, and can be implicitly
2942 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2943 // is reference-compatible with "cv3 T3" 92) (this
2944 // conversion is selected by enumerating the applicable
2945 // conversion functions (13.3.1.6) and choosing the best
2946 // one through overload resolution (13.3)),
2947 if (!SuppressUserConversions && T2->isRecordType() &&
2948 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2949 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002950 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2951 Init, T2, /*AllowRvalues=*/false,
2952 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002953 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002954 }
2955 }
2956
Sebastian Redld92badf2010-06-30 18:13:39 +00002957 // -- Otherwise, the reference shall be an lvalue reference to a
2958 // non-volatile const type (i.e., cv1 shall be const), or the reference
2959 // shall be an rvalue reference and the initializer expression shall be
2960 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002961 //
2962 // We actually handle one oddity of C++ [over.ics.ref] at this
2963 // point, which is that, due to p2 (which short-circuits reference
2964 // binding by only attempting a simple conversion for non-direct
2965 // bindings) and p3's strange wording, we allow a const volatile
2966 // reference to bind to an rvalue. Hence the check for the presence
2967 // of "const" rather than checking for "const" being the only
2968 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002969 // This is also the point where rvalue references and lvalue inits no longer
2970 // go together.
2971 if ((!isRValRef && !T1.isConstQualified()) ||
2972 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002973 return ICS;
2974
Sebastian Redld92badf2010-06-30 18:13:39 +00002975 // -- If T1 is a function type, then
2976 // -- if T2 is the same type as T1, the reference is bound to the
2977 // initializer expression lvalue;
2978 // -- if T2 is a class type and the initializer expression can be
2979 // implicitly converted to an lvalue of type T1 [...], the
2980 // reference is bound to the function lvalue that is the result
2981 // of the conversion;
2982 // This is the same as for the lvalue case above, so it was handled there.
2983 // -- otherwise, the program is ill-formed.
2984 // This is the one difference to the lvalue case.
2985 if (T1->isFunctionType())
2986 return ICS;
2987
2988 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002989 // -- the initializer expression is an rvalue and "cv1 T1"
2990 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002991 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002992 // -- T1 is not reference-related to T2 and the initializer
2993 // expression can be implicitly converted to an rvalue
2994 // of type "cv3 T3" (this conversion is selected by
2995 // enumerating the applicable conversion functions
2996 // (13.3.1.6) and choosing the best one through overload
2997 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002998 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002999 // then the reference is bound to the initializer
3000 // expression rvalue in the first case and to the object
3001 // that is the result of the conversion in the second case
3002 // (or, in either case, to the appropriate base class
3003 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00003004 if (T2->isRecordType()) {
3005 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3006 // direct binding in C++0x but not in C++03.
3007 if (InitCategory.isRValue() &&
3008 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3009 ICS.setStandard();
3010 ICS.Standard.First = ICK_Identity;
3011 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3012 : ObjCConversion? ICK_Compatible_Conversion
3013 : ICK_Identity;
3014 ICS.Standard.Third = ICK_Identity;
3015 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3016 ICS.Standard.setToType(0, T2);
3017 ICS.Standard.setToType(1, T1);
3018 ICS.Standard.setToType(2, T1);
3019 ICS.Standard.ReferenceBinding = true;
3020 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3021 ICS.Standard.RRefBinding = isRValRef;
3022 ICS.Standard.CopyConstructor = 0;
3023 return ICS;
3024 }
3025
3026 // Second case: not reference-related.
3027 if (RefRelationship == Sema::Ref_Incompatible &&
3028 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3029 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3030 Init, T2, /*AllowRvalues=*/true,
3031 AllowExplicit))
3032 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003033 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003034
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003035 // -- Otherwise, a temporary of type "cv1 T1" is created and
3036 // initialized from the initializer expression using the
3037 // rules for a non-reference copy initialization (8.5). The
3038 // reference is then bound to the temporary. If T1 is
3039 // reference-related to T2, cv1 must be the same
3040 // cv-qualification as, or greater cv-qualification than,
3041 // cv2; otherwise, the program is ill-formed.
3042 if (RefRelationship == Sema::Ref_Related) {
3043 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3044 // we would be reference-compatible or reference-compatible with
3045 // added qualification. But that wasn't the case, so the reference
3046 // initialization fails.
3047 return ICS;
3048 }
3049
3050 // If at least one of the types is a class type, the types are not
3051 // related, and we aren't allowed any user conversions, the
3052 // reference binding fails. This case is important for breaking
3053 // recursion, since TryImplicitConversion below will attempt to
3054 // create a temporary through the use of a copy constructor.
3055 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3056 (T1->isRecordType() || T2->isRecordType()))
3057 return ICS;
3058
3059 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003060 // When a parameter of reference type is not bound directly to
3061 // an argument expression, the conversion sequence is the one
3062 // required to convert the argument expression to the
3063 // underlying type of the reference according to
3064 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3065 // to copy-initializing a temporary of the underlying type with
3066 // the argument expression. Any difference in top-level
3067 // cv-qualification is subsumed by the initialization itself
3068 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003069 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3070 /*AllowExplicit=*/false,
3071 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003072
3073 // Of course, that's still a reference binding.
3074 if (ICS.isStandard()) {
3075 ICS.Standard.ReferenceBinding = true;
3076 ICS.Standard.RRefBinding = isRValRef;
3077 } else if (ICS.isUserDefined()) {
3078 ICS.UserDefined.After.ReferenceBinding = true;
3079 ICS.UserDefined.After.RRefBinding = isRValRef;
3080 }
3081 return ICS;
3082}
3083
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003084/// TryCopyInitialization - Try to copy-initialize a value of type
3085/// ToType from the expression From. Return the implicit conversion
3086/// sequence required to pass this argument, which may be a bad
3087/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003088/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003089/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003090static ImplicitConversionSequence
3091TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003092 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003093 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003094 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003095 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003096 /*FIXME:*/From->getLocStart(),
3097 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003098 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003099
John McCall5c32be02010-08-24 20:38:10 +00003100 return TryImplicitConversion(S, From, ToType,
3101 SuppressUserConversions,
3102 /*AllowExplicit=*/false,
3103 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003104}
3105
Douglas Gregor436424c2008-11-18 23:14:02 +00003106/// TryObjectArgumentInitialization - Try to initialize the object
3107/// parameter of the given member function (@c Method) from the
3108/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003109static ImplicitConversionSequence
3110TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3111 CXXMethodDecl *Method,
3112 CXXRecordDecl *ActingContext) {
3113 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003114 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3115 // const volatile object.
3116 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3117 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003118 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003119
3120 // Set up the conversion sequence as a "bad" conversion, to allow us
3121 // to exit early.
3122 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003123
3124 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003125 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003126 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003127 FromType = PT->getPointeeType();
3128
3129 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003130
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003131 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003132 // where X is the class of which the function is a member
3133 // (C++ [over.match.funcs]p4). However, when finding an implicit
3134 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003135 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003136 // (C++ [over.match.funcs]p5). We perform a simplified version of
3137 // reference binding here, that allows class rvalues to bind to
3138 // non-constant references.
3139
3140 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3141 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003142 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003143 if (ImplicitParamType.getCVRQualifiers()
3144 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003145 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003146 ICS.setBad(BadConversionSequence::bad_qualifiers,
3147 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003148 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003149 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003150
3151 // Check that we have either the same type or a derived type. It
3152 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003153 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003154 ImplicitConversionKind SecondKind;
3155 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3156 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003157 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003158 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003159 else {
John McCall65eb8792010-02-25 01:37:24 +00003160 ICS.setBad(BadConversionSequence::unrelated_class,
3161 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003162 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003163 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003164
3165 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003166 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003167 ICS.Standard.setAsIdentityConversion();
3168 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003169 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003170 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003171 ICS.Standard.ReferenceBinding = true;
3172 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003173 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003174 return ICS;
3175}
3176
3177/// PerformObjectArgumentInitialization - Perform initialization of
3178/// the implicit object parameter for the given Method with the given
3179/// expression.
3180bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003181Sema::PerformObjectArgumentInitialization(Expr *&From,
3182 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003183 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003184 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003185 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003186 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003187 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003188
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003189 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003190 FromRecordType = PT->getPointeeType();
3191 DestType = Method->getThisType(Context);
3192 } else {
3193 FromRecordType = From->getType();
3194 DestType = ImplicitParamRecordType;
3195 }
3196
John McCall6e9f8f62009-12-03 04:06:58 +00003197 // Note that we always use the true parent context when performing
3198 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003199 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003200 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003201 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003202 if (ICS.isBad()) {
3203 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3204 Qualifiers FromQs = FromRecordType.getQualifiers();
3205 Qualifiers ToQs = DestType.getQualifiers();
3206 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3207 if (CVR) {
3208 Diag(From->getSourceRange().getBegin(),
3209 diag::err_member_function_call_bad_cvr)
3210 << Method->getDeclName() << FromRecordType << (CVR - 1)
3211 << From->getSourceRange();
3212 Diag(Method->getLocation(), diag::note_previous_decl)
3213 << Method->getDeclName();
3214 return true;
3215 }
3216 }
3217
Douglas Gregor436424c2008-11-18 23:14:02 +00003218 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003219 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003220 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003221 }
Mike Stump11289f42009-09-09 15:08:12 +00003222
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003223 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003224 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003225
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003226 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003227 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003228 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003229 return false;
3230}
3231
Douglas Gregor5fb53972009-01-14 15:45:31 +00003232/// TryContextuallyConvertToBool - Attempt to contextually convert the
3233/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003234static ImplicitConversionSequence
3235TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003236 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003237 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003238 // FIXME: Are these flags correct?
3239 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003240 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003241 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003242}
3243
3244/// PerformContextuallyConvertToBool - Perform a contextual conversion
3245/// of the expression From to bool (C++0x [conv]p3).
3246bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003247 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003248 if (!ICS.isBad())
3249 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003250
Fariborz Jahanian76197412009-11-18 18:26:29 +00003251 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003252 return Diag(From->getSourceRange().getBegin(),
3253 diag::err_typecheck_bool_condition)
3254 << From->getType() << From->getSourceRange();
3255 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003256}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003257
3258/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3259/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003260static ImplicitConversionSequence
3261TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3262 QualType Ty = S.Context.getObjCIdType();
3263 return TryImplicitConversion(S, From, Ty,
3264 // FIXME: Are these flags correct?
3265 /*SuppressUserConversions=*/false,
3266 /*AllowExplicit=*/true,
3267 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003268}
John McCall5c32be02010-08-24 20:38:10 +00003269
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003270/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3271/// of the expression From to 'id'.
3272bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003273 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003274 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003275 if (!ICS.isBad())
3276 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3277 return true;
3278}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003279
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003280/// \brief Attempt to convert the given expression to an integral or
3281/// enumeration type.
3282///
3283/// This routine will attempt to convert an expression of class type to an
3284/// integral or enumeration type, if that class type only has a single
3285/// conversion to an integral or enumeration type.
3286///
Douglas Gregor4799d032010-06-30 00:20:43 +00003287/// \param Loc The source location of the construct that requires the
3288/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003289///
Douglas Gregor4799d032010-06-30 00:20:43 +00003290/// \param FromE The expression we're converting from.
3291///
3292/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3293/// have integral or enumeration type.
3294///
3295/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3296/// incomplete class type.
3297///
3298/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3299/// explicit conversion function (because no implicit conversion functions
3300/// were available). This is a recovery mode.
3301///
3302/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3303/// showing which conversion was picked.
3304///
3305/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3306/// conversion function that could convert to integral or enumeration type.
3307///
3308/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3309/// usable conversion function.
3310///
3311/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3312/// function, which may be an extension in this case.
3313///
3314/// \returns The expression, converted to an integral or enumeration type if
3315/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003316ExprResult
John McCallb268a282010-08-23 23:25:46 +00003317Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003318 const PartialDiagnostic &NotIntDiag,
3319 const PartialDiagnostic &IncompleteDiag,
3320 const PartialDiagnostic &ExplicitConvDiag,
3321 const PartialDiagnostic &ExplicitConvNote,
3322 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003323 const PartialDiagnostic &AmbigNote,
3324 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003325 // We can't perform any more checking for type-dependent expressions.
3326 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003327 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003328
3329 // If the expression already has integral or enumeration type, we're golden.
3330 QualType T = From->getType();
3331 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003332 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003333
3334 // FIXME: Check for missing '()' if T is a function type?
3335
3336 // If we don't have a class type in C++, there's no way we can get an
3337 // expression of integral or enumeration type.
3338 const RecordType *RecordTy = T->getAs<RecordType>();
3339 if (!RecordTy || !getLangOptions().CPlusPlus) {
3340 Diag(Loc, NotIntDiag)
3341 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003342 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003343 }
3344
3345 // We must have a complete class type.
3346 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003347 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003348
3349 // Look for a conversion to an integral or enumeration type.
3350 UnresolvedSet<4> ViableConversions;
3351 UnresolvedSet<4> ExplicitConversions;
3352 const UnresolvedSetImpl *Conversions
3353 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3354
3355 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3356 E = Conversions->end();
3357 I != E;
3358 ++I) {
3359 if (CXXConversionDecl *Conversion
3360 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3361 if (Conversion->getConversionType().getNonReferenceType()
3362 ->isIntegralOrEnumerationType()) {
3363 if (Conversion->isExplicit())
3364 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3365 else
3366 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3367 }
3368 }
3369
3370 switch (ViableConversions.size()) {
3371 case 0:
3372 if (ExplicitConversions.size() == 1) {
3373 DeclAccessPair Found = ExplicitConversions[0];
3374 CXXConversionDecl *Conversion
3375 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3376
3377 // The user probably meant to invoke the given explicit
3378 // conversion; use it.
3379 QualType ConvTy
3380 = Conversion->getConversionType().getNonReferenceType();
3381 std::string TypeStr;
3382 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3383
3384 Diag(Loc, ExplicitConvDiag)
3385 << T << ConvTy
3386 << FixItHint::CreateInsertion(From->getLocStart(),
3387 "static_cast<" + TypeStr + ">(")
3388 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3389 ")");
3390 Diag(Conversion->getLocation(), ExplicitConvNote)
3391 << ConvTy->isEnumeralType() << ConvTy;
3392
3393 // If we aren't in a SFINAE context, build a call to the
3394 // explicit conversion function.
3395 if (isSFINAEContext())
3396 return ExprError();
3397
3398 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003399 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003400 }
3401
3402 // We'll complain below about a non-integral condition type.
3403 break;
3404
3405 case 1: {
3406 // Apply this conversion.
3407 DeclAccessPair Found = ViableConversions[0];
3408 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003409
3410 CXXConversionDecl *Conversion
3411 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3412 QualType ConvTy
3413 = Conversion->getConversionType().getNonReferenceType();
3414 if (ConvDiag.getDiagID()) {
3415 if (isSFINAEContext())
3416 return ExprError();
3417
3418 Diag(Loc, ConvDiag)
3419 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3420 }
3421
John McCallb268a282010-08-23 23:25:46 +00003422 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003423 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003424 break;
3425 }
3426
3427 default:
3428 Diag(Loc, AmbigDiag)
3429 << T << From->getSourceRange();
3430 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3431 CXXConversionDecl *Conv
3432 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3433 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3434 Diag(Conv->getLocation(), AmbigNote)
3435 << ConvTy->isEnumeralType() << ConvTy;
3436 }
John McCallb268a282010-08-23 23:25:46 +00003437 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003438 }
3439
Douglas Gregor5823da32010-06-29 23:25:20 +00003440 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003441 Diag(Loc, NotIntDiag)
3442 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003443
John McCallb268a282010-08-23 23:25:46 +00003444 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003445}
3446
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003447/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003448/// candidate functions, using the given function call arguments. If
3449/// @p SuppressUserConversions, then don't allow user-defined
3450/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003451///
3452/// \para PartialOverloading true if we are performing "partial" overloading
3453/// based on an incomplete set of function arguments. This feature is used by
3454/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003455void
3456Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003457 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003458 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003459 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003460 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003461 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003462 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003463 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003464 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003465 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003466 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003467
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003469 if (!isa<CXXConstructorDecl>(Method)) {
3470 // If we get here, it's because we're calling a member function
3471 // that is named without a member access expression (e.g.,
3472 // "this->f") that was either written explicitly or created
3473 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003474 // function, e.g., X::f(). We use an empty type for the implied
3475 // object argument (C++ [over.call.func]p3), and the acting context
3476 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003477 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003478 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003479 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003480 return;
3481 }
3482 // We treat a constructor like a non-member function, since its object
3483 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003484 }
3485
Douglas Gregorff7028a2009-11-13 23:59:09 +00003486 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003487 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003488
Douglas Gregor27381f32009-11-23 12:27:39 +00003489 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003490 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003491
Douglas Gregorffe14e32009-11-14 01:20:54 +00003492 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3493 // C++ [class.copy]p3:
3494 // A member function template is never instantiated to perform the copy
3495 // of a class object to an object of its class type.
3496 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3497 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003498 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003499 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3500 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003501 return;
3502 }
3503
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003504 // Add this candidate
3505 CandidateSet.push_back(OverloadCandidate());
3506 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003507 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003508 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003509 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003510 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003511 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003512
3513 unsigned NumArgsInProto = Proto->getNumArgs();
3514
3515 // (C++ 13.3.2p2): A candidate function having fewer than m
3516 // parameters is viable only if it has an ellipsis in its parameter
3517 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003518 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3519 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003520 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003521 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003522 return;
3523 }
3524
3525 // (C++ 13.3.2p2): A candidate function having more than m parameters
3526 // is viable only if the (m+1)st parameter has a default argument
3527 // (8.3.6). For the purposes of overload resolution, the
3528 // parameter list is truncated on the right, so that there are
3529 // exactly m parameters.
3530 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003531 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003532 // Not enough arguments.
3533 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003534 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003535 return;
3536 }
3537
3538 // Determine the implicit conversion sequences for each of the
3539 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003540 Candidate.Conversions.resize(NumArgs);
3541 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3542 if (ArgIdx < NumArgsInProto) {
3543 // (C++ 13.3.2p3): for F to be a viable function, there shall
3544 // exist for each argument an implicit conversion sequence
3545 // (13.3.3.1) that converts that argument to the corresponding
3546 // parameter of F.
3547 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003548 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003549 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003550 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003551 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003552 if (Candidate.Conversions[ArgIdx].isBad()) {
3553 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003554 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003555 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003556 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003557 } else {
3558 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3559 // argument for which there is no corresponding parameter is
3560 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003561 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003562 }
3563 }
3564}
3565
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003566/// \brief Add all of the function declarations in the given function set to
3567/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003568void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003569 Expr **Args, unsigned NumArgs,
3570 OverloadCandidateSet& CandidateSet,
3571 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003572 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003573 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3574 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003575 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003576 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003577 cast<CXXMethodDecl>(FD)->getParent(),
3578 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003579 CandidateSet, SuppressUserConversions);
3580 else
John McCalla0296f72010-03-19 07:35:19 +00003581 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003582 SuppressUserConversions);
3583 } else {
John McCalla0296f72010-03-19 07:35:19 +00003584 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003585 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3586 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003587 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003588 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003589 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003590 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003591 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003592 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003593 else
John McCalla0296f72010-03-19 07:35:19 +00003594 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003595 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003596 Args, NumArgs, CandidateSet,
3597 SuppressUserConversions);
3598 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003599 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003600}
3601
John McCallf0f1cf02009-11-17 07:50:12 +00003602/// AddMethodCandidate - Adds a named decl (which is some kind of
3603/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003604void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003605 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003606 Expr **Args, unsigned NumArgs,
3607 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003608 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003609 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003610 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003611
3612 if (isa<UsingShadowDecl>(Decl))
3613 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3614
3615 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3616 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3617 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003618 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3619 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003620 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003621 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003622 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003623 } else {
John McCalla0296f72010-03-19 07:35:19 +00003624 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003625 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003626 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003627 }
3628}
3629
Douglas Gregor436424c2008-11-18 23:14:02 +00003630/// AddMethodCandidate - Adds the given C++ member function to the set
3631/// of candidate functions, using the given function call arguments
3632/// and the object argument (@c Object). For example, in a call
3633/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3634/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3635/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003636/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003637void
John McCalla0296f72010-03-19 07:35:19 +00003638Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003639 CXXRecordDecl *ActingContext, QualType ObjectType,
3640 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003641 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003642 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003643 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003644 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003645 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003646 assert(!isa<CXXConstructorDecl>(Method) &&
3647 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003648
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003649 if (!CandidateSet.isNewCandidate(Method))
3650 return;
3651
Douglas Gregor27381f32009-11-23 12:27:39 +00003652 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003653 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003654
Douglas Gregor436424c2008-11-18 23:14:02 +00003655 // Add this candidate
3656 CandidateSet.push_back(OverloadCandidate());
3657 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003658 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003659 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003660 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003661 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003662
3663 unsigned NumArgsInProto = Proto->getNumArgs();
3664
3665 // (C++ 13.3.2p2): A candidate function having fewer than m
3666 // parameters is viable only if it has an ellipsis in its parameter
3667 // list (8.3.5).
3668 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3669 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003670 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003671 return;
3672 }
3673
3674 // (C++ 13.3.2p2): A candidate function having more than m parameters
3675 // is viable only if the (m+1)st parameter has a default argument
3676 // (8.3.6). For the purposes of overload resolution, the
3677 // parameter list is truncated on the right, so that there are
3678 // exactly m parameters.
3679 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3680 if (NumArgs < MinRequiredArgs) {
3681 // Not enough arguments.
3682 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003683 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003684 return;
3685 }
3686
3687 Candidate.Viable = true;
3688 Candidate.Conversions.resize(NumArgs + 1);
3689
John McCall6e9f8f62009-12-03 04:06:58 +00003690 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003691 // The implicit object argument is ignored.
3692 Candidate.IgnoreObjectArgument = true;
3693 else {
3694 // Determine the implicit conversion sequence for the object
3695 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003696 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003697 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3698 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003699 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003700 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003701 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003702 return;
3703 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003704 }
3705
3706 // Determine the implicit conversion sequences for each of the
3707 // arguments.
3708 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3709 if (ArgIdx < NumArgsInProto) {
3710 // (C++ 13.3.2p3): for F to be a viable function, there shall
3711 // exist for each argument an implicit conversion sequence
3712 // (13.3.3.1) that converts that argument to the corresponding
3713 // parameter of F.
3714 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003715 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003716 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003717 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003718 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003719 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003720 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003721 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003722 break;
3723 }
3724 } else {
3725 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3726 // argument for which there is no corresponding parameter is
3727 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003728 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003729 }
3730 }
3731}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003732
Douglas Gregor97628d62009-08-21 00:16:32 +00003733/// \brief Add a C++ member function template as a candidate to the candidate
3734/// set, using template argument deduction to produce an appropriate member
3735/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003736void
Douglas Gregor97628d62009-08-21 00:16:32 +00003737Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003738 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003739 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003740 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003741 QualType ObjectType,
3742 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003743 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003744 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003745 if (!CandidateSet.isNewCandidate(MethodTmpl))
3746 return;
3747
Douglas Gregor97628d62009-08-21 00:16:32 +00003748 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003749 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003750 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003751 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003752 // candidate functions in the usual way.113) A given name can refer to one
3753 // or more function templates and also to a set of overloaded non-template
3754 // functions. In such a case, the candidate functions generated from each
3755 // function template are combined with the set of non-template candidate
3756 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003757 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003758 FunctionDecl *Specialization = 0;
3759 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003760 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003761 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003762 CandidateSet.push_back(OverloadCandidate());
3763 OverloadCandidate &Candidate = CandidateSet.back();
3764 Candidate.FoundDecl = FoundDecl;
3765 Candidate.Function = MethodTmpl->getTemplatedDecl();
3766 Candidate.Viable = false;
3767 Candidate.FailureKind = ovl_fail_bad_deduction;
3768 Candidate.IsSurrogate = false;
3769 Candidate.IgnoreObjectArgument = false;
3770 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3771 Info);
3772 return;
3773 }
Mike Stump11289f42009-09-09 15:08:12 +00003774
Douglas Gregor97628d62009-08-21 00:16:32 +00003775 // Add the function template specialization produced by template argument
3776 // deduction as a candidate.
3777 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003778 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003779 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003780 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003781 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003782 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003783}
3784
Douglas Gregor05155d82009-08-21 23:19:43 +00003785/// \brief Add a C++ function template specialization as a candidate
3786/// in the candidate set, using template argument deduction to produce
3787/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003788void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003789Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003790 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003791 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003792 Expr **Args, unsigned NumArgs,
3793 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003794 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003795 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3796 return;
3797
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003798 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003799 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003800 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003801 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003802 // candidate functions in the usual way.113) A given name can refer to one
3803 // or more function templates and also to a set of overloaded non-template
3804 // functions. In such a case, the candidate functions generated from each
3805 // function template are combined with the set of non-template candidate
3806 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003807 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003808 FunctionDecl *Specialization = 0;
3809 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003810 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003811 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003812 CandidateSet.push_back(OverloadCandidate());
3813 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003814 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003815 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3816 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003817 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003818 Candidate.IsSurrogate = false;
3819 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003820 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3821 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003822 return;
3823 }
Mike Stump11289f42009-09-09 15:08:12 +00003824
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003825 // Add the function template specialization produced by template argument
3826 // deduction as a candidate.
3827 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003828 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003829 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003830}
Mike Stump11289f42009-09-09 15:08:12 +00003831
Douglas Gregora1f013e2008-11-07 22:36:19 +00003832/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003833/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003834/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003835/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003836/// (which may or may not be the same type as the type that the
3837/// conversion function produces).
3838void
3839Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003840 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003841 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003842 Expr *From, QualType ToType,
3843 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 assert(!Conversion->getDescribedFunctionTemplate() &&
3845 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003846 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003847 if (!CandidateSet.isNewCandidate(Conversion))
3848 return;
3849
Douglas Gregor27381f32009-11-23 12:27:39 +00003850 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003851 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003852
Douglas Gregora1f013e2008-11-07 22:36:19 +00003853 // Add this candidate
3854 CandidateSet.push_back(OverloadCandidate());
3855 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003856 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003857 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003858 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003859 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003860 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003861 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003862 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003863 Candidate.Viable = true;
3864 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003865
Douglas Gregor6affc782010-08-19 15:37:02 +00003866 // C++ [over.match.funcs]p4:
3867 // For conversion functions, the function is considered to be a member of
3868 // the class of the implicit implied object argument for the purpose of
3869 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003870 //
3871 // Determine the implicit conversion sequence for the implicit
3872 // object parameter.
3873 QualType ImplicitParamType = From->getType();
3874 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3875 ImplicitParamType = FromPtrType->getPointeeType();
3876 CXXRecordDecl *ConversionContext
3877 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3878
3879 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003880 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003881 ConversionContext);
3882
John McCall0d1da222010-01-12 00:44:57 +00003883 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003884 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003885 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003886 return;
3887 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003888
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003889 // We won't go through a user-define type conversion function to convert a
3890 // derived to base as such conversions are given Conversion Rank. They only
3891 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3892 QualType FromCanon
3893 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3894 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3895 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3896 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003897 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003898 return;
3899 }
3900
Douglas Gregora1f013e2008-11-07 22:36:19 +00003901 // To determine what the conversion from the result of calling the
3902 // conversion function to the type we're eventually trying to
3903 // convert to (ToType), we need to synthesize a call to the
3904 // conversion function and attempt copy initialization from it. This
3905 // makes sure that we get the right semantics with respect to
3906 // lvalues/rvalues and the type. Fortunately, we can allocate this
3907 // call on the stack and we don't need its arguments to be
3908 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003909 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003910 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003911 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3912 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003913 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003914 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003915
Douglas Gregor72ebdab2010-11-13 19:36:57 +00003916 QualType CallResultType
3917 = Conversion->getConversionType().getNonLValueExprType(Context);
3918 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3919 Candidate.Viable = false;
3920 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3921 return;
3922 }
3923
John McCall7decc9e2010-11-18 06:31:45 +00003924 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3925
Mike Stump11289f42009-09-09 15:08:12 +00003926 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003927 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3928 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00003929 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00003930 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003931 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003932 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003933 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003934 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003935
John McCall0d1da222010-01-12 00:44:57 +00003936 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003937 case ImplicitConversionSequence::StandardConversion:
3938 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003939
3940 // C++ [over.ics.user]p3:
3941 // If the user-defined conversion is specified by a specialization of a
3942 // conversion function template, the second standard conversion sequence
3943 // shall have exact match rank.
3944 if (Conversion->getPrimaryTemplate() &&
3945 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3946 Candidate.Viable = false;
3947 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3948 }
3949
Douglas Gregora1f013e2008-11-07 22:36:19 +00003950 break;
3951
3952 case ImplicitConversionSequence::BadConversion:
3953 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003954 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003955 break;
3956
3957 default:
Mike Stump11289f42009-09-09 15:08:12 +00003958 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003959 "Can only end up with a standard conversion sequence or failure");
3960 }
3961}
3962
Douglas Gregor05155d82009-08-21 23:19:43 +00003963/// \brief Adds a conversion function template specialization
3964/// candidate to the overload set, using template argument deduction
3965/// to deduce the template arguments of the conversion function
3966/// template from the type that we are converting to (C++
3967/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003968void
Douglas Gregor05155d82009-08-21 23:19:43 +00003969Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003970 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003971 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003972 Expr *From, QualType ToType,
3973 OverloadCandidateSet &CandidateSet) {
3974 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3975 "Only conversion function templates permitted here");
3976
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003977 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3978 return;
3979
John McCallbc077cf2010-02-08 23:07:23 +00003980 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003981 CXXConversionDecl *Specialization = 0;
3982 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003983 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003984 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003985 CandidateSet.push_back(OverloadCandidate());
3986 OverloadCandidate &Candidate = CandidateSet.back();
3987 Candidate.FoundDecl = FoundDecl;
3988 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3989 Candidate.Viable = false;
3990 Candidate.FailureKind = ovl_fail_bad_deduction;
3991 Candidate.IsSurrogate = false;
3992 Candidate.IgnoreObjectArgument = false;
3993 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3994 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003995 return;
3996 }
Mike Stump11289f42009-09-09 15:08:12 +00003997
Douglas Gregor05155d82009-08-21 23:19:43 +00003998 // Add the conversion function template specialization produced by
3999 // template argument deduction as a candidate.
4000 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004001 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004002 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004003}
4004
Douglas Gregorab7897a2008-11-19 22:57:39 +00004005/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4006/// converts the given @c Object to a function pointer via the
4007/// conversion function @c Conversion, and then attempts to call it
4008/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4009/// the type of function that we'll eventually be calling.
4010void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004011 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004012 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004013 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00004014 QualType ObjectType,
4015 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004016 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004017 if (!CandidateSet.isNewCandidate(Conversion))
4018 return;
4019
Douglas Gregor27381f32009-11-23 12:27:39 +00004020 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004021 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004022
Douglas Gregorab7897a2008-11-19 22:57:39 +00004023 CandidateSet.push_back(OverloadCandidate());
4024 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004025 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004026 Candidate.Function = 0;
4027 Candidate.Surrogate = Conversion;
4028 Candidate.Viable = true;
4029 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004030 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004031 Candidate.Conversions.resize(NumArgs + 1);
4032
4033 // Determine the implicit conversion sequence for the implicit
4034 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004035 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004036 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4037 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004038 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004039 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004040 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004041 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004042 return;
4043 }
4044
4045 // The first conversion is actually a user-defined conversion whose
4046 // first conversion is ObjectInit's standard conversion (which is
4047 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004048 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004049 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004050 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004051 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00004052 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004053 = Candidate.Conversions[0].UserDefined.Before;
4054 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4055
Mike Stump11289f42009-09-09 15:08:12 +00004056 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004057 unsigned NumArgsInProto = Proto->getNumArgs();
4058
4059 // (C++ 13.3.2p2): A candidate function having fewer than m
4060 // parameters is viable only if it has an ellipsis in its parameter
4061 // list (8.3.5).
4062 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004064 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004065 return;
4066 }
4067
4068 // Function types don't have any default arguments, so just check if
4069 // we have enough arguments.
4070 if (NumArgs < NumArgsInProto) {
4071 // Not enough arguments.
4072 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004073 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004074 return;
4075 }
4076
4077 // Determine the implicit conversion sequences for each of the
4078 // arguments.
4079 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4080 if (ArgIdx < NumArgsInProto) {
4081 // (C++ 13.3.2p3): for F to be a viable function, there shall
4082 // exist for each argument an implicit conversion sequence
4083 // (13.3.3.1) that converts that argument to the corresponding
4084 // parameter of F.
4085 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004086 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004087 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004088 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004089 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004090 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004091 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004092 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004093 break;
4094 }
4095 } else {
4096 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4097 // argument for which there is no corresponding parameter is
4098 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004099 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004100 }
4101 }
4102}
4103
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004104/// \brief Add overload candidates for overloaded operators that are
4105/// member functions.
4106///
4107/// Add the overloaded operator candidates that are member functions
4108/// for the operator Op that was used in an operator expression such
4109/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4110/// CandidateSet will store the added overload candidates. (C++
4111/// [over.match.oper]).
4112void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4113 SourceLocation OpLoc,
4114 Expr **Args, unsigned NumArgs,
4115 OverloadCandidateSet& CandidateSet,
4116 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004117 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4118
4119 // C++ [over.match.oper]p3:
4120 // For a unary operator @ with an operand of a type whose
4121 // cv-unqualified version is T1, and for a binary operator @ with
4122 // a left operand of a type whose cv-unqualified version is T1 and
4123 // a right operand of a type whose cv-unqualified version is T2,
4124 // three sets of candidate functions, designated member
4125 // candidates, non-member candidates and built-in candidates, are
4126 // constructed as follows:
4127 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004128
4129 // -- If T1 is a class type, the set of member candidates is the
4130 // result of the qualified lookup of T1::operator@
4131 // (13.3.1.1.1); otherwise, the set of member candidates is
4132 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004133 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004134 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004135 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004136 return;
Mike Stump11289f42009-09-09 15:08:12 +00004137
John McCall27b18f82009-11-17 02:14:36 +00004138 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4139 LookupQualifiedName(Operators, T1Rec->getDecl());
4140 Operators.suppressDiagnostics();
4141
Mike Stump11289f42009-09-09 15:08:12 +00004142 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004143 OperEnd = Operators.end();
4144 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004145 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004146 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004147 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004148 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004149 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004150}
4151
Douglas Gregora11693b2008-11-12 17:17:38 +00004152/// AddBuiltinCandidate - Add a candidate for a built-in
4153/// operator. ResultTy and ParamTys are the result and parameter types
4154/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004155/// arguments being passed to the candidate. IsAssignmentOperator
4156/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004157/// operator. NumContextualBoolArguments is the number of arguments
4158/// (at the beginning of the argument list) that will be contextually
4159/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004160void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004161 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004162 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004163 bool IsAssignmentOperator,
4164 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004165 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004166 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004167
Douglas Gregora11693b2008-11-12 17:17:38 +00004168 // Add this candidate
4169 CandidateSet.push_back(OverloadCandidate());
4170 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004171 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004172 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004173 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004174 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004175 Candidate.BuiltinTypes.ResultTy = ResultTy;
4176 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4177 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4178
4179 // Determine the implicit conversion sequences for each of the
4180 // arguments.
4181 Candidate.Viable = true;
4182 Candidate.Conversions.resize(NumArgs);
4183 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004184 // C++ [over.match.oper]p4:
4185 // For the built-in assignment operators, conversions of the
4186 // left operand are restricted as follows:
4187 // -- no temporaries are introduced to hold the left operand, and
4188 // -- no user-defined conversions are applied to the left
4189 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004190 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004191 //
4192 // We block these conversions by turning off user-defined
4193 // conversions, since that is the only way that initialization of
4194 // a reference to a non-class type can occur from something that
4195 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004196 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004197 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004198 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004199 Candidate.Conversions[ArgIdx]
4200 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004201 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004202 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004203 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004204 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004205 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004206 }
John McCall0d1da222010-01-12 00:44:57 +00004207 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004208 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004209 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004210 break;
4211 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004212 }
4213}
4214
4215/// BuiltinCandidateTypeSet - A set of types that will be used for the
4216/// candidate operator functions for built-in operators (C++
4217/// [over.built]). The types are separated into pointer types and
4218/// enumeration types.
4219class BuiltinCandidateTypeSet {
4220 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004221 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004222
4223 /// PointerTypes - The set of pointer types that will be used in the
4224 /// built-in candidates.
4225 TypeSet PointerTypes;
4226
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004227 /// MemberPointerTypes - The set of member pointer types that will be
4228 /// used in the built-in candidates.
4229 TypeSet MemberPointerTypes;
4230
Douglas Gregora11693b2008-11-12 17:17:38 +00004231 /// EnumerationTypes - The set of enumeration types that will be
4232 /// used in the built-in candidates.
4233 TypeSet EnumerationTypes;
4234
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004235 /// \brief The set of vector types that will be used in the built-in
4236 /// candidates.
4237 TypeSet VectorTypes;
4238
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004239 /// Sema - The semantic analysis instance where we are building the
4240 /// candidate type set.
4241 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004242
Douglas Gregora11693b2008-11-12 17:17:38 +00004243 /// Context - The AST context in which we will build the type sets.
4244 ASTContext &Context;
4245
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004246 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4247 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004248 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004249
4250public:
4251 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004252 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004253
Mike Stump11289f42009-09-09 15:08:12 +00004254 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004255 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004256
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004257 void AddTypesConvertedFrom(QualType Ty,
4258 SourceLocation Loc,
4259 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004260 bool AllowExplicitConversions,
4261 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004262
4263 /// pointer_begin - First pointer type found;
4264 iterator pointer_begin() { return PointerTypes.begin(); }
4265
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004266 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004267 iterator pointer_end() { return PointerTypes.end(); }
4268
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004269 /// member_pointer_begin - First member pointer type found;
4270 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4271
4272 /// member_pointer_end - Past the last member pointer type found;
4273 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4274
Douglas Gregora11693b2008-11-12 17:17:38 +00004275 /// enumeration_begin - First enumeration type found;
4276 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4277
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004278 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004279 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004280
4281 iterator vector_begin() { return VectorTypes.begin(); }
4282 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004283};
4284
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004285/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004286/// the set of pointer types along with any more-qualified variants of
4287/// that type. For example, if @p Ty is "int const *", this routine
4288/// will add "int const *", "int const volatile *", "int const
4289/// restrict *", and "int const volatile restrict *" to the set of
4290/// pointer types. Returns true if the add of @p Ty itself succeeded,
4291/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004292///
4293/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004294bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004295BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4296 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004297
Douglas Gregora11693b2008-11-12 17:17:38 +00004298 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004299 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004300 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004301
4302 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004303 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004304 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004305 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004306 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004307 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004308 buildObjCPtr = true;
4309 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004310 else
4311 assert(false && "type was not a pointer type!");
4312 }
4313 else
4314 PointeeTy = PointerTy->getPointeeType();
4315
Sebastian Redl4990a632009-11-18 20:39:26 +00004316 // Don't add qualified variants of arrays. For one, they're not allowed
4317 // (the qualifier would sink to the element type), and for another, the
4318 // only overload situation where it matters is subscript or pointer +- int,
4319 // and those shouldn't have qualifier variants anyway.
4320 if (PointeeTy->isArrayType())
4321 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004322 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004323 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004324 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004325 bool hasVolatile = VisibleQuals.hasVolatile();
4326 bool hasRestrict = VisibleQuals.hasRestrict();
4327
John McCall8ccfcb52009-09-24 19:53:00 +00004328 // Iterate through all strict supersets of BaseCVR.
4329 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4330 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004331 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4332 // in the types.
4333 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4334 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004335 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004336 if (!buildObjCPtr)
4337 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4338 else
4339 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004340 }
4341
4342 return true;
4343}
4344
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004345/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4346/// to the set of pointer types along with any more-qualified variants of
4347/// that type. For example, if @p Ty is "int const *", this routine
4348/// will add "int const *", "int const volatile *", "int const
4349/// restrict *", and "int const volatile restrict *" to the set of
4350/// pointer types. Returns true if the add of @p Ty itself succeeded,
4351/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004352///
4353/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004354bool
4355BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4356 QualType Ty) {
4357 // Insert this type.
4358 if (!MemberPointerTypes.insert(Ty))
4359 return false;
4360
John McCall8ccfcb52009-09-24 19:53:00 +00004361 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4362 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004363
John McCall8ccfcb52009-09-24 19:53:00 +00004364 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004365 // Don't add qualified variants of arrays. For one, they're not allowed
4366 // (the qualifier would sink to the element type), and for another, the
4367 // only overload situation where it matters is subscript or pointer +- int,
4368 // and those shouldn't have qualifier variants anyway.
4369 if (PointeeTy->isArrayType())
4370 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004371 const Type *ClassTy = PointerTy->getClass();
4372
4373 // Iterate through all strict supersets of the pointee type's CVR
4374 // qualifiers.
4375 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4376 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4377 if ((CVR | BaseCVR) != CVR) continue;
4378
4379 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4380 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004381 }
4382
4383 return true;
4384}
4385
Douglas Gregora11693b2008-11-12 17:17:38 +00004386/// AddTypesConvertedFrom - Add each of the types to which the type @p
4387/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004388/// primarily interested in pointer types and enumeration types. We also
4389/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004390/// AllowUserConversions is true if we should look at the conversion
4391/// functions of a class type, and AllowExplicitConversions if we
4392/// should also include the explicit conversion functions of a class
4393/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004394void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004395BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004396 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004397 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004398 bool AllowExplicitConversions,
4399 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004400 // Only deal with canonical types.
4401 Ty = Context.getCanonicalType(Ty);
4402
4403 // Look through reference types; they aren't part of the type of an
4404 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004405 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004406 Ty = RefTy->getPointeeType();
4407
4408 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004409 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004410
Sebastian Redl65ae2002009-11-05 16:36:20 +00004411 // If we're dealing with an array type, decay to the pointer.
4412 if (Ty->isArrayType())
4413 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004414 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4415 PointerTypes.insert(Ty);
4416 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004417 // Insert our type, and its more-qualified variants, into the set
4418 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004419 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004420 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004421 } else if (Ty->isMemberPointerType()) {
4422 // Member pointers are far easier, since the pointee can't be converted.
4423 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4424 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004425 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004426 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004427 } else if (Ty->isVectorType()) {
4428 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004429 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004430 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004431 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004432 // No conversion functions in incomplete types.
4433 return;
4434 }
Mike Stump11289f42009-09-09 15:08:12 +00004435
Douglas Gregora11693b2008-11-12 17:17:38 +00004436 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004437 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004438 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004439 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004440 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004441 NamedDecl *D = I.getDecl();
4442 if (isa<UsingShadowDecl>(D))
4443 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004444
Mike Stump11289f42009-09-09 15:08:12 +00004445 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004446 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004447 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004448 continue;
4449
John McCallda4458e2010-03-31 01:36:47 +00004450 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004451 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004452 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004453 VisibleQuals);
4454 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004455 }
4456 }
4457 }
4458}
4459
Douglas Gregor84605ae2009-08-24 13:43:27 +00004460/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4461/// the volatile- and non-volatile-qualified assignment operators for the
4462/// given type to the candidate set.
4463static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4464 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004465 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004466 unsigned NumArgs,
4467 OverloadCandidateSet &CandidateSet) {
4468 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004469
Douglas Gregor84605ae2009-08-24 13:43:27 +00004470 // T& operator=(T&, T)
4471 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4472 ParamTypes[1] = T;
4473 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4474 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004475
Douglas Gregor84605ae2009-08-24 13:43:27 +00004476 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4477 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004478 ParamTypes[0]
4479 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004480 ParamTypes[1] = T;
4481 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004482 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004483 }
4484}
Mike Stump11289f42009-09-09 15:08:12 +00004485
Sebastian Redl1054fae2009-10-25 17:03:50 +00004486/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4487/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004488static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4489 Qualifiers VRQuals;
4490 const RecordType *TyRec;
4491 if (const MemberPointerType *RHSMPType =
4492 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004493 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004494 else
4495 TyRec = ArgExpr->getType()->getAs<RecordType>();
4496 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004497 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004498 VRQuals.addVolatile();
4499 VRQuals.addRestrict();
4500 return VRQuals;
4501 }
4502
4503 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004504 if (!ClassDecl->hasDefinition())
4505 return VRQuals;
4506
John McCallad371252010-01-20 00:46:10 +00004507 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004508 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004509
John McCallad371252010-01-20 00:46:10 +00004510 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004511 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004512 NamedDecl *D = I.getDecl();
4513 if (isa<UsingShadowDecl>(D))
4514 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4515 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004516 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4517 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4518 CanTy = ResTypeRef->getPointeeType();
4519 // Need to go down the pointer/mempointer chain and add qualifiers
4520 // as see them.
4521 bool done = false;
4522 while (!done) {
4523 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4524 CanTy = ResTypePtr->getPointeeType();
4525 else if (const MemberPointerType *ResTypeMPtr =
4526 CanTy->getAs<MemberPointerType>())
4527 CanTy = ResTypeMPtr->getPointeeType();
4528 else
4529 done = true;
4530 if (CanTy.isVolatileQualified())
4531 VRQuals.addVolatile();
4532 if (CanTy.isRestrictQualified())
4533 VRQuals.addRestrict();
4534 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4535 return VRQuals;
4536 }
4537 }
4538 }
4539 return VRQuals;
4540}
John McCall52872982010-11-13 05:51:15 +00004541
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004542
Douglas Gregord08452f2008-11-19 15:42:04 +00004543/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4544/// operator overloads to the candidate set (C++ [over.built]), based
4545/// on the operator @p Op and the arguments given. For example, if the
4546/// operator is a binary '+', this routine might add "int
4547/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004548void
Mike Stump11289f42009-09-09 15:08:12 +00004549Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004550 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004551 Expr **Args, unsigned NumArgs,
4552 OverloadCandidateSet& CandidateSet) {
John McCall52872982010-11-13 05:51:15 +00004553 // Information about arithmetic types useful to builtin-type
4554 // calculations.
4555
4556 // The "promoted arithmetic types" are the arithmetic
4557 // types are that preserved by promotion (C++ [over.built]p2).
4558
4559 static const unsigned FirstIntegralType = 3;
4560 static const unsigned LastIntegralType = 18;
4561 static const unsigned FirstPromotedIntegralType = 3,
4562 LastPromotedIntegralType = 9;
4563 static const unsigned FirstPromotedArithmeticType = 0,
4564 LastPromotedArithmeticType = 9;
4565 static const unsigned NumArithmeticTypes = 18;
4566
John McCall988ffb72010-11-13 02:01:09 +00004567 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall52872982010-11-13 05:51:15 +00004568 // Start of promoted types.
4569 &ASTContext::FloatTy,
4570 &ASTContext::DoubleTy,
4571 &ASTContext::LongDoubleTy,
4572
4573 // Start of integral types.
4574 &ASTContext::IntTy,
4575 &ASTContext::LongTy,
4576 &ASTContext::LongLongTy,
4577 &ASTContext::UnsignedIntTy,
4578 &ASTContext::UnsignedLongTy,
4579 &ASTContext::UnsignedLongLongTy,
4580 // End of promoted types.
4581
John McCall988ffb72010-11-13 02:01:09 +00004582 &ASTContext::BoolTy,
4583 &ASTContext::CharTy,
4584 &ASTContext::WCharTy,
4585 &ASTContext::Char16Ty,
4586 &ASTContext::Char32Ty,
4587 &ASTContext::SignedCharTy,
4588 &ASTContext::ShortTy,
4589 &ASTContext::UnsignedCharTy,
John McCall52872982010-11-13 05:51:15 +00004590 &ASTContext::UnsignedShortTy
4591 // End of integral types.
Douglas Gregora11693b2008-11-12 17:17:38 +00004592 };
John McCall52872982010-11-13 05:51:15 +00004593 // FIXME: What about complex?
John McCall988ffb72010-11-13 02:01:09 +00004594 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004595 "Invalid first promoted integral type");
4596 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall988ffb72010-11-13 02:01:09 +00004597 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004598 "Invalid last promoted integral type");
John McCall52872982010-11-13 05:51:15 +00004599 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004600 "Invalid first promoted arithmetic type");
4601 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall52872982010-11-13 05:51:15 +00004602 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004603 "Invalid last promoted arithmetic type");
John McCall52872982010-11-13 05:51:15 +00004604
4605 // Accelerator table for performing the usual arithmetic conversions.
4606 // The rules are basically:
4607 // - if either is floating-point, use the wider floating-point
4608 // - if same signedness, use the higher rank
4609 // - if same size, use unsigned of the higher rank
4610 // - use the larger type
4611 // These rules, together with the axiom that higher ranks are
4612 // never smaller, are sufficient to precompute all of these results
4613 // *except* when dealing with signed types of higher rank.
4614 // (we could precompute SLL x UI for all known platforms, but it's
4615 // better not to make any assumptions).
4616 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4617 static PromT UsualArithmeticConversionsTypes
4618 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4619 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4620 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4621 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4622 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4623 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4624 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4625 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4626 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4627 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4628 };
4629 struct UsualArithmeticConversionsType {
4630 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4631 assert(L < LastPromotedArithmeticType);
4632 assert(R < LastPromotedArithmeticType);
4633 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4634
4635 // Fast path: the table gives us a concrete answer.
4636 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4637
4638 // Slow path: we need to compare widths.
4639 // An invariant is that the signed type has higher rank.
4640 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4641 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4642
4643 // If they're different widths, use the signed type.
4644 if (LW > RW) return LT;
4645 else if (LW > RW) return RT;
4646
4647 // Otherwise, use the unsigned type of the signed type's rank.
4648 if (L == SL || R == SL) return C.UnsignedLongTy;
4649 assert(L == SLL || R == SLL);
4650 return C.UnsignedLongLongTy;
4651 }
4652 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004653
Douglas Gregora11693b2008-11-12 17:17:38 +00004654 // Find all of the types that the arguments can convert to, but only
4655 // if the operator we're looking at has built-in operator candidates
4656 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004657 Qualifiers VisibleTypeConversionsQuals;
4658 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004659 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4660 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4661
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004662 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4663 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4664 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4665 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4666 OpLoc,
4667 true,
4668 (Op == OO_Exclaim ||
4669 Op == OO_AmpAmp ||
4670 Op == OO_PipePipe),
4671 VisibleTypeConversionsQuals);
4672 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004673
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004674 // C++ [over.built]p1:
4675 // If there is a user-written candidate with the same name and parameter
4676 // types as a built-in candidate operator function, the built-in operator
4677 // function is hidden and is not included in the set of candidate functions.
4678 //
4679 // The text is actually in a note, but if we don't implement it then we end
4680 // up with ambiguities when the user provides an overloaded operator for
4681 // an enumeration type. Note that only enumeration types have this problem,
4682 // so we track which enumeration types we've seen operators for.
4683 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4684 UserDefinedBinaryOperators;
4685
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004686 /// Set of (canonical) types that we've already handled.
4687 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4688
4689 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4690 if (CandidateTypes[ArgIdx].enumeration_begin()
4691 != CandidateTypes[ArgIdx].enumeration_end()) {
4692 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4693 CEnd = CandidateSet.end();
4694 C != CEnd; ++C) {
4695 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4696 continue;
4697
4698 // Check if the first parameter is of enumeration type.
4699 QualType FirstParamType
4700 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4701 if (!FirstParamType->isEnumeralType())
4702 continue;
4703
4704 // Check if the second parameter is of enumeration type.
4705 QualType SecondParamType
4706 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4707 if (!SecondParamType->isEnumeralType())
4708 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004709
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004710 // Add this operator to the set of known user-defined operators.
4711 UserDefinedBinaryOperators.insert(
4712 std::make_pair(Context.getCanonicalType(FirstParamType),
4713 Context.getCanonicalType(SecondParamType)));
4714 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004715 }
4716 }
4717
Douglas Gregora11693b2008-11-12 17:17:38 +00004718 bool isComparison = false;
4719 switch (Op) {
4720 case OO_None:
4721 case NUM_OVERLOADED_OPERATORS:
4722 assert(false && "Expected an overloaded operator");
4723 break;
4724
Douglas Gregord08452f2008-11-19 15:42:04 +00004725 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004726 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004727 goto UnaryStar;
4728 else
4729 goto BinaryStar;
4730 break;
4731
4732 case OO_Plus: // '+' is either unary or binary
4733 if (NumArgs == 1)
4734 goto UnaryPlus;
4735 else
4736 goto BinaryPlus;
4737 break;
4738
4739 case OO_Minus: // '-' is either unary or binary
4740 if (NumArgs == 1)
4741 goto UnaryMinus;
4742 else
4743 goto BinaryMinus;
4744 break;
4745
4746 case OO_Amp: // '&' is either unary or binary
4747 if (NumArgs == 1)
4748 goto UnaryAmp;
4749 else
4750 goto BinaryAmp;
4751
4752 case OO_PlusPlus:
4753 case OO_MinusMinus:
4754 // C++ [over.built]p3:
4755 //
4756 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4757 // is either volatile or empty, there exist candidate operator
4758 // functions of the form
4759 //
4760 // VQ T& operator++(VQ T&);
4761 // T operator++(VQ T&, int);
4762 //
4763 // C++ [over.built]p4:
4764 //
4765 // For every pair (T, VQ), where T is an arithmetic type other
4766 // than bool, and VQ is either volatile or empty, there exist
4767 // candidate operator functions of the form
4768 //
4769 // VQ T& operator--(VQ T&);
4770 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004771 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004772 Arith < NumArithmeticTypes; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004773 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004774 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004775 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004776
4777 // Non-volatile version.
4778 if (NumArgs == 1)
4779 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4780 else
4781 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004782 // heuristic to reduce number of builtin candidates in the set.
4783 // Add volatile version only if there are conversions to a volatile type.
4784 if (VisibleTypeConversionsQuals.hasVolatile()) {
4785 // Volatile version
4786 ParamTypes[0]
4787 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4788 if (NumArgs == 1)
4789 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4790 else
4791 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4792 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004793 }
4794
4795 // C++ [over.built]p5:
4796 //
4797 // For every pair (T, VQ), where T is a cv-qualified or
4798 // cv-unqualified object type, and VQ is either volatile or
4799 // empty, there exist candidate operator functions of the form
4800 //
4801 // T*VQ& operator++(T*VQ&);
4802 // T*VQ& operator--(T*VQ&);
4803 // T* operator++(T*VQ&, int);
4804 // T* operator--(T*VQ&, int);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004805 for (BuiltinCandidateTypeSet::iterator
4806 Ptr = CandidateTypes[0].pointer_begin(),
4807 PtrEnd = CandidateTypes[0].pointer_end();
4808 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004809 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004810 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004811 continue;
4812
Mike Stump11289f42009-09-09 15:08:12 +00004813 QualType ParamTypes[2] = {
4814 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004815 };
Mike Stump11289f42009-09-09 15:08:12 +00004816
Douglas Gregord08452f2008-11-19 15:42:04 +00004817 // Without volatile
4818 if (NumArgs == 1)
4819 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4820 else
4821 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4822
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004823 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4824 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004825 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004826 ParamTypes[0]
4827 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004828 if (NumArgs == 1)
4829 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4830 else
4831 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4832 }
4833 }
4834 break;
4835
4836 UnaryStar:
4837 // C++ [over.built]p6:
4838 // For every cv-qualified or cv-unqualified object type T, there
4839 // exist candidate operator functions of the form
4840 //
4841 // T& operator*(T*);
4842 //
4843 // C++ [over.built]p7:
4844 // For every function type T, there exist candidate operator
4845 // functions of the form
4846 // T& operator*(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004847 for (BuiltinCandidateTypeSet::iterator
4848 Ptr = CandidateTypes[0].pointer_begin(),
4849 PtrEnd = CandidateTypes[0].pointer_end();
4850 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004851 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004852 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004853 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004854 &ParamTy, Args, 1, CandidateSet);
4855 }
4856 break;
4857
4858 UnaryPlus:
4859 // C++ [over.built]p8:
4860 // For every type T, there exist candidate operator functions of
4861 // the form
4862 //
4863 // T* operator+(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004864 for (BuiltinCandidateTypeSet::iterator
4865 Ptr = CandidateTypes[0].pointer_begin(),
4866 PtrEnd = CandidateTypes[0].pointer_end();
4867 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004868 QualType ParamTy = *Ptr;
4869 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4870 }
Mike Stump11289f42009-09-09 15:08:12 +00004871
Douglas Gregord08452f2008-11-19 15:42:04 +00004872 // Fall through
4873
4874 UnaryMinus:
4875 // C++ [over.built]p9:
4876 // For every promoted arithmetic type T, there exist candidate
4877 // operator functions of the form
4878 //
4879 // T operator+(T);
4880 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004881 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004882 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004883 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregord08452f2008-11-19 15:42:04 +00004884 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4885 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004886
4887 // Extension: We also add these operators for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004888 for (BuiltinCandidateTypeSet::iterator
4889 Vec = CandidateTypes[0].vector_begin(),
4890 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004891 Vec != VecEnd; ++Vec) {
4892 QualType VecTy = *Vec;
4893 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4894 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004895 break;
4896
4897 case OO_Tilde:
4898 // C++ [over.built]p10:
4899 // For every promoted integral type T, there exist candidate
4900 // operator functions of the form
4901 //
4902 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004903 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004904 Int < LastPromotedIntegralType; ++Int) {
John McCall988ffb72010-11-13 02:01:09 +00004905 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregord08452f2008-11-19 15:42:04 +00004906 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4907 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004908
4909 // Extension: We also add this operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004910 for (BuiltinCandidateTypeSet::iterator
4911 Vec = CandidateTypes[0].vector_begin(),
4912 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004913 Vec != VecEnd; ++Vec) {
4914 QualType VecTy = *Vec;
4915 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4916 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004917 break;
4918
Douglas Gregora11693b2008-11-12 17:17:38 +00004919 case OO_New:
4920 case OO_Delete:
4921 case OO_Array_New:
4922 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004923 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004924 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004925 break;
4926
4927 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004928 UnaryAmp:
4929 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004930 // C++ [over.match.oper]p3:
4931 // -- For the operator ',', the unary operator '&', or the
4932 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004933 break;
4934
Douglas Gregor84605ae2009-08-24 13:43:27 +00004935 case OO_EqualEqual:
4936 case OO_ExclaimEqual:
4937 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004938 // For every pointer to member type T, there exist candidate operator
4939 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004940 //
4941 // bool operator==(T,T);
4942 // bool operator!=(T,T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004943 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4944 for (BuiltinCandidateTypeSet::iterator
4945 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4946 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4947 MemPtr != MemPtrEnd;
4948 ++MemPtr) {
4949 // Don't add the same builtin candidate twice.
4950 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4951 continue;
4952
4953 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4954 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4955 }
Douglas Gregor84605ae2009-08-24 13:43:27 +00004956 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004957 AddedTypes.clear();
4958
Douglas Gregor84605ae2009-08-24 13:43:27 +00004959 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004960
Douglas Gregora11693b2008-11-12 17:17:38 +00004961 case OO_Less:
4962 case OO_Greater:
4963 case OO_LessEqual:
4964 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004965 // C++ [over.built]p15:
4966 //
4967 // For every pointer or enumeration type T, there exist
4968 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004969 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004970 // bool operator<(T, T);
4971 // bool operator>(T, T);
4972 // bool operator<=(T, T);
4973 // bool operator>=(T, T);
4974 // bool operator==(T, T);
4975 // bool operator!=(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004976 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4977 for (BuiltinCandidateTypeSet::iterator
4978 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4979 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4980 Ptr != PtrEnd; ++Ptr) {
4981 // Don't add the same builtin candidate twice.
4982 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4983 continue;
4984
4985 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004986 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004987 }
4988 for (BuiltinCandidateTypeSet::iterator
4989 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4990 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4991 Enum != EnumEnd; ++Enum) {
4992 // Don't add the same builtin candidate twice.
4993 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4994 continue;
4995
4996 QualType ParamTypes[2] = { *Enum, *Enum };
4997 CanQualType CanonType = Context.getCanonicalType(*Enum);
4998 if (!UserDefinedBinaryOperators.count(
4999 std::make_pair(CanonType, CanonType)))
5000 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
5001 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005002 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005003 AddedTypes.clear();
5004
Douglas Gregora11693b2008-11-12 17:17:38 +00005005 // Fall through.
5006 isComparison = true;
5007
Douglas Gregord08452f2008-11-19 15:42:04 +00005008 BinaryPlus:
5009 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00005010 if (!isComparison) {
5011 // We didn't fall through, so we must have OO_Plus or OO_Minus.
5012
5013 // C++ [over.built]p13:
5014 //
5015 // For every cv-qualified or cv-unqualified object type T
5016 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005017 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005018 // T* operator+(T*, ptrdiff_t);
5019 // T& operator[](T*, ptrdiff_t); [BELOW]
5020 // T* operator-(T*, ptrdiff_t);
5021 // T* operator+(ptrdiff_t, T*);
5022 // T& operator[](ptrdiff_t, T*); [BELOW]
5023 //
5024 // C++ [over.built]p14:
5025 //
5026 // For every T, where T is a pointer to object type, there
5027 // exist candidate operator functions of the form
5028 //
5029 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005030 for (BuiltinCandidateTypeSet::iterator
5031 Ptr = CandidateTypes[0].pointer_begin(),
5032 PtrEnd = CandidateTypes[0].pointer_end();
5033 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005034 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
5035
5036 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5037 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5038
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005039 if (Op == OO_Minus) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005040 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005041 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5042 continue;
5043
Douglas Gregora11693b2008-11-12 17:17:38 +00005044 ParamTypes[1] = *Ptr;
5045 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5046 Args, 2, CandidateSet);
5047 }
5048 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005049
5050 for (BuiltinCandidateTypeSet::iterator
5051 Ptr = CandidateTypes[1].pointer_begin(),
5052 PtrEnd = CandidateTypes[1].pointer_end();
5053 Ptr != PtrEnd; ++Ptr) {
5054 if (Op == OO_Plus) {
5055 // T* operator+(ptrdiff_t, T*);
5056 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5057 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5058 } else {
5059 // ptrdiff_t operator-(T, T);
5060 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5061 continue;
5062
5063 QualType ParamTypes[2] = { *Ptr, *Ptr };
5064 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5065 Args, 2, CandidateSet);
5066 }
5067 }
5068
5069 AddedTypes.clear();
Douglas Gregora11693b2008-11-12 17:17:38 +00005070 }
5071 // Fall through
5072
Douglas Gregora11693b2008-11-12 17:17:38 +00005073 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00005074 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00005075 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00005076 // C++ [over.built]p12:
5077 //
5078 // For every pair of promoted arithmetic types L and R, there
5079 // exist candidate operator functions of the form
5080 //
5081 // LR operator*(L, R);
5082 // LR operator/(L, R);
5083 // LR operator+(L, R);
5084 // LR operator-(L, R);
5085 // bool operator<(L, R);
5086 // bool operator>(L, R);
5087 // bool operator<=(L, R);
5088 // bool operator>=(L, R);
5089 // bool operator==(L, R);
5090 // bool operator!=(L, R);
5091 //
5092 // where LR is the result of the usual arithmetic conversions
5093 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005094 //
5095 // C++ [over.built]p24:
5096 //
5097 // For every pair of promoted arithmetic types L and R, there exist
5098 // candidate operator functions of the form
5099 //
5100 // LR operator?(bool, L, R);
5101 //
5102 // where LR is the result of the usual arithmetic conversions
5103 // between types L and R.
5104 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005105 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005106 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005107 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005108 Right < LastPromotedArithmeticType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005109 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5110 Context.*ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005111 QualType Result
5112 = isComparison
5113 ? Context.BoolTy
John McCall52872982010-11-13 05:51:15 +00005114 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005115 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5116 }
5117 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005118
5119 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5120 // conditional operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005121 for (BuiltinCandidateTypeSet::iterator
5122 Vec1 = CandidateTypes[0].vector_begin(),
5123 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005124 Vec1 != Vec1End; ++Vec1)
5125 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005126 Vec2 = CandidateTypes[1].vector_begin(),
5127 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005128 Vec2 != Vec2End; ++Vec2) {
5129 QualType LandR[2] = { *Vec1, *Vec2 };
5130 QualType Result;
5131 if (isComparison)
5132 Result = Context.BoolTy;
5133 else {
5134 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5135 Result = *Vec1;
5136 else
5137 Result = *Vec2;
5138 }
5139
5140 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5141 }
5142
Douglas Gregora11693b2008-11-12 17:17:38 +00005143 break;
5144
5145 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005146 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005147 case OO_Caret:
5148 case OO_Pipe:
5149 case OO_LessLess:
5150 case OO_GreaterGreater:
5151 // C++ [over.built]p17:
5152 //
5153 // For every pair of promoted integral types L and R, there
5154 // exist candidate operator functions of the form
5155 //
5156 // LR operator%(L, R);
5157 // LR operator&(L, R);
5158 // LR operator^(L, R);
5159 // LR operator|(L, R);
5160 // L operator<<(L, R);
5161 // L operator>>(L, R);
5162 //
5163 // where LR is the result of the usual arithmetic conversions
5164 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00005165 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005166 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005167 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005168 Right < LastPromotedIntegralType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005169 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5170 Context.*ArithmeticTypes[Right] };
Douglas Gregora11693b2008-11-12 17:17:38 +00005171 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5172 ? LandR[0]
John McCall52872982010-11-13 05:51:15 +00005173 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005174 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5175 }
5176 }
5177 break;
5178
5179 case OO_Equal:
5180 // C++ [over.built]p20:
5181 //
5182 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00005183 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00005184 // empty, there exist candidate operator functions of the form
5185 //
5186 // VQ T& operator=(VQ T&, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005187 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5188 for (BuiltinCandidateTypeSet::iterator
5189 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5190 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5191 Enum != EnumEnd; ++Enum) {
5192 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5193 continue;
5194
5195 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5196 CandidateSet);
5197 }
5198
5199 for (BuiltinCandidateTypeSet::iterator
5200 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5201 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5202 MemPtr != MemPtrEnd; ++MemPtr) {
5203 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5204 continue;
5205
5206 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5207 CandidateSet);
5208 }
5209 }
5210 AddedTypes.clear();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005211
5212 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005213
5214 case OO_PlusEqual:
5215 case OO_MinusEqual:
5216 // C++ [over.built]p19:
5217 //
5218 // For every pair (T, VQ), where T is any type and VQ is either
5219 // volatile or empty, there exist candidate operator functions
5220 // of the form
5221 //
5222 // T*VQ& operator=(T*VQ&, T*);
5223 //
5224 // C++ [over.built]p21:
5225 //
5226 // For every pair (T, VQ), where T is a cv-qualified or
5227 // cv-unqualified object type and VQ is either volatile or
5228 // empty, there exist candidate operator functions of the form
5229 //
5230 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5231 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005232 for (BuiltinCandidateTypeSet::iterator
5233 Ptr = CandidateTypes[0].pointer_begin(),
5234 PtrEnd = CandidateTypes[0].pointer_end();
5235 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005236 QualType ParamTypes[2];
5237 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5238
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005239 // If this is operator=, keep track of the builtin candidates we added.
5240 if (Op == OO_Equal)
5241 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5242
Douglas Gregora11693b2008-11-12 17:17:38 +00005243 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005244 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005245 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5246 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005247
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005248 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5249 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005250 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005251 ParamTypes[0]
5252 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005253 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5254 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005255 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005256 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005257
5258 if (Op == OO_Equal) {
5259 for (BuiltinCandidateTypeSet::iterator
5260 Ptr = CandidateTypes[1].pointer_begin(),
5261 PtrEnd = CandidateTypes[1].pointer_end();
5262 Ptr != PtrEnd; ++Ptr) {
5263 // Make sure we don't add the same candidate twice.
5264 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5265 continue;
5266
5267 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5268
5269 // non-volatile version
5270 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5271 /*IsAssigmentOperator=*/true);
5272
5273 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5274 VisibleTypeConversionsQuals.hasVolatile()) {
5275 // volatile version
5276 ParamTypes[0]
5277 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5278 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5279 /*IsAssigmentOperator=*/true);
5280 }
5281 }
5282 AddedTypes.clear();
5283 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005284 // Fall through.
5285
5286 case OO_StarEqual:
5287 case OO_SlashEqual:
5288 // C++ [over.built]p18:
5289 //
5290 // For every triple (L, VQ, R), where L is an arithmetic type,
5291 // VQ is either volatile or empty, and R is a promoted
5292 // arithmetic type, there exist candidate operator functions of
5293 // the form
5294 //
5295 // VQ L& operator=(VQ L&, R);
5296 // VQ L& operator*=(VQ L&, R);
5297 // VQ L& operator/=(VQ L&, R);
5298 // VQ L& operator+=(VQ L&, R);
5299 // VQ L& operator-=(VQ L&, R);
5300 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005301 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005302 Right < LastPromotedArithmeticType; ++Right) {
5303 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005304 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005305
5306 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005307 ParamTypes[0] =
5308 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005309 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5310 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005311
5312 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005313 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall988ffb72010-11-13 02:01:09 +00005314 ParamTypes[0] =
5315 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005316 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5317 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5318 /*IsAssigmentOperator=*/Op == OO_Equal);
5319 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005320 }
5321 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005322
5323 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005324 for (BuiltinCandidateTypeSet::iterator
5325 Vec1 = CandidateTypes[0].vector_begin(),
5326 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005327 Vec1 != Vec1End; ++Vec1)
5328 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005329 Vec2 = CandidateTypes[1].vector_begin(),
5330 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005331 Vec2 != Vec2End; ++Vec2) {
5332 QualType ParamTypes[2];
5333 ParamTypes[1] = *Vec2;
5334 // Add this built-in operator as a candidate (VQ is empty).
5335 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5336 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5337 /*IsAssigmentOperator=*/Op == OO_Equal);
5338
5339 // Add this built-in operator as a candidate (VQ is 'volatile').
5340 if (VisibleTypeConversionsQuals.hasVolatile()) {
5341 ParamTypes[0] = Context.getVolatileType(*Vec1);
5342 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5343 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5344 /*IsAssigmentOperator=*/Op == OO_Equal);
5345 }
5346 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005347 break;
5348
5349 case OO_PercentEqual:
5350 case OO_LessLessEqual:
5351 case OO_GreaterGreaterEqual:
5352 case OO_AmpEqual:
5353 case OO_CaretEqual:
5354 case OO_PipeEqual:
5355 // C++ [over.built]p22:
5356 //
5357 // For every triple (L, VQ, R), where L is an integral type, VQ
5358 // is either volatile or empty, and R is a promoted integral
5359 // type, there exist candidate operator functions of the form
5360 //
5361 // VQ L& operator%=(VQ L&, R);
5362 // VQ L& operator<<=(VQ L&, R);
5363 // VQ L& operator>>=(VQ L&, R);
5364 // VQ L& operator&=(VQ L&, R);
5365 // VQ L& operator^=(VQ L&, R);
5366 // VQ L& operator|=(VQ L&, R);
5367 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005368 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005369 Right < LastPromotedIntegralType; ++Right) {
5370 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005371 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005372
5373 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005374 ParamTypes[0] =
5375 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005376 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005377 if (VisibleTypeConversionsQuals.hasVolatile()) {
5378 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall988ffb72010-11-13 02:01:09 +00005379 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005380 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5381 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5382 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5383 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005384 }
5385 }
5386 break;
5387
Douglas Gregord08452f2008-11-19 15:42:04 +00005388 case OO_Exclaim: {
5389 // C++ [over.operator]p23:
5390 //
5391 // There also exist candidate operator functions of the form
5392 //
Mike Stump11289f42009-09-09 15:08:12 +00005393 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005394 // bool operator&&(bool, bool); [BELOW]
5395 // bool operator||(bool, bool); [BELOW]
5396 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005397 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5398 /*IsAssignmentOperator=*/false,
5399 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005400 break;
5401 }
5402
Douglas Gregora11693b2008-11-12 17:17:38 +00005403 case OO_AmpAmp:
5404 case OO_PipePipe: {
5405 // C++ [over.operator]p23:
5406 //
5407 // There also exist candidate operator functions of the form
5408 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005409 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005410 // bool operator&&(bool, bool);
5411 // bool operator||(bool, bool);
5412 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005413 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5414 /*IsAssignmentOperator=*/false,
5415 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005416 break;
5417 }
5418
5419 case OO_Subscript:
5420 // C++ [over.built]p13:
5421 //
5422 // For every cv-qualified or cv-unqualified object type T there
5423 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005424 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005425 // T* operator+(T*, ptrdiff_t); [ABOVE]
5426 // T& operator[](T*, ptrdiff_t);
5427 // T* operator-(T*, ptrdiff_t); [ABOVE]
5428 // T* operator+(ptrdiff_t, T*); [ABOVE]
5429 // T& operator[](ptrdiff_t, T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005430 for (BuiltinCandidateTypeSet::iterator
5431 Ptr = CandidateTypes[0].pointer_begin(),
5432 PtrEnd = CandidateTypes[0].pointer_end();
5433 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005434 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005435 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005436 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005437
5438 // T& operator[](T*, ptrdiff_t)
5439 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005440 }
5441
5442 for (BuiltinCandidateTypeSet::iterator
5443 Ptr = CandidateTypes[1].pointer_begin(),
5444 PtrEnd = CandidateTypes[1].pointer_end();
5445 Ptr != PtrEnd; ++Ptr) {
5446 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5447 QualType PointeeType = (*Ptr)->getPointeeType();
5448 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5449
5450 // T& operator[](ptrdiff_t, T*)
Douglas Gregora11693b2008-11-12 17:17:38 +00005451 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005452 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005453 break;
5454
5455 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005456 // C++ [over.built]p11:
5457 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5458 // C1 is the same type as C2 or is a derived class of C2, T is an object
5459 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5460 // there exist candidate operator functions of the form
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005461 //
5462 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5463 //
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005464 // where CV12 is the union of CV1 and CV2.
5465 {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005466 for (BuiltinCandidateTypeSet::iterator
5467 Ptr = CandidateTypes[0].pointer_begin(),
5468 PtrEnd = CandidateTypes[0].pointer_end();
5469 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005470 QualType C1Ty = (*Ptr);
5471 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005472 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005473 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5474 if (!isa<RecordType>(C1))
5475 continue;
5476 // heuristic to reduce number of builtin candidates in the set.
5477 // Add volatile/restrict version only if there are conversions to a
5478 // volatile/restrict type.
5479 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5480 continue;
5481 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5482 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005483 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005484 MemPtr = CandidateTypes[1].member_pointer_begin(),
5485 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005486 MemPtr != MemPtrEnd; ++MemPtr) {
5487 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5488 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005489 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005490 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5491 break;
5492 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5493 // build CV12 T&
5494 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005495 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5496 T.isVolatileQualified())
5497 continue;
5498 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5499 T.isRestrictQualified())
5500 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005501 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005502 QualType ResultTy = Context.getLValueReferenceType(T);
5503 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5504 }
5505 }
5506 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005507 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005508
5509 case OO_Conditional:
5510 // Note that we don't consider the first argument, since it has been
5511 // contextually converted to bool long ago. The candidates below are
5512 // therefore added as binary.
5513 //
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005514 // C++ [over.built]p25:
5515 // For every type T, where T is a pointer, pointer-to-member, or scoped
5516 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl1a99f442009-04-16 17:51:27 +00005517 //
5518 // T operator?(bool, T, T);
5519 //
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005520 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5521 for (BuiltinCandidateTypeSet::iterator
5522 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5523 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5524 Ptr != PtrEnd; ++Ptr) {
5525 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5526 continue;
5527
5528 QualType ParamTypes[2] = { *Ptr, *Ptr };
5529 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5530 }
5531
5532 for (BuiltinCandidateTypeSet::iterator
5533 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5534 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5535 MemPtr != MemPtrEnd; ++MemPtr) {
5536 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5537 continue;
5538
5539 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5540 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5541 }
5542
5543 if (getLangOptions().CPlusPlus0x) {
5544 for (BuiltinCandidateTypeSet::iterator
5545 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5546 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5547 Enum != EnumEnd; ++Enum) {
5548 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5549 continue;
5550
5551 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5552 continue;
5553
5554 QualType ParamTypes[2] = { *Enum, *Enum };
5555 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5556 }
5557 }
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005558 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005559 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005560 }
5561}
5562
Douglas Gregore254f902009-02-04 00:32:51 +00005563/// \brief Add function candidates found via argument-dependent lookup
5564/// to the set of overloading candidates.
5565///
5566/// This routine performs argument-dependent name lookup based on the
5567/// given function name (which may also be an operator name) and adds
5568/// all of the overload candidates found by ADL to the overload
5569/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005570void
Douglas Gregore254f902009-02-04 00:32:51 +00005571Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005572 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005573 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005574 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005575 OverloadCandidateSet& CandidateSet,
5576 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005577 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005578
John McCall91f61fc2010-01-26 06:04:06 +00005579 // FIXME: This approach for uniquing ADL results (and removing
5580 // redundant candidates from the set) relies on pointer-equality,
5581 // which means we need to key off the canonical decl. However,
5582 // always going back to the canonical decl might not get us the
5583 // right set of default arguments. What default arguments are
5584 // we supposed to consider on ADL candidates, anyway?
5585
Douglas Gregorcabea402009-09-22 15:41:20 +00005586 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005587 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005588
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005589 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005590 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5591 CandEnd = CandidateSet.end();
5592 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005593 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005594 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005595 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005596 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005597 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005598
5599 // For each of the ADL candidates we found, add it to the overload
5600 // set.
John McCall8fe68082010-01-26 07:16:45 +00005601 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005602 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005603 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005604 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005605 continue;
5606
John McCalla0296f72010-03-19 07:35:19 +00005607 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005608 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005609 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005610 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005611 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005612 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005613 }
Douglas Gregore254f902009-02-04 00:32:51 +00005614}
5615
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005616/// isBetterOverloadCandidate - Determines whether the first overload
5617/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005618bool
John McCall5c32be02010-08-24 20:38:10 +00005619isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005620 const OverloadCandidate &Cand1,
5621 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005622 SourceLocation Loc,
5623 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005624 // Define viable functions to be better candidates than non-viable
5625 // functions.
5626 if (!Cand2.Viable)
5627 return Cand1.Viable;
5628 else if (!Cand1.Viable)
5629 return false;
5630
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005631 // C++ [over.match.best]p1:
5632 //
5633 // -- if F is a static member function, ICS1(F) is defined such
5634 // that ICS1(F) is neither better nor worse than ICS1(G) for
5635 // any function G, and, symmetrically, ICS1(G) is neither
5636 // better nor worse than ICS1(F).
5637 unsigned StartArg = 0;
5638 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5639 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005640
Douglas Gregord3cb3562009-07-07 23:38:56 +00005641 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005642 // A viable function F1 is defined to be a better function than another
5643 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005644 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005645 unsigned NumArgs = Cand1.Conversions.size();
5646 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5647 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005648 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005649 switch (CompareImplicitConversionSequences(S,
5650 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005651 Cand2.Conversions[ArgIdx])) {
5652 case ImplicitConversionSequence::Better:
5653 // Cand1 has a better conversion sequence.
5654 HasBetterConversion = true;
5655 break;
5656
5657 case ImplicitConversionSequence::Worse:
5658 // Cand1 can't be better than Cand2.
5659 return false;
5660
5661 case ImplicitConversionSequence::Indistinguishable:
5662 // Do nothing.
5663 break;
5664 }
5665 }
5666
Mike Stump11289f42009-09-09 15:08:12 +00005667 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005668 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005669 if (HasBetterConversion)
5670 return true;
5671
Mike Stump11289f42009-09-09 15:08:12 +00005672 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005673 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005674 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005675 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5676 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005677
5678 // -- F1 and F2 are function template specializations, and the function
5679 // template for F1 is more specialized than the template for F2
5680 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005681 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005682 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5683 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005684 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005685 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5686 Cand2.Function->getPrimaryTemplate(),
5687 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005688 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5689 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005690 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005691
Douglas Gregora1f013e2008-11-07 22:36:19 +00005692 // -- the context is an initialization by user-defined conversion
5693 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5694 // from the return type of F1 to the destination type (i.e.,
5695 // the type of the entity being initialized) is a better
5696 // conversion sequence than the standard conversion sequence
5697 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005698 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005699 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005700 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005701 switch (CompareStandardConversionSequences(S,
5702 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005703 Cand2.FinalConversion)) {
5704 case ImplicitConversionSequence::Better:
5705 // Cand1 has a better conversion sequence.
5706 return true;
5707
5708 case ImplicitConversionSequence::Worse:
5709 // Cand1 can't be better than Cand2.
5710 return false;
5711
5712 case ImplicitConversionSequence::Indistinguishable:
5713 // Do nothing
5714 break;
5715 }
5716 }
5717
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005718 return false;
5719}
5720
Mike Stump11289f42009-09-09 15:08:12 +00005721/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005722/// within an overload candidate set.
5723///
5724/// \param CandidateSet the set of candidate functions.
5725///
5726/// \param Loc the location of the function name (or operator symbol) for
5727/// which overload resolution occurs.
5728///
Mike Stump11289f42009-09-09 15:08:12 +00005729/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005730/// function, Best points to the candidate function found.
5731///
5732/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005733OverloadingResult
5734OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005735 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005736 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005737 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005738 Best = end();
5739 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5740 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005741 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5742 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005743 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005744 }
5745
5746 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005747 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005748 return OR_No_Viable_Function;
5749
5750 // Make sure that this function is better than every other viable
5751 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005752 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005753 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005754 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005755 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5756 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005757 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005758 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005759 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005760 }
Mike Stump11289f42009-09-09 15:08:12 +00005761
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005762 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005763 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005764 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005765 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005766 return OR_Deleted;
5767
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005768 // C++ [basic.def.odr]p2:
5769 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005770 // when referred to from a potentially-evaluated expression. [Note: this
5771 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005772 // (clause 13), user-defined conversions (12.3.2), allocation function for
5773 // placement new (5.3.4), as well as non-default initialization (8.5).
5774 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005775 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005776
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005777 return OR_Success;
5778}
5779
John McCall53262c92010-01-12 02:15:36 +00005780namespace {
5781
5782enum OverloadCandidateKind {
5783 oc_function,
5784 oc_method,
5785 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005786 oc_function_template,
5787 oc_method_template,
5788 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005789 oc_implicit_default_constructor,
5790 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005791 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005792};
5793
John McCalle1ac8d12010-01-13 00:25:19 +00005794OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5795 FunctionDecl *Fn,
5796 std::string &Description) {
5797 bool isTemplate = false;
5798
5799 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5800 isTemplate = true;
5801 Description = S.getTemplateArgumentBindingsText(
5802 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5803 }
John McCallfd0b2f82010-01-06 09:43:14 +00005804
5805 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005806 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005807 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005808
John McCall53262c92010-01-12 02:15:36 +00005809 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5810 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005811 }
5812
5813 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5814 // This actually gets spelled 'candidate function' for now, but
5815 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005816 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005817 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005818
Douglas Gregorec3bec02010-09-27 22:37:28 +00005819 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005820 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005821 return oc_implicit_copy_assignment;
5822 }
5823
John McCalle1ac8d12010-01-13 00:25:19 +00005824 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005825}
5826
5827} // end anonymous namespace
5828
5829// Notes the location of an overload candidate.
5830void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005831 std::string FnDesc;
5832 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5833 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5834 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005835}
5836
John McCall0d1da222010-01-12 00:44:57 +00005837/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5838/// "lead" diagnostic; it will be given two arguments, the source and
5839/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005840void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5841 Sema &S,
5842 SourceLocation CaretLoc,
5843 const PartialDiagnostic &PDiag) const {
5844 S.Diag(CaretLoc, PDiag)
5845 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005846 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005847 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5848 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005849 }
John McCall12f97bc2010-01-08 04:41:39 +00005850}
5851
John McCall0d1da222010-01-12 00:44:57 +00005852namespace {
5853
John McCall6a61b522010-01-13 09:16:55 +00005854void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5855 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5856 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005857 assert(Cand->Function && "for now, candidate must be a function");
5858 FunctionDecl *Fn = Cand->Function;
5859
5860 // There's a conversion slot for the object argument if this is a
5861 // non-constructor method. Note that 'I' corresponds the
5862 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005863 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005864 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005865 if (I == 0)
5866 isObjectArgument = true;
5867 else
5868 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005869 }
5870
John McCalle1ac8d12010-01-13 00:25:19 +00005871 std::string FnDesc;
5872 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5873
John McCall6a61b522010-01-13 09:16:55 +00005874 Expr *FromExpr = Conv.Bad.FromExpr;
5875 QualType FromTy = Conv.Bad.getFromType();
5876 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005877
John McCallfb7ad0f2010-02-02 02:42:52 +00005878 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005879 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005880 Expr *E = FromExpr->IgnoreParens();
5881 if (isa<UnaryOperator>(E))
5882 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005883 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005884
5885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5886 << (unsigned) FnKind << FnDesc
5887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5888 << ToTy << Name << I+1;
5889 return;
5890 }
5891
John McCall6d174642010-01-23 08:10:49 +00005892 // Do some hand-waving analysis to see if the non-viability is due
5893 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005894 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5895 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5896 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5897 CToTy = RT->getPointeeType();
5898 else {
5899 // TODO: detect and diagnose the full richness of const mismatches.
5900 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5901 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5902 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5903 }
5904
5905 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5906 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5907 // It is dumb that we have to do this here.
5908 while (isa<ArrayType>(CFromTy))
5909 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5910 while (isa<ArrayType>(CToTy))
5911 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5912
5913 Qualifiers FromQs = CFromTy.getQualifiers();
5914 Qualifiers ToQs = CToTy.getQualifiers();
5915
5916 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5918 << (unsigned) FnKind << FnDesc
5919 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5920 << FromTy
5921 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5922 << (unsigned) isObjectArgument << I+1;
5923 return;
5924 }
5925
5926 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5927 assert(CVR && "unexpected qualifiers mismatch");
5928
5929 if (isObjectArgument) {
5930 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5931 << (unsigned) FnKind << FnDesc
5932 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5933 << FromTy << (CVR - 1);
5934 } else {
5935 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5936 << (unsigned) FnKind << FnDesc
5937 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5938 << FromTy << (CVR - 1) << I+1;
5939 }
5940 return;
5941 }
5942
John McCall6d174642010-01-23 08:10:49 +00005943 // Diagnose references or pointers to incomplete types differently,
5944 // since it's far from impossible that the incompleteness triggered
5945 // the failure.
5946 QualType TempFromTy = FromTy.getNonReferenceType();
5947 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5948 TempFromTy = PTy->getPointeeType();
5949 if (TempFromTy->isIncompleteType()) {
5950 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5951 << (unsigned) FnKind << FnDesc
5952 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5953 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5954 return;
5955 }
5956
Douglas Gregor56f2e342010-06-30 23:01:39 +00005957 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005958 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005959 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5960 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5961 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5962 FromPtrTy->getPointeeType()) &&
5963 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5964 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5965 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5966 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005967 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005968 }
5969 } else if (const ObjCObjectPointerType *FromPtrTy
5970 = FromTy->getAs<ObjCObjectPointerType>()) {
5971 if (const ObjCObjectPointerType *ToPtrTy
5972 = ToTy->getAs<ObjCObjectPointerType>())
5973 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5974 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5975 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5976 FromPtrTy->getPointeeType()) &&
5977 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005978 BaseToDerivedConversion = 2;
5979 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5980 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5981 !FromTy->isIncompleteType() &&
5982 !ToRefTy->getPointeeType()->isIncompleteType() &&
5983 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5984 BaseToDerivedConversion = 3;
5985 }
5986
5987 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005988 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005989 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005990 << (unsigned) FnKind << FnDesc
5991 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005992 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005993 << FromTy << ToTy << I+1;
5994 return;
5995 }
5996
John McCall47000992010-01-14 03:28:57 +00005997 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005998 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5999 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006000 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006001 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006002}
6003
6004void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6005 unsigned NumFormalArgs) {
6006 // TODO: treat calls to a missing default constructor as a special case
6007
6008 FunctionDecl *Fn = Cand->Function;
6009 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6010
6011 unsigned MinParams = Fn->getMinRequiredArguments();
6012
6013 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00006014 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00006015 unsigned mode, modeCount;
6016 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006017 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6018 (Cand->FailureKind == ovl_fail_bad_deduction &&
6019 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00006020 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6021 mode = 0; // "at least"
6022 else
6023 mode = 2; // "exactly"
6024 modeCount = MinParams;
6025 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006026 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6027 (Cand->FailureKind == ovl_fail_bad_deduction &&
6028 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006029 if (MinParams != FnTy->getNumArgs())
6030 mode = 1; // "at most"
6031 else
6032 mode = 2; // "exactly"
6033 modeCount = FnTy->getNumArgs();
6034 }
6035
6036 std::string Description;
6037 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6038
6039 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006040 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6041 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006042}
6043
John McCall8b9ed552010-02-01 18:53:26 +00006044/// Diagnose a failed template-argument deduction.
6045void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6046 Expr **Args, unsigned NumArgs) {
6047 FunctionDecl *Fn = Cand->Function; // pattern
6048
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006049 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006050 NamedDecl *ParamD;
6051 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6052 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6053 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006054 switch (Cand->DeductionFailure.Result) {
6055 case Sema::TDK_Success:
6056 llvm_unreachable("TDK_success while diagnosing bad deduction");
6057
6058 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006059 assert(ParamD && "no parameter found for incomplete deduction result");
6060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6061 << ParamD->getDeclName();
6062 return;
6063 }
6064
John McCall42d7d192010-08-05 09:05:08 +00006065 case Sema::TDK_Underqualified: {
6066 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6067 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6068
6069 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6070
6071 // Param will have been canonicalized, but it should just be a
6072 // qualified version of ParamD, so move the qualifiers to that.
6073 QualifierCollector Qs(S.Context);
6074 Qs.strip(Param);
6075 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6076 assert(S.Context.hasSameType(Param, NonCanonParam));
6077
6078 // Arg has also been canonicalized, but there's nothing we can do
6079 // about that. It also doesn't matter as much, because it won't
6080 // have any template parameters in it (because deduction isn't
6081 // done on dependent types).
6082 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6083
6084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6085 << ParamD->getDeclName() << Arg << NonCanonParam;
6086 return;
6087 }
6088
6089 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006090 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006091 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006092 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006093 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006094 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006095 which = 1;
6096 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006097 which = 2;
6098 }
6099
6100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6101 << which << ParamD->getDeclName()
6102 << *Cand->DeductionFailure.getFirstArg()
6103 << *Cand->DeductionFailure.getSecondArg();
6104 return;
6105 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006106
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006107 case Sema::TDK_InvalidExplicitArguments:
6108 assert(ParamD && "no parameter found for invalid explicit arguments");
6109 if (ParamD->getDeclName())
6110 S.Diag(Fn->getLocation(),
6111 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6112 << ParamD->getDeclName();
6113 else {
6114 int index = 0;
6115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6116 index = TTP->getIndex();
6117 else if (NonTypeTemplateParmDecl *NTTP
6118 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6119 index = NTTP->getIndex();
6120 else
6121 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6122 S.Diag(Fn->getLocation(),
6123 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6124 << (index + 1);
6125 }
6126 return;
6127
Douglas Gregor02eb4832010-05-08 18:13:28 +00006128 case Sema::TDK_TooManyArguments:
6129 case Sema::TDK_TooFewArguments:
6130 DiagnoseArityMismatch(S, Cand, NumArgs);
6131 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006132
6133 case Sema::TDK_InstantiationDepth:
6134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6135 return;
6136
6137 case Sema::TDK_SubstitutionFailure: {
6138 std::string ArgString;
6139 if (TemplateArgumentList *Args
6140 = Cand->DeductionFailure.getTemplateArgumentList())
6141 ArgString = S.getTemplateArgumentBindingsText(
6142 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6143 *Args);
6144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6145 << ArgString;
6146 return;
6147 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006148
John McCall8b9ed552010-02-01 18:53:26 +00006149 // TODO: diagnose these individually, then kill off
6150 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006151 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006152 case Sema::TDK_FailedOverloadResolution:
6153 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6154 return;
6155 }
6156}
6157
6158/// Generates a 'note' diagnostic for an overload candidate. We've
6159/// already generated a primary error at the call site.
6160///
6161/// It really does need to be a single diagnostic with its caret
6162/// pointed at the candidate declaration. Yes, this creates some
6163/// major challenges of technical writing. Yes, this makes pointing
6164/// out problems with specific arguments quite awkward. It's still
6165/// better than generating twenty screens of text for every failed
6166/// overload.
6167///
6168/// It would be great to be able to express per-candidate problems
6169/// more richly for those diagnostic clients that cared, but we'd
6170/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006171void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6172 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006173 FunctionDecl *Fn = Cand->Function;
6174
John McCall12f97bc2010-01-08 04:41:39 +00006175 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006176 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006177 std::string FnDesc;
6178 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006179
6180 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006181 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006182 return;
John McCall12f97bc2010-01-08 04:41:39 +00006183 }
6184
John McCalle1ac8d12010-01-13 00:25:19 +00006185 // We don't really have anything else to say about viable candidates.
6186 if (Cand->Viable) {
6187 S.NoteOverloadCandidate(Fn);
6188 return;
6189 }
John McCall0d1da222010-01-12 00:44:57 +00006190
John McCall6a61b522010-01-13 09:16:55 +00006191 switch (Cand->FailureKind) {
6192 case ovl_fail_too_many_arguments:
6193 case ovl_fail_too_few_arguments:
6194 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006195
John McCall6a61b522010-01-13 09:16:55 +00006196 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006197 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6198
John McCallfe796dd2010-01-23 05:17:32 +00006199 case ovl_fail_trivial_conversion:
6200 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006201 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006202 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006203
John McCall65eb8792010-02-25 01:37:24 +00006204 case ovl_fail_bad_conversion: {
6205 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6206 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006207 if (Cand->Conversions[I].isBad())
6208 return DiagnoseBadConversion(S, Cand, I);
6209
6210 // FIXME: this currently happens when we're called from SemaInit
6211 // when user-conversion overload fails. Figure out how to handle
6212 // those conditions and diagnose them well.
6213 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006214 }
John McCall65eb8792010-02-25 01:37:24 +00006215 }
John McCalld3224162010-01-08 00:58:21 +00006216}
6217
6218void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6219 // Desugar the type of the surrogate down to a function type,
6220 // retaining as many typedefs as possible while still showing
6221 // the function type (and, therefore, its parameter types).
6222 QualType FnType = Cand->Surrogate->getConversionType();
6223 bool isLValueReference = false;
6224 bool isRValueReference = false;
6225 bool isPointer = false;
6226 if (const LValueReferenceType *FnTypeRef =
6227 FnType->getAs<LValueReferenceType>()) {
6228 FnType = FnTypeRef->getPointeeType();
6229 isLValueReference = true;
6230 } else if (const RValueReferenceType *FnTypeRef =
6231 FnType->getAs<RValueReferenceType>()) {
6232 FnType = FnTypeRef->getPointeeType();
6233 isRValueReference = true;
6234 }
6235 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6236 FnType = FnTypePtr->getPointeeType();
6237 isPointer = true;
6238 }
6239 // Desugar down to a function type.
6240 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6241 // Reconstruct the pointer/reference as appropriate.
6242 if (isPointer) FnType = S.Context.getPointerType(FnType);
6243 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6244 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6245
6246 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6247 << FnType;
6248}
6249
6250void NoteBuiltinOperatorCandidate(Sema &S,
6251 const char *Opc,
6252 SourceLocation OpLoc,
6253 OverloadCandidate *Cand) {
6254 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6255 std::string TypeStr("operator");
6256 TypeStr += Opc;
6257 TypeStr += "(";
6258 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6259 if (Cand->Conversions.size() == 1) {
6260 TypeStr += ")";
6261 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6262 } else {
6263 TypeStr += ", ";
6264 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6265 TypeStr += ")";
6266 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6267 }
6268}
6269
6270void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6271 OverloadCandidate *Cand) {
6272 unsigned NoOperands = Cand->Conversions.size();
6273 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6274 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006275 if (ICS.isBad()) break; // all meaningless after first invalid
6276 if (!ICS.isAmbiguous()) continue;
6277
John McCall5c32be02010-08-24 20:38:10 +00006278 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006279 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006280 }
6281}
6282
John McCall3712d9e2010-01-15 23:32:50 +00006283SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6284 if (Cand->Function)
6285 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006286 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006287 return Cand->Surrogate->getLocation();
6288 return SourceLocation();
6289}
6290
John McCallad2587a2010-01-12 00:48:53 +00006291struct CompareOverloadCandidatesForDisplay {
6292 Sema &S;
6293 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006294
6295 bool operator()(const OverloadCandidate *L,
6296 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006297 // Fast-path this check.
6298 if (L == R) return false;
6299
John McCall12f97bc2010-01-08 04:41:39 +00006300 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006301 if (L->Viable) {
6302 if (!R->Viable) return true;
6303
6304 // TODO: introduce a tri-valued comparison for overload
6305 // candidates. Would be more worthwhile if we had a sort
6306 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006307 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6308 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006309 } else if (R->Viable)
6310 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006311
John McCall3712d9e2010-01-15 23:32:50 +00006312 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006313
John McCall3712d9e2010-01-15 23:32:50 +00006314 // Criteria by which we can sort non-viable candidates:
6315 if (!L->Viable) {
6316 // 1. Arity mismatches come after other candidates.
6317 if (L->FailureKind == ovl_fail_too_many_arguments ||
6318 L->FailureKind == ovl_fail_too_few_arguments)
6319 return false;
6320 if (R->FailureKind == ovl_fail_too_many_arguments ||
6321 R->FailureKind == ovl_fail_too_few_arguments)
6322 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006323
John McCallfe796dd2010-01-23 05:17:32 +00006324 // 2. Bad conversions come first and are ordered by the number
6325 // of bad conversions and quality of good conversions.
6326 if (L->FailureKind == ovl_fail_bad_conversion) {
6327 if (R->FailureKind != ovl_fail_bad_conversion)
6328 return true;
6329
6330 // If there's any ordering between the defined conversions...
6331 // FIXME: this might not be transitive.
6332 assert(L->Conversions.size() == R->Conversions.size());
6333
6334 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006335 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6336 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006337 switch (CompareImplicitConversionSequences(S,
6338 L->Conversions[I],
6339 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006340 case ImplicitConversionSequence::Better:
6341 leftBetter++;
6342 break;
6343
6344 case ImplicitConversionSequence::Worse:
6345 leftBetter--;
6346 break;
6347
6348 case ImplicitConversionSequence::Indistinguishable:
6349 break;
6350 }
6351 }
6352 if (leftBetter > 0) return true;
6353 if (leftBetter < 0) return false;
6354
6355 } else if (R->FailureKind == ovl_fail_bad_conversion)
6356 return false;
6357
John McCall3712d9e2010-01-15 23:32:50 +00006358 // TODO: others?
6359 }
6360
6361 // Sort everything else by location.
6362 SourceLocation LLoc = GetLocationForCandidate(L);
6363 SourceLocation RLoc = GetLocationForCandidate(R);
6364
6365 // Put candidates without locations (e.g. builtins) at the end.
6366 if (LLoc.isInvalid()) return false;
6367 if (RLoc.isInvalid()) return true;
6368
6369 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006370 }
6371};
6372
John McCallfe796dd2010-01-23 05:17:32 +00006373/// CompleteNonViableCandidate - Normally, overload resolution only
6374/// computes up to the first
6375void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6376 Expr **Args, unsigned NumArgs) {
6377 assert(!Cand->Viable);
6378
6379 // Don't do anything on failures other than bad conversion.
6380 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6381
6382 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006383 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006384 unsigned ConvCount = Cand->Conversions.size();
6385 while (true) {
6386 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6387 ConvIdx++;
6388 if (Cand->Conversions[ConvIdx - 1].isBad())
6389 break;
6390 }
6391
6392 if (ConvIdx == ConvCount)
6393 return;
6394
John McCall65eb8792010-02-25 01:37:24 +00006395 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6396 "remaining conversion is initialized?");
6397
Douglas Gregoradc7a702010-04-16 17:45:54 +00006398 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006399 // operation somehow.
6400 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006401
6402 const FunctionProtoType* Proto;
6403 unsigned ArgIdx = ConvIdx;
6404
6405 if (Cand->IsSurrogate) {
6406 QualType ConvType
6407 = Cand->Surrogate->getConversionType().getNonReferenceType();
6408 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6409 ConvType = ConvPtrType->getPointeeType();
6410 Proto = ConvType->getAs<FunctionProtoType>();
6411 ArgIdx--;
6412 } else if (Cand->Function) {
6413 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6414 if (isa<CXXMethodDecl>(Cand->Function) &&
6415 !isa<CXXConstructorDecl>(Cand->Function))
6416 ArgIdx--;
6417 } else {
6418 // Builtin binary operator with a bad first conversion.
6419 assert(ConvCount <= 3);
6420 for (; ConvIdx != ConvCount; ++ConvIdx)
6421 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006422 = TryCopyInitialization(S, Args[ConvIdx],
6423 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6424 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006425 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006426 return;
6427 }
6428
6429 // Fill in the rest of the conversions.
6430 unsigned NumArgsInProto = Proto->getNumArgs();
6431 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6432 if (ArgIdx < NumArgsInProto)
6433 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006434 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6435 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006436 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006437 else
6438 Cand->Conversions[ConvIdx].setEllipsis();
6439 }
6440}
6441
John McCalld3224162010-01-08 00:58:21 +00006442} // end anonymous namespace
6443
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006444/// PrintOverloadCandidates - When overload resolution fails, prints
6445/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006446/// set.
John McCall5c32be02010-08-24 20:38:10 +00006447void OverloadCandidateSet::NoteCandidates(Sema &S,
6448 OverloadCandidateDisplayKind OCD,
6449 Expr **Args, unsigned NumArgs,
6450 const char *Opc,
6451 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006452 // Sort the candidates by viability and position. Sorting directly would
6453 // be prohibitive, so we make a set of pointers and sort those.
6454 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006455 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6456 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006457 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006458 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006459 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006460 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006461 if (Cand->Function || Cand->IsSurrogate)
6462 Cands.push_back(Cand);
6463 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6464 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006465 }
6466 }
6467
John McCallad2587a2010-01-12 00:48:53 +00006468 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006469 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006470
John McCall0d1da222010-01-12 00:44:57 +00006471 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006472
John McCall12f97bc2010-01-08 04:41:39 +00006473 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006474 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006475 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006476 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6477 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006478
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006479 // Set an arbitrary limit on the number of candidate functions we'll spam
6480 // the user with. FIXME: This limit should depend on details of the
6481 // candidate list.
6482 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6483 break;
6484 }
6485 ++CandsShown;
6486
John McCalld3224162010-01-08 00:58:21 +00006487 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006488 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006489 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006490 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006491 else {
6492 assert(Cand->Viable &&
6493 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006494 // Generally we only see ambiguities including viable builtin
6495 // operators if overload resolution got screwed up by an
6496 // ambiguous user-defined conversion.
6497 //
6498 // FIXME: It's quite possible for different conversions to see
6499 // different ambiguities, though.
6500 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006501 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006502 ReportedAmbiguousConversions = true;
6503 }
John McCalld3224162010-01-08 00:58:21 +00006504
John McCall0d1da222010-01-12 00:44:57 +00006505 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006506 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006507 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006508 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006509
6510 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006511 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006512}
6513
John McCalla0296f72010-03-19 07:35:19 +00006514static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006515 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006516 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006517
John McCalla0296f72010-03-19 07:35:19 +00006518 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006519}
6520
Douglas Gregorcd695e52008-11-10 20:40:00 +00006521/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6522/// an overloaded function (C++ [over.over]), where @p From is an
6523/// expression with overloaded function type and @p ToType is the type
6524/// we're trying to resolve to. For example:
6525///
6526/// @code
6527/// int f(double);
6528/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006529///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006530/// int (*pfd)(double) = f; // selects f(double)
6531/// @endcode
6532///
6533/// This routine returns the resulting FunctionDecl if it could be
6534/// resolved, and NULL otherwise. When @p Complain is true, this
6535/// routine will emit diagnostics if there is an error.
6536FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006537Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006538 bool Complain,
6539 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006540 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006541 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006542 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006543 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006544 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006545 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006546 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006547 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006548 FunctionType = MemTypePtr->getPointeeType();
6549 IsMember = true;
6550 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006551
Douglas Gregorcd695e52008-11-10 20:40:00 +00006552 // C++ [over.over]p1:
6553 // [...] [Note: any redundant set of parentheses surrounding the
6554 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006555 // C++ [over.over]p1:
6556 // [...] The overloaded function name can be preceded by the &
6557 // operator.
John McCall7d460512010-08-24 23:26:21 +00006558 // However, remember whether the expression has member-pointer form:
6559 // C++ [expr.unary.op]p4:
6560 // A pointer to member is only formed when an explicit & is used
6561 // and its operand is a qualified-id not enclosed in
6562 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006563 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6564 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006565
Douglas Gregor064fdb22010-04-14 23:11:21 +00006566 // We expect a pointer or reference to function, or a function pointer.
6567 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6568 if (!FunctionType->isFunctionType()) {
6569 if (Complain)
6570 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6571 << OvlExpr->getName() << ToType;
6572
6573 return 0;
6574 }
6575
John McCall24d18942010-08-24 22:52:39 +00006576 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006577 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006578 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006579 if (!Complain) return 0;
6580
6581 // TODO: Should we condition this on whether any functions might
6582 // have matched, or is it more appropriate to do that in callers?
6583 // TODO: a fixit wouldn't hurt.
6584 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6585 << ToType << OvlExpr->getSourceRange();
6586 return 0;
6587 }
6588
6589 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6590 if (OvlExpr->hasExplicitTemplateArgs()) {
6591 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6592 ExplicitTemplateArgs = &ETABuffer;
6593 }
6594
Douglas Gregor064fdb22010-04-14 23:11:21 +00006595 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006596
Douglas Gregorcd695e52008-11-10 20:40:00 +00006597 // Look through all of the overloaded functions, searching for one
6598 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006599 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006600 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006601
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006602 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006603 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6604 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006605 // Look through any using declarations to find the underlying function.
6606 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6607
Douglas Gregorcd695e52008-11-10 20:40:00 +00006608 // C++ [over.over]p3:
6609 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006610 // targets of type "pointer-to-function" or "reference-to-function."
6611 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006612 // type "pointer-to-member-function."
6613 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006614
Mike Stump11289f42009-09-09 15:08:12 +00006615 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006616 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006617 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006618 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006619 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006620 // static when converting to member pointer.
6621 if (Method->isStatic() == IsMember)
6622 continue;
6623 } else if (IsMember)
6624 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006625
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006626 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006627 // If the name is a function template, template argument deduction is
6628 // done (14.8.2.2), and if the argument deduction succeeds, the
6629 // resulting template argument list is used to generate a single
6630 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006631 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006632 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006633 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006634 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006635 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006636 FunctionType, Specialization, Info)) {
6637 // FIXME: make a note of the failed deduction for diagnostics.
6638 (void)Result;
6639 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006640 // Template argument deduction ensures that we have an exact match.
6641 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006642 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006643 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006644 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006645 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006646 }
John McCalld14a8642009-11-21 08:51:07 +00006647
6648 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006649 }
Mike Stump11289f42009-09-09 15:08:12 +00006650
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006652 // Skip non-static functions when converting to pointer, and static
6653 // when converting to member pointer.
6654 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006655 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006656
6657 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006658 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006659 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006660 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006661 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006662
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006663 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006664 QualType ResultTy;
6665 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6666 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6667 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006668 Matches.push_back(std::make_pair(I.getPair(),
6669 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006670 FoundNonTemplateFunction = true;
6671 }
Mike Stump11289f42009-09-09 15:08:12 +00006672 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006673 }
6674
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006675 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006676 if (Matches.empty()) {
6677 if (Complain) {
6678 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6679 << OvlExpr->getName() << FunctionType;
6680 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6681 E = OvlExpr->decls_end();
6682 I != E; ++I)
6683 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6684 NoteOverloadCandidate(F);
6685 }
6686
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006687 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006688 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006689 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006690 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006691 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006692 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006693 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006694 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006695 return Result;
6696 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006697
6698 // C++ [over.over]p4:
6699 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006700 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006701 // [...] and any given function template specialization F1 is
6702 // eliminated if the set contains a second function template
6703 // specialization whose function template is more specialized
6704 // than the function template of F1 according to the partial
6705 // ordering rules of 14.5.5.2.
6706
6707 // The algorithm specified above is quadratic. We instead use a
6708 // two-pass algorithm (similar to the one used to identify the
6709 // best viable function in an overload set) that identifies the
6710 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006711
6712 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6713 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6714 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006715
6716 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006717 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006718 TPOC_Other, From->getLocStart(),
6719 PDiag(),
6720 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006721 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006722 PDiag(diag::note_ovl_candidate)
6723 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006724 if (Result == MatchesCopy.end())
6725 return 0;
6726
John McCall58cc69d2010-01-27 01:50:18 +00006727 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006728 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006729 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006730 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006731 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006732 }
Mike Stump11289f42009-09-09 15:08:12 +00006733
Douglas Gregorfae1d712009-09-26 03:56:17 +00006734 // [...] any function template specializations in the set are
6735 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006736 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006737 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006738 ++I;
6739 else {
John McCalla0296f72010-03-19 07:35:19 +00006740 Matches[I] = Matches[--N];
6741 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006742 }
6743 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006744
Mike Stump11289f42009-09-09 15:08:12 +00006745 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006746 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006747 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006748 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006749 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006750 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006751 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6752 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006753 }
Mike Stump11289f42009-09-09 15:08:12 +00006754
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006755 // FIXME: We should probably return the same thing that BestViableFunction
6756 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006757 if (Complain) {
6758 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6759 << Matches[0].second->getDeclName();
6760 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6761 NoteOverloadCandidate(Matches[I].second);
6762 }
6763
Douglas Gregorcd695e52008-11-10 20:40:00 +00006764 return 0;
6765}
6766
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006767/// \brief Given an expression that refers to an overloaded function, try to
6768/// resolve that overloaded function expression down to a single function.
6769///
6770/// This routine can only resolve template-ids that refer to a single function
6771/// template, where that template-id refers to a single template whose template
6772/// arguments are either provided by the template-id or have defaults,
6773/// as described in C++0x [temp.arg.explicit]p3.
6774FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6775 // C++ [over.over]p1:
6776 // [...] [Note: any redundant set of parentheses surrounding the
6777 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006778 // C++ [over.over]p1:
6779 // [...] The overloaded function name can be preceded by the &
6780 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006781
6782 if (From->getType() != Context.OverloadTy)
6783 return 0;
6784
John McCall8d08b9b2010-08-27 09:08:28 +00006785 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006786
6787 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006788 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006789 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006790
6791 TemplateArgumentListInfo ExplicitTemplateArgs;
6792 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006793
6794 // Look through all of the overloaded functions, searching for one
6795 // whose type matches exactly.
6796 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006797 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6798 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006799 // C++0x [temp.arg.explicit]p3:
6800 // [...] In contexts where deduction is done and fails, or in contexts
6801 // where deduction is not done, if a template argument list is
6802 // specified and it, along with any default template arguments,
6803 // identifies a single function template specialization, then the
6804 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006805 FunctionTemplateDecl *FunctionTemplate
6806 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006807
6808 // C++ [over.over]p2:
6809 // If the name is a function template, template argument deduction is
6810 // done (14.8.2.2), and if the argument deduction succeeds, the
6811 // resulting template argument list is used to generate a single
6812 // function template specialization, which is added to the set of
6813 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006814 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006815 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006816 if (TemplateDeductionResult Result
6817 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6818 Specialization, Info)) {
6819 // FIXME: make a note of the failed deduction for diagnostics.
6820 (void)Result;
6821 continue;
6822 }
6823
6824 // Multiple matches; we can't resolve to a single declaration.
6825 if (Matched)
6826 return 0;
6827
6828 Matched = Specialization;
6829 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006830
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006831 return Matched;
6832}
6833
Douglas Gregorcabea402009-09-22 15:41:20 +00006834/// \brief Add a single candidate to the overload set.
6835static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006836 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006837 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006838 Expr **Args, unsigned NumArgs,
6839 OverloadCandidateSet &CandidateSet,
6840 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006841 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006842 if (isa<UsingShadowDecl>(Callee))
6843 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6844
Douglas Gregorcabea402009-09-22 15:41:20 +00006845 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006846 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006847 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006848 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006849 return;
John McCalld14a8642009-11-21 08:51:07 +00006850 }
6851
6852 if (FunctionTemplateDecl *FuncTemplate
6853 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006854 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6855 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006856 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006857 return;
6858 }
6859
6860 assert(false && "unhandled case in overloaded call candidate");
6861
6862 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006863}
6864
6865/// \brief Add the overload candidates named by callee and/or found by argument
6866/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006867void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006868 Expr **Args, unsigned NumArgs,
6869 OverloadCandidateSet &CandidateSet,
6870 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006871
6872#ifndef NDEBUG
6873 // Verify that ArgumentDependentLookup is consistent with the rules
6874 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006875 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006876 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6877 // and let Y be the lookup set produced by argument dependent
6878 // lookup (defined as follows). If X contains
6879 //
6880 // -- a declaration of a class member, or
6881 //
6882 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006883 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006884 //
6885 // -- a declaration that is neither a function or a function
6886 // template
6887 //
6888 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006889
John McCall57500772009-12-16 12:17:52 +00006890 if (ULE->requiresADL()) {
6891 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6892 E = ULE->decls_end(); I != E; ++I) {
6893 assert(!(*I)->getDeclContext()->isRecord());
6894 assert(isa<UsingShadowDecl>(*I) ||
6895 !(*I)->getDeclContext()->isFunctionOrMethod());
6896 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006897 }
6898 }
6899#endif
6900
John McCall57500772009-12-16 12:17:52 +00006901 // It would be nice to avoid this copy.
6902 TemplateArgumentListInfo TABuffer;
6903 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6904 if (ULE->hasExplicitTemplateArgs()) {
6905 ULE->copyTemplateArgumentsInto(TABuffer);
6906 ExplicitTemplateArgs = &TABuffer;
6907 }
6908
6909 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6910 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006911 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006912 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006913 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006914
John McCall57500772009-12-16 12:17:52 +00006915 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006916 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6917 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006918 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006919 CandidateSet,
6920 PartialOverloading);
6921}
John McCalld681c392009-12-16 08:11:27 +00006922
6923/// Attempts to recover from a call where no functions were found.
6924///
6925/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006926static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006927BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006928 UnresolvedLookupExpr *ULE,
6929 SourceLocation LParenLoc,
6930 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006931 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006932
6933 CXXScopeSpec SS;
6934 if (ULE->getQualifier()) {
6935 SS.setScopeRep(ULE->getQualifier());
6936 SS.setRange(ULE->getQualifierRange());
6937 }
6938
John McCall57500772009-12-16 12:17:52 +00006939 TemplateArgumentListInfo TABuffer;
6940 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6941 if (ULE->hasExplicitTemplateArgs()) {
6942 ULE->copyTemplateArgumentsInto(TABuffer);
6943 ExplicitTemplateArgs = &TABuffer;
6944 }
6945
John McCalld681c392009-12-16 08:11:27 +00006946 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6947 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006948 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006949 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006950
John McCall57500772009-12-16 12:17:52 +00006951 assert(!R.empty() && "lookup results empty despite recovery");
6952
6953 // Build an implicit member call if appropriate. Just drop the
6954 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006955 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006956 if ((*R.begin())->isCXXClassMember())
6957 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6958 else if (ExplicitTemplateArgs)
6959 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6960 else
6961 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6962
6963 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006964 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006965
6966 // This shouldn't cause an infinite loop because we're giving it
6967 // an expression with non-empty lookup results, which should never
6968 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006969 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006970 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006971}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006972
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006973/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006974/// (which eventually refers to the declaration Func) and the call
6975/// arguments Args/NumArgs, attempt to resolve the function call down
6976/// to a specific function. If overload resolution succeeds, returns
6977/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006978/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006979/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006980ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006981Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006982 SourceLocation LParenLoc,
6983 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006984 SourceLocation RParenLoc) {
6985#ifndef NDEBUG
6986 if (ULE->requiresADL()) {
6987 // To do ADL, we must have found an unqualified name.
6988 assert(!ULE->getQualifier() && "qualified name with ADL");
6989
6990 // We don't perform ADL for implicit declarations of builtins.
6991 // Verify that this was correctly set up.
6992 FunctionDecl *F;
6993 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6994 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6995 F->getBuiltinID() && F->isImplicit())
6996 assert(0 && "performing ADL for builtin");
6997
6998 // We don't perform ADL in C.
6999 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7000 }
7001#endif
7002
John McCallbc077cf2010-02-08 23:07:23 +00007003 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007004
John McCall57500772009-12-16 12:17:52 +00007005 // Add the functions denoted by the callee to the set of candidate
7006 // functions, including those from argument-dependent lookup.
7007 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007008
7009 // If we found nothing, try to recover.
7010 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7011 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007012 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007013 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007014 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007015
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007016 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007017 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007018 case OR_Success: {
7019 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007020 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00007021 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007022 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00007023 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
7024 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007025
7026 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007027 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007028 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007029 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007030 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007031 break;
7032
7033 case OR_Ambiguous:
7034 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007035 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007036 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007037 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007038
7039 case OR_Deleted:
7040 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7041 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007042 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007043 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007044 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007045 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007046 }
7047
Douglas Gregorb412e172010-07-25 18:17:45 +00007048 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007049 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007050}
7051
John McCall4c4c1df2010-01-26 03:27:55 +00007052static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007053 return Functions.size() > 1 ||
7054 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7055}
7056
Douglas Gregor084d8552009-03-13 23:49:33 +00007057/// \brief Create a unary operation that may resolve to an overloaded
7058/// operator.
7059///
7060/// \param OpLoc The location of the operator itself (e.g., '*').
7061///
7062/// \param OpcIn The UnaryOperator::Opcode that describes this
7063/// operator.
7064///
7065/// \param Functions The set of non-member functions that will be
7066/// considered by overload resolution. The caller needs to build this
7067/// set based on the context using, e.g.,
7068/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7069/// set should not contain any member functions; those will be added
7070/// by CreateOverloadedUnaryOp().
7071///
7072/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007073ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007074Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7075 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007076 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007077 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007078
7079 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7080 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7081 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007082 // TODO: provide better source location info.
7083 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007084
John McCalle26a8722010-12-04 08:14:53 +00007085 if (Input->getObjectKind() == OK_ObjCProperty)
7086 ConvertPropertyForRValue(Input);
7087
Douglas Gregor084d8552009-03-13 23:49:33 +00007088 Expr *Args[2] = { Input, 0 };
7089 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007090
Douglas Gregor084d8552009-03-13 23:49:33 +00007091 // For post-increment and post-decrement, add the implicit '0' as
7092 // the second argument, so that we know this is a post-increment or
7093 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007094 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007095 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007096 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7097 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007098 NumArgs = 2;
7099 }
7100
7101 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007102 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007103 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007104 Opc,
7105 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007106 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007107 OpLoc));
7108
John McCall58cc69d2010-01-27 01:50:18 +00007109 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007110 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007111 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007112 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007113 /*ADL*/ true, IsOverloaded(Fns),
7114 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007115 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7116 &Args[0], NumArgs,
7117 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007118 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007119 OpLoc));
7120 }
7121
7122 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007123 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007124
7125 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007126 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007127
7128 // Add operator candidates that are member functions.
7129 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7130
John McCall4c4c1df2010-01-26 03:27:55 +00007131 // Add candidates from ADL.
7132 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007133 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007134 /*ExplicitTemplateArgs*/ 0,
7135 CandidateSet);
7136
Douglas Gregor084d8552009-03-13 23:49:33 +00007137 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007138 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007139
7140 // Perform overload resolution.
7141 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007142 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007143 case OR_Success: {
7144 // We found a built-in operator or an overloaded operator.
7145 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007146
Douglas Gregor084d8552009-03-13 23:49:33 +00007147 if (FnDecl) {
7148 // We matched an overloaded operator. Build a call to that
7149 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007150
Douglas Gregor084d8552009-03-13 23:49:33 +00007151 // Convert the arguments.
7152 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007153 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007154
John McCall16df1e52010-03-30 21:47:33 +00007155 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7156 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007157 return ExprError();
7158 } else {
7159 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007160 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007161 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007162 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007163 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007164 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007165 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007166 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007167 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007168 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007169 }
7170
John McCall4fa0d5f2010-05-06 18:15:07 +00007171 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7172
John McCall7decc9e2010-11-18 06:31:45 +00007173 // Determine the result type.
7174 QualType ResultTy = FnDecl->getResultType();
7175 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7176 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007177
Douglas Gregor084d8552009-03-13 23:49:33 +00007178 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007179 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007180
Eli Friedman030eee42009-11-18 03:58:17 +00007181 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007182 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007183 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007184 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007185
John McCallb268a282010-08-23 23:25:46 +00007186 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007187 FnDecl))
7188 return ExprError();
7189
John McCallb268a282010-08-23 23:25:46 +00007190 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007191 } else {
7192 // We matched a built-in operator. Convert the arguments, then
7193 // break out so that we will build the appropriate built-in
7194 // operator node.
7195 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007196 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007197 return ExprError();
7198
7199 break;
7200 }
7201 }
7202
7203 case OR_No_Viable_Function:
7204 // No viable function; fall through to handling this as a
7205 // built-in operator, which will produce an error message for us.
7206 break;
7207
7208 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007209 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007210 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007211 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007212 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007213 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7214 Args, NumArgs,
7215 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007216 return ExprError();
7217
7218 case OR_Deleted:
7219 Diag(OpLoc, diag::err_ovl_deleted_oper)
7220 << Best->Function->isDeleted()
7221 << UnaryOperator::getOpcodeStr(Opc)
7222 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007224 return ExprError();
7225 }
7226
7227 // Either we found no viable overloaded operator or we matched a
7228 // built-in operator. In either case, fall through to trying to
7229 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007230 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007231}
7232
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007233/// \brief Create a binary operation that may resolve to an overloaded
7234/// operator.
7235///
7236/// \param OpLoc The location of the operator itself (e.g., '+').
7237///
7238/// \param OpcIn The BinaryOperator::Opcode that describes this
7239/// operator.
7240///
7241/// \param Functions The set of non-member functions that will be
7242/// considered by overload resolution. The caller needs to build this
7243/// set based on the context using, e.g.,
7244/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7245/// set should not contain any member functions; those will be added
7246/// by CreateOverloadedBinOp().
7247///
7248/// \param LHS Left-hand argument.
7249/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007250ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007251Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007252 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007253 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007254 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007255 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007256 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007257
7258 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7259 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7260 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7261
7262 // If either side is type-dependent, create an appropriate dependent
7263 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007264 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007265 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007266 // If there are no functions to store, just build a dependent
7267 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007268 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007269 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007270 Context.DependentTy,
7271 VK_RValue, OK_Ordinary,
7272 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007273
7274 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7275 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007276 VK_LValue,
7277 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007278 Context.DependentTy,
7279 Context.DependentTy,
7280 OpLoc));
7281 }
John McCall4c4c1df2010-01-26 03:27:55 +00007282
7283 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007284 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007285 // TODO: provide better source location info in DNLoc component.
7286 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007287 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007288 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007289 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007290 /*ADL*/ true, IsOverloaded(Fns),
7291 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007292 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007293 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007294 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007295 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007296 OpLoc));
7297 }
7298
John McCalle26a8722010-12-04 08:14:53 +00007299 // Always do property rvalue conversions on the RHS.
7300 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7301 ConvertPropertyForRValue(Args[1]);
7302
7303 // The LHS is more complicated.
7304 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7305
7306 // There's a tension for assignment operators between primitive
7307 // property assignment and the overloaded operators.
7308 if (BinaryOperator::isAssignmentOp(Opc)) {
7309 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7310
7311 // Is the property "logically" settable?
7312 bool Settable = (PRE->isExplicitProperty() ||
7313 PRE->getImplicitPropertySetter());
7314
7315 // To avoid gratuitously inventing semantics, use the primitive
7316 // unless it isn't. Thoughts in case we ever really care:
7317 // - If the property isn't logically settable, we have to
7318 // load and hope.
7319 // - If the property is settable and this is simple assignment,
7320 // we really should use the primitive.
7321 // - If the property is settable, then we could try overloading
7322 // on a generic lvalue of the appropriate type; if it works
7323 // out to a builtin candidate, we would do that same operation
7324 // on the property, and otherwise just error.
7325 if (Settable)
7326 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7327 }
7328
7329 ConvertPropertyForRValue(Args[0]);
7330 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007331
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007332 // If this is the assignment operator, we only perform overload resolution
7333 // if the left-hand side is a class or enumeration type. This is actually
7334 // a hack. The standard requires that we do overload resolution between the
7335 // various built-in candidates, but as DR507 points out, this can lead to
7336 // problems. So we do it this way, which pretty much follows what GCC does.
7337 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007338 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007339 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007340
John McCalle26a8722010-12-04 08:14:53 +00007341 // If this is the .* operator, which is not overloadable, just
7342 // create a built-in binary operator.
7343 if (Opc == BO_PtrMemD)
7344 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7345
Douglas Gregor084d8552009-03-13 23:49:33 +00007346 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007347 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007348
7349 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007350 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007351
7352 // Add operator candidates that are member functions.
7353 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7354
John McCall4c4c1df2010-01-26 03:27:55 +00007355 // Add candidates from ADL.
7356 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7357 Args, 2,
7358 /*ExplicitTemplateArgs*/ 0,
7359 CandidateSet);
7360
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007361 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007362 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007363
7364 // Perform overload resolution.
7365 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007366 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007367 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007368 // We found a built-in operator or an overloaded operator.
7369 FunctionDecl *FnDecl = Best->Function;
7370
7371 if (FnDecl) {
7372 // We matched an overloaded operator. Build a call to that
7373 // operator.
7374
7375 // Convert the arguments.
7376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007377 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007378 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007379
John McCalldadc5752010-08-24 06:29:42 +00007380 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007381 = PerformCopyInitialization(
7382 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007383 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007384 FnDecl->getParamDecl(0)),
7385 SourceLocation(),
7386 Owned(Args[1]));
7387 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007388 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007389
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007390 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007391 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007392 return ExprError();
7393
7394 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007395 } else {
7396 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007397 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007398 = PerformCopyInitialization(
7399 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007400 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007401 FnDecl->getParamDecl(0)),
7402 SourceLocation(),
7403 Owned(Args[0]));
7404 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007405 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007406
John McCalldadc5752010-08-24 06:29:42 +00007407 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007408 = PerformCopyInitialization(
7409 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007410 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007411 FnDecl->getParamDecl(1)),
7412 SourceLocation(),
7413 Owned(Args[1]));
7414 if (Arg1.isInvalid())
7415 return ExprError();
7416 Args[0] = LHS = Arg0.takeAs<Expr>();
7417 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007418 }
7419
John McCall4fa0d5f2010-05-06 18:15:07 +00007420 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7421
John McCall7decc9e2010-11-18 06:31:45 +00007422 // Determine the result type.
7423 QualType ResultTy = FnDecl->getResultType();
7424 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7425 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007426
7427 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007428 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007429
John McCallb268a282010-08-23 23:25:46 +00007430 CXXOperatorCallExpr *TheCall =
7431 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007432 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007433
John McCallb268a282010-08-23 23:25:46 +00007434 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007435 FnDecl))
7436 return ExprError();
7437
John McCallb268a282010-08-23 23:25:46 +00007438 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007439 } else {
7440 // We matched a built-in operator. Convert the arguments, then
7441 // break out so that we will build the appropriate built-in
7442 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007443 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007444 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007445 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007446 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007447 return ExprError();
7448
7449 break;
7450 }
7451 }
7452
Douglas Gregor66950a32009-09-30 21:46:01 +00007453 case OR_No_Viable_Function: {
7454 // C++ [over.match.oper]p9:
7455 // If the operator is the operator , [...] and there are no
7456 // viable functions, then the operator is assumed to be the
7457 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007458 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007459 break;
7460
Sebastian Redl027de2a2009-05-21 11:50:50 +00007461 // For class as left operand for assignment or compound assigment operator
7462 // do not fall through to handling in built-in, but report that no overloaded
7463 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007464 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007465 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007466 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007467 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7468 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007469 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007470 } else {
7471 // No viable function; try to create a built-in operation, which will
7472 // produce an error. Then, show the non-viable candidates.
7473 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007474 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007475 assert(Result.isInvalid() &&
7476 "C++ binary operator overloading is missing candidates!");
7477 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007478 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7479 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007480 return move(Result);
7481 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007482
7483 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007484 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007485 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007486 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007487 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007488 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7489 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007490 return ExprError();
7491
7492 case OR_Deleted:
7493 Diag(OpLoc, diag::err_ovl_deleted_oper)
7494 << Best->Function->isDeleted()
7495 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007496 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007497 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007498 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007499 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007500
Douglas Gregor66950a32009-09-30 21:46:01 +00007501 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007502 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007503}
7504
John McCalldadc5752010-08-24 06:29:42 +00007505ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007506Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7507 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007508 Expr *Base, Expr *Idx) {
7509 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007510 DeclarationName OpName =
7511 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7512
7513 // If either side is type-dependent, create an appropriate dependent
7514 // expression.
7515 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7516
John McCall58cc69d2010-01-27 01:50:18 +00007517 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007518 // CHECKME: no 'operator' keyword?
7519 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7520 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007521 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007522 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007523 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007524 /*ADL*/ true, /*Overloaded*/ false,
7525 UnresolvedSetIterator(),
7526 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007527 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007528
Sebastian Redladba46e2009-10-29 20:17:01 +00007529 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7530 Args, 2,
7531 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007532 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007533 RLoc));
7534 }
7535
John McCalle26a8722010-12-04 08:14:53 +00007536 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7537 ConvertPropertyForRValue(Args[0]);
7538 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7539 ConvertPropertyForRValue(Args[1]);
7540
Sebastian Redladba46e2009-10-29 20:17:01 +00007541 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007542 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007543
7544 // Subscript can only be overloaded as a member function.
7545
7546 // Add operator candidates that are member functions.
7547 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7548
7549 // Add builtin operator candidates.
7550 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7551
7552 // Perform overload resolution.
7553 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007554 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007555 case OR_Success: {
7556 // We found a built-in operator or an overloaded operator.
7557 FunctionDecl *FnDecl = Best->Function;
7558
7559 if (FnDecl) {
7560 // We matched an overloaded operator. Build a call to that
7561 // operator.
7562
John McCalla0296f72010-03-19 07:35:19 +00007563 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007564 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007565
Sebastian Redladba46e2009-10-29 20:17:01 +00007566 // Convert the arguments.
7567 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007568 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007569 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007570 return ExprError();
7571
Anders Carlssona68e51e2010-01-29 18:37:50 +00007572 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007573 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007574 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007575 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007576 FnDecl->getParamDecl(0)),
7577 SourceLocation(),
7578 Owned(Args[1]));
7579 if (InputInit.isInvalid())
7580 return ExprError();
7581
7582 Args[1] = InputInit.takeAs<Expr>();
7583
Sebastian Redladba46e2009-10-29 20:17:01 +00007584 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007585 QualType ResultTy = FnDecl->getResultType();
7586 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7587 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007588
7589 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007590 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007591
John McCallb268a282010-08-23 23:25:46 +00007592 CXXOperatorCallExpr *TheCall =
7593 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7594 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007595 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007596
John McCallb268a282010-08-23 23:25:46 +00007597 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007598 FnDecl))
7599 return ExprError();
7600
John McCallb268a282010-08-23 23:25:46 +00007601 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007602 } else {
7603 // We matched a built-in operator. Convert the arguments, then
7604 // break out so that we will build the appropriate built-in
7605 // operator node.
7606 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007607 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007608 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007609 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007610 return ExprError();
7611
7612 break;
7613 }
7614 }
7615
7616 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007617 if (CandidateSet.empty())
7618 Diag(LLoc, diag::err_ovl_no_oper)
7619 << Args[0]->getType() << /*subscript*/ 0
7620 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7621 else
7622 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7623 << Args[0]->getType()
7624 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007625 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7626 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007627 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007628 }
7629
7630 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007631 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7632 << "[]"
7633 << Args[0]->getType() << Args[1]->getType()
7634 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007635 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7636 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007637 return ExprError();
7638
7639 case OR_Deleted:
7640 Diag(LLoc, diag::err_ovl_deleted_oper)
7641 << Best->Function->isDeleted() << "[]"
7642 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007643 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7644 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007645 return ExprError();
7646 }
7647
7648 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007649 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007650}
7651
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007652/// BuildCallToMemberFunction - Build a call to a member
7653/// function. MemExpr is the expression that refers to the member
7654/// function (and includes the object parameter), Args/NumArgs are the
7655/// arguments to the function call (not including the object
7656/// parameter). The caller needs to validate that the member
7657/// expression refers to a member function or an overloaded member
7658/// function.
John McCalldadc5752010-08-24 06:29:42 +00007659ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007660Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7661 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007662 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007663 // Dig out the member expression. This holds both the object
7664 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007665 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7666
John McCall10eae182009-11-30 22:42:35 +00007667 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007668 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007669 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007670 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007671 if (isa<MemberExpr>(NakedMemExpr)) {
7672 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007673 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007674 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007675 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007676 } else {
7677 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007678 Qualifier = UnresExpr->getQualifier();
7679
John McCall6e9f8f62009-12-03 04:06:58 +00007680 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007681
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007682 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007683 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007684
John McCall2d74de92009-12-01 22:10:20 +00007685 // FIXME: avoid copy.
7686 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7687 if (UnresExpr->hasExplicitTemplateArgs()) {
7688 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7689 TemplateArgs = &TemplateArgsBuffer;
7690 }
7691
John McCall10eae182009-11-30 22:42:35 +00007692 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7693 E = UnresExpr->decls_end(); I != E; ++I) {
7694
John McCall6e9f8f62009-12-03 04:06:58 +00007695 NamedDecl *Func = *I;
7696 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7697 if (isa<UsingShadowDecl>(Func))
7698 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7699
John McCall10eae182009-11-30 22:42:35 +00007700 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007701 // If explicit template arguments were provided, we can't call a
7702 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007703 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007704 continue;
7705
John McCalla0296f72010-03-19 07:35:19 +00007706 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007707 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007708 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007709 } else {
John McCall10eae182009-11-30 22:42:35 +00007710 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007711 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007712 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007713 CandidateSet,
7714 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007715 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007716 }
Mike Stump11289f42009-09-09 15:08:12 +00007717
John McCall10eae182009-11-30 22:42:35 +00007718 DeclarationName DeclName = UnresExpr->getMemberName();
7719
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007720 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007721 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007722 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007723 case OR_Success:
7724 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007725 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007726 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007727 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007728 break;
7729
7730 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007731 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007732 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007733 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007734 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007735 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007736 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007737
7738 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007739 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007740 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007741 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007742 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007743 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007744
7745 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007746 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007747 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007748 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007750 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007752 }
7753
John McCall16df1e52010-03-30 21:47:33 +00007754 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007755
John McCall2d74de92009-12-01 22:10:20 +00007756 // If overload resolution picked a static member, build a
7757 // non-member call based on that function.
7758 if (Method->isStatic()) {
7759 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7760 Args, NumArgs, RParenLoc);
7761 }
7762
John McCall10eae182009-11-30 22:42:35 +00007763 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007764 }
7765
John McCall7decc9e2010-11-18 06:31:45 +00007766 QualType ResultType = Method->getResultType();
7767 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7768 ResultType = ResultType.getNonLValueExprType(Context);
7769
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007770 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007771 CXXMemberCallExpr *TheCall =
7772 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00007773 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007774
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007775 // Check for a valid return type.
7776 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007777 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007778 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007779
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007780 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007781 // We only need to do this if there was actually an overload; otherwise
7782 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007783 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007784 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007785 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7786 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007787 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007788 MemExpr->setBase(ObjectArg);
7789
7790 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007791 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007792 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007793 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007794 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007795
John McCallb268a282010-08-23 23:25:46 +00007796 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007797 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007798
John McCallb268a282010-08-23 23:25:46 +00007799 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007800}
7801
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007802/// BuildCallToObjectOfClassType - Build a call to an object of class
7803/// type (C++ [over.call.object]), which can end up invoking an
7804/// overloaded function call operator (@c operator()) or performing a
7805/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007806ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007807Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007808 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007809 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007810 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00007811 if (Object->getObjectKind() == OK_ObjCProperty)
7812 ConvertPropertyForRValue(Object);
7813
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007814 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007815 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007816
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007817 // C++ [over.call.object]p1:
7818 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007819 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007820 // candidate functions includes at least the function call
7821 // operators of T. The function call operators of T are obtained by
7822 // ordinary lookup of the name operator() in the context of
7823 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007824 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007825 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007826
7827 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007828 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007829 << Object->getSourceRange()))
7830 return true;
7831
John McCall27b18f82009-11-17 02:14:36 +00007832 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7833 LookupQualifiedName(R, Record->getDecl());
7834 R.suppressDiagnostics();
7835
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007836 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007837 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007838 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007839 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007840 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007841 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007842
Douglas Gregorab7897a2008-11-19 22:57:39 +00007843 // C++ [over.call.object]p2:
7844 // In addition, for each conversion function declared in T of the
7845 // form
7846 //
7847 // operator conversion-type-id () cv-qualifier;
7848 //
7849 // where cv-qualifier is the same cv-qualification as, or a
7850 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007851 // denotes the type "pointer to function of (P1,...,Pn) returning
7852 // R", or the type "reference to pointer to function of
7853 // (P1,...,Pn) returning R", or the type "reference to function
7854 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007855 // is also considered as a candidate function. Similarly,
7856 // surrogate call functions are added to the set of candidate
7857 // functions for each conversion function declared in an
7858 // accessible base class provided the function is not hidden
7859 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007860 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007861 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007862 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007863 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007864 NamedDecl *D = *I;
7865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7866 if (isa<UsingShadowDecl>(D))
7867 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7868
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007869 // Skip over templated conversion functions; they aren't
7870 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007871 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007872 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007873
John McCall6e9f8f62009-12-03 04:06:58 +00007874 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007875
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007876 // Strip the reference type (if any) and then the pointer type (if
7877 // any) to get down to what might be a function type.
7878 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7879 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7880 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007881
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007882 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007883 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007884 Object->getType(), Args, NumArgs,
7885 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007886 }
Mike Stump11289f42009-09-09 15:08:12 +00007887
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007888 // Perform overload resolution.
7889 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007890 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7891 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007892 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007893 // Overload resolution succeeded; we'll build the appropriate call
7894 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007895 break;
7896
7897 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007898 if (CandidateSet.empty())
7899 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7900 << Object->getType() << /*call*/ 1
7901 << Object->getSourceRange();
7902 else
7903 Diag(Object->getSourceRange().getBegin(),
7904 diag::err_ovl_no_viable_object_call)
7905 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007906 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007907 break;
7908
7909 case OR_Ambiguous:
7910 Diag(Object->getSourceRange().getBegin(),
7911 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007912 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007913 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007914 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007915
7916 case OR_Deleted:
7917 Diag(Object->getSourceRange().getBegin(),
7918 diag::err_ovl_deleted_object_call)
7919 << Best->Function->isDeleted()
7920 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007921 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007922 break;
Mike Stump11289f42009-09-09 15:08:12 +00007923 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007924
Douglas Gregorb412e172010-07-25 18:17:45 +00007925 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007926 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007927
Douglas Gregorab7897a2008-11-19 22:57:39 +00007928 if (Best->Function == 0) {
7929 // Since there is no function declaration, this is one of the
7930 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007931 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007932 = cast<CXXConversionDecl>(
7933 Best->Conversions[0].UserDefined.ConversionFunction);
7934
John McCalla0296f72010-03-19 07:35:19 +00007935 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007936 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007937
Douglas Gregorab7897a2008-11-19 22:57:39 +00007938 // We selected one of the surrogate functions that converts the
7939 // object parameter to a function pointer. Perform the conversion
7940 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007941
7942 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007943 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007944 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7945 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007946
John McCallfaf5fb42010-08-26 23:41:50 +00007947 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007948 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007949 }
7950
John McCalla0296f72010-03-19 07:35:19 +00007951 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007952 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007953
Douglas Gregorab7897a2008-11-19 22:57:39 +00007954 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7955 // that calls this method, using Object for the implicit object
7956 // parameter and passing along the remaining arguments.
7957 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007958 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007959
7960 unsigned NumArgsInProto = Proto->getNumArgs();
7961 unsigned NumArgsToCheck = NumArgs;
7962
7963 // Build the full argument list for the method call (the
7964 // implicit object parameter is placed at the beginning of the
7965 // list).
7966 Expr **MethodArgs;
7967 if (NumArgs < NumArgsInProto) {
7968 NumArgsToCheck = NumArgsInProto;
7969 MethodArgs = new Expr*[NumArgsInProto + 1];
7970 } else {
7971 MethodArgs = new Expr*[NumArgs + 1];
7972 }
7973 MethodArgs[0] = Object;
7974 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7975 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007976
John McCall7decc9e2010-11-18 06:31:45 +00007977 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007978
7979 // Once we've built TheCall, all of the expressions are properly
7980 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00007981 QualType ResultTy = Method->getResultType();
7982 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7983 ResultTy = ResultTy.getNonLValueExprType(Context);
7984
John McCallb268a282010-08-23 23:25:46 +00007985 CXXOperatorCallExpr *TheCall =
7986 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7987 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00007988 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007989 delete [] MethodArgs;
7990
John McCallb268a282010-08-23 23:25:46 +00007991 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007992 Method))
7993 return true;
7994
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007995 // We may have default arguments. If so, we need to allocate more
7996 // slots in the call for them.
7997 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007998 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007999 else if (NumArgs > NumArgsInProto)
8000 NumArgsToCheck = NumArgsInProto;
8001
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008002 bool IsError = false;
8003
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008004 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008005 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008006 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008007 TheCall->setArg(0, Object);
8008
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008009
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008010 // Check the argument types.
8011 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008012 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008013 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008014 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008015
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008016 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008017
John McCalldadc5752010-08-24 06:29:42 +00008018 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008019 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008020 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008021 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008022 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008023
8024 IsError |= InputInit.isInvalid();
8025 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008026 } else {
John McCalldadc5752010-08-24 06:29:42 +00008027 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008028 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8029 if (DefArg.isInvalid()) {
8030 IsError = true;
8031 break;
8032 }
8033
8034 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008035 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008036
8037 TheCall->setArg(i + 1, Arg);
8038 }
8039
8040 // If this is a variadic call, handle args passed through "...".
8041 if (Proto->isVariadic()) {
8042 // Promote the arguments (C99 6.5.2.2p7).
8043 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8044 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008045 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008046 TheCall->setArg(i + 1, Arg);
8047 }
8048 }
8049
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008050 if (IsError) return true;
8051
John McCallb268a282010-08-23 23:25:46 +00008052 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008053 return true;
8054
John McCalle172be52010-08-24 06:09:16 +00008055 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008056}
8057
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008058/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008059/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008060/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008061ExprResult
John McCallb268a282010-08-23 23:25:46 +00008062Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008063 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008064
John McCalle26a8722010-12-04 08:14:53 +00008065 if (Base->getObjectKind() == OK_ObjCProperty)
8066 ConvertPropertyForRValue(Base);
8067
John McCallbc077cf2010-02-08 23:07:23 +00008068 SourceLocation Loc = Base->getExprLoc();
8069
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008070 // C++ [over.ref]p1:
8071 //
8072 // [...] An expression x->m is interpreted as (x.operator->())->m
8073 // for a class object x of type T if T::operator->() exists and if
8074 // the operator is selected as the best match function by the
8075 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008076 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008077 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008078 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008079
John McCallbc077cf2010-02-08 23:07:23 +00008080 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008081 PDiag(diag::err_typecheck_incomplete_tag)
8082 << Base->getSourceRange()))
8083 return ExprError();
8084
John McCall27b18f82009-11-17 02:14:36 +00008085 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8086 LookupQualifiedName(R, BaseRecord->getDecl());
8087 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008088
8089 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008090 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008091 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008092 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008093 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008094
8095 // Perform overload resolution.
8096 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008097 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008098 case OR_Success:
8099 // Overload resolution succeeded; we'll build the call below.
8100 break;
8101
8102 case OR_No_Viable_Function:
8103 if (CandidateSet.empty())
8104 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008105 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008106 else
8107 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008108 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008109 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008110 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008111
8112 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008113 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8114 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008115 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008116 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008117
8118 case OR_Deleted:
8119 Diag(OpLoc, diag::err_ovl_deleted_oper)
8120 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008121 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008122 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008123 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008124 }
8125
John McCalla0296f72010-03-19 07:35:19 +00008126 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008127 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008128
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008129 // Convert the object parameter.
8130 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008131 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8132 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008133 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008134
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008135 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008136 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008137
John McCall7decc9e2010-11-18 06:31:45 +00008138 QualType ResultTy = Method->getResultType();
8139 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8140 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008141 CXXOperatorCallExpr *TheCall =
8142 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008143 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008144
John McCallb268a282010-08-23 23:25:46 +00008145 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008146 Method))
8147 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008148 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008149}
8150
Douglas Gregorcd695e52008-11-10 20:40:00 +00008151/// FixOverloadedFunctionReference - E is an expression that refers to
8152/// a C++ overloaded function (possibly with some parentheses and
8153/// perhaps a '&' around it). We have resolved the overloaded function
8154/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008155/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008156Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008157 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008158 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008159 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8160 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008161 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008162 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008163
8164 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8165 }
8166
8167 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008168 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8169 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008170 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008171 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008172 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008173 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008174 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008175 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008176
John McCallcf142162010-08-07 06:22:56 +00008177 return ImplicitCastExpr::Create(Context, ICE->getType(),
8178 ICE->getCastKind(),
8179 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008180 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008181 }
8182
8183 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008184 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008185 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008186 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8187 if (Method->isStatic()) {
8188 // Do nothing: static member functions aren't any different
8189 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008190 } else {
John McCalle66edc12009-11-24 19:00:30 +00008191 // Fix the sub expression, which really has to be an
8192 // UnresolvedLookupExpr holding an overloaded member function
8193 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008194 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8195 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008196 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008197 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008198
John McCalld14a8642009-11-21 08:51:07 +00008199 assert(isa<DeclRefExpr>(SubExpr)
8200 && "fixed to something other than a decl ref");
8201 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8202 && "fixed to a member ref with no nested name qualifier");
8203
8204 // We have taken the address of a pointer to member
8205 // function. Perform the computation here so that we get the
8206 // appropriate pointer to member type.
8207 QualType ClassType
8208 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8209 QualType MemPtrType
8210 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8211
John McCall7decc9e2010-11-18 06:31:45 +00008212 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8213 VK_RValue, OK_Ordinary,
8214 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008215 }
8216 }
John McCall16df1e52010-03-30 21:47:33 +00008217 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8218 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008219 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008220 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008221
John McCalle3027922010-08-25 11:45:40 +00008222 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008223 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008224 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008225 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008226 }
John McCalld14a8642009-11-21 08:51:07 +00008227
8228 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008229 // FIXME: avoid copy.
8230 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008231 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008232 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8233 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008234 }
8235
John McCalld14a8642009-11-21 08:51:07 +00008236 return DeclRefExpr::Create(Context,
8237 ULE->getQualifier(),
8238 ULE->getQualifierRange(),
8239 Fn,
8240 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008241 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008242 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008243 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008244 }
8245
John McCall10eae182009-11-30 22:42:35 +00008246 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008247 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008248 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8249 if (MemExpr->hasExplicitTemplateArgs()) {
8250 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8251 TemplateArgs = &TemplateArgsBuffer;
8252 }
John McCall6b51f282009-11-23 01:53:49 +00008253
John McCall2d74de92009-12-01 22:10:20 +00008254 Expr *Base;
8255
John McCall7decc9e2010-11-18 06:31:45 +00008256 // If we're filling in a static method where we used to have an
8257 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008258 if (MemExpr->isImplicitAccess()) {
8259 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8260 return DeclRefExpr::Create(Context,
8261 MemExpr->getQualifier(),
8262 MemExpr->getQualifierRange(),
8263 Fn,
8264 MemExpr->getMemberLoc(),
8265 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008266 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008267 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008268 } else {
8269 SourceLocation Loc = MemExpr->getMemberLoc();
8270 if (MemExpr->getQualifier())
8271 Loc = MemExpr->getQualifierRange().getBegin();
8272 Base = new (Context) CXXThisExpr(Loc,
8273 MemExpr->getBaseType(),
8274 /*isImplicit=*/true);
8275 }
John McCall2d74de92009-12-01 22:10:20 +00008276 } else
John McCallc3007a22010-10-26 07:05:15 +00008277 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008278
8279 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008280 MemExpr->isArrow(),
8281 MemExpr->getQualifier(),
8282 MemExpr->getQualifierRange(),
8283 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008284 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008285 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008286 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008287 Fn->getType(),
8288 cast<CXXMethodDecl>(Fn)->isStatic()
8289 ? VK_LValue : VK_RValue,
8290 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008291 }
8292
John McCallc3007a22010-10-26 07:05:15 +00008293 llvm_unreachable("Invalid reference to overloaded function");
8294 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008295}
8296
John McCalldadc5752010-08-24 06:29:42 +00008297ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8298 DeclAccessPair Found,
8299 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008300 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008301}
8302
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008303} // end namespace clang