blob: 0c8d78025b435be19ea332914f3f90bc5390631c [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"
Douglas Gregora11693b2008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035
John McCall5c32be02010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor5251f1b2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164}
165
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000193 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
195 return true;
196
197 return false;
198}
199
Douglas Gregor5c407d92008-10-23 00:40:37 +0000200/// isPointerConversionToVoidPointer - Determines whether this
201/// conversion is a conversion of a pointer to a void pointer. This is
202/// used as part of the ranking of standard conversion sequences (C++
203/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000204bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000205StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000206isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000207 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000208 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000209
210 // Note that FromType has not necessarily been transformed by the
211 // array-to-pointer implicit conversion, so check for its presence
212 // and redo the conversion to get a pointer.
213 if (First == ICK_Array_To_Pointer)
214 FromType = Context.getArrayDecayedType(FromType);
215
John McCall75851b12010-10-26 06:40:27 +0000216 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000217 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000218 return ToPtrType->getPointeeType()->isVoidType();
219
220 return false;
221}
222
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223/// DebugPrint - Print this standard conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000226 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000227 bool PrintedSomething = false;
228 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 PrintedSomething = true;
231 }
232
233 if (Second != ICK_Identity) {
234 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000237 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000238
239 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000240 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000241 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000243 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000244 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000245 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000246 PrintedSomething = true;
247 }
248
249 if (Third != ICK_Identity) {
250 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000251 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000252 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000254 PrintedSomething = true;
255 }
256
257 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000258 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 }
260}
261
262/// DebugPrint - Print this user-defined conversion sequence to standard
263/// error. Useful for debugging overloading issues.
264void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000265 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000266 if (Before.First || Before.Second || Before.Third) {
267 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000270 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000272 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273 After.DebugPrint();
274 }
275}
276
277/// DebugPrint - Print this implicit conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 switch (ConversionKind) {
282 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 Standard.DebugPrint();
285 break;
286 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000287 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 UserDefined.DebugPrint();
289 break;
290 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 break;
John McCall0d1da222010-01-12 00:44:57 +0000293 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000294 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000295 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000297 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 break;
299 }
300
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000301 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000302}
303
John McCall0d1da222010-01-12 00:44:57 +0000304void AmbiguousConversionSequence::construct() {
305 new (&conversions()) ConversionSet();
306}
307
308void AmbiguousConversionSequence::destruct() {
309 conversions().~ConversionSet();
310}
311
312void
313AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
314 FromTypePtr = O.FromTypePtr;
315 ToTypePtr = O.ToTypePtr;
316 new (&conversions()) ConversionSet(O.conversions());
317}
318
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000319namespace {
320 // Structure used by OverloadCandidate::DeductionFailureInfo to store
321 // template parameter and template argument information.
322 struct DFIParamWithArguments {
323 TemplateParameter Param;
324 TemplateArgument FirstArg;
325 TemplateArgument SecondArg;
326 };
327}
328
329/// \brief Convert from Sema's representation of template deduction information
330/// to the form used in overload-candidate information.
331OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000332static MakeDeductionFailureInfo(ASTContext &Context,
333 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000334 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000335 OverloadCandidate::DeductionFailureInfo Result;
336 Result.Result = static_cast<unsigned>(TDK);
337 Result.Data = 0;
338 switch (TDK) {
339 case Sema::TDK_Success:
340 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000341 case Sema::TDK_TooManyArguments:
342 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000343 break;
344
345 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000346 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000347 Result.Data = Info.Param.getOpaqueValue();
348 break;
349
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000352 // FIXME: Should allocate from normal heap so that we can free this later.
353 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354 Saved->Param = Info.Param;
355 Saved->FirstArg = Info.FirstArg;
356 Saved->SecondArg = Info.SecondArg;
357 Result.Data = Saved;
358 break;
359 }
360
361 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000362 Result.Data = Info.take();
363 break;
364
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000366 case Sema::TDK_FailedOverloadResolution:
367 break;
368 }
369
370 return Result;
371}
John McCall0d1da222010-01-12 00:44:57 +0000372
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000373void OverloadCandidate::DeductionFailureInfo::Destroy() {
374 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
375 case Sema::TDK_Success:
376 case Sema::TDK_InstantiationDepth:
377 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000378 case Sema::TDK_TooManyArguments:
379 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000380 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 break;
382
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000384 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000385 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 Data = 0;
387 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000388
389 case Sema::TDK_SubstitutionFailure:
390 // FIXME: Destroy the template arugment list?
391 Data = 0;
392 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393
Douglas Gregor461761d2010-05-08 18:20:53 +0000394 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_FailedOverloadResolution:
397 break;
398 }
399}
400
401TemplateParameter
402OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
403 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
404 case Sema::TDK_Success:
405 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000406 case Sema::TDK_TooManyArguments:
407 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000408 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 return TemplateParameter();
410
411 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000412 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000413 return TemplateParameter::getFromOpaqueValue(Data);
414
415 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000416 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000417 return static_cast<DFIParamWithArguments*>(Data)->Param;
418
419 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 case Sema::TDK_FailedOverloadResolution:
422 break;
423 }
424
425 return TemplateParameter();
426}
Douglas Gregord09efd42010-05-08 20:07:26 +0000427
428TemplateArgumentList *
429OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
435 case Sema::TDK_Incomplete:
436 case Sema::TDK_InvalidExplicitArguments:
437 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000438 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000439 return 0;
440
441 case Sema::TDK_SubstitutionFailure:
442 return static_cast<TemplateArgumentList*>(Data);
443
444 // Unhandled
445 case Sema::TDK_NonDeducedMismatch:
446 case Sema::TDK_FailedOverloadResolution:
447 break;
448 }
449
450 return 0;
451}
452
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000453const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
454 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
455 case Sema::TDK_Success:
456 case Sema::TDK_InstantiationDepth:
457 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000458 case Sema::TDK_TooManyArguments:
459 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000460 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000461 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 return 0;
463
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000464 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
467
Douglas Gregor461761d2010-05-08 18:20:53 +0000468 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000469 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 case Sema::TDK_FailedOverloadResolution:
471 break;
472 }
473
474 return 0;
475}
476
477const TemplateArgument *
478OverloadCandidate::DeductionFailureInfo::getSecondArg() {
479 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
480 case Sema::TDK_Success:
481 case Sema::TDK_InstantiationDepth:
482 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000483 case Sema::TDK_TooManyArguments:
484 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000485 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000486 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000487 return 0;
488
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000490 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
492
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000495 case Sema::TDK_FailedOverloadResolution:
496 break;
497 }
498
499 return 0;
500}
501
502void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503 inherited::clear();
504 Functions.clear();
505}
506
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000508// overload of the declarations in Old. This routine returns false if
509// New and Old cannot be overloaded, e.g., if New has the same
510// signature as some function in Old (C++ 1.3.10) or if the Old
511// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000512// it does return false, MatchedDecl will point to the decl that New
513// cannot be overloaded with. This decl may be a UsingShadowDecl on
514// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515//
516// Example: Given the following input:
517//
518// void f(int, float); // #1
519// void f(int, int); // #2
520// int f(int, int); // #3
521//
522// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000523// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524//
John McCall3d988d92009-12-02 08:47:38 +0000525// When we process #2, Old contains only the FunctionDecl for #1. By
526// comparing the parameter types, we see that #1 and #2 are overloaded
527// (since they have different signatures), so this routine returns
528// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529//
John McCall3d988d92009-12-02 08:47:38 +0000530// When we process #3, Old is an overload set containing #1 and #2. We
531// compare the signatures of #3 to #1 (they're overloaded, so we do
532// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
533// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534// signature), IsOverload returns false and MatchedDecl will be set to
535// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000536//
537// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
538// into a class by a using declaration. The rules for whether to hide
539// shadow declarations ignore some properties which otherwise figure
540// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000541Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000542Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
543 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000544 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000545 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000546 NamedDecl *OldD = *I;
547
548 bool OldIsUsingDecl = false;
549 if (isa<UsingShadowDecl>(OldD)) {
550 OldIsUsingDecl = true;
551
552 // We can always introduce two using declarations into the same
553 // context, even if they have identical signatures.
554 if (NewIsUsingDecl) continue;
555
556 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
557 }
558
559 // If either declaration was introduced by a using declaration,
560 // we'll need to use slightly different rules for matching.
561 // Essentially, these rules are the normal rules, except that
562 // function templates hide function templates with different
563 // return types or template parameter lists.
564 bool UseMemberUsingDeclRules =
565 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
566
John McCall3d988d92009-12-02 08:47:38 +0000567 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000568 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
569 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
570 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
571 continue;
572 }
573
John McCalldaa3d6b2009-12-09 03:35:25 +0000574 Match = *I;
575 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000576 }
John McCall3d988d92009-12-02 08:47:38 +0000577 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCalldaa3d6b2009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000586 }
John McCalla8987a2942010-11-10 03:01:53 +0000587 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000588 // We can overload with these, which can show up when doing
589 // redeclaration checks for UsingDecls.
590 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000591 } else if (isa<TagDecl>(OldD)) {
592 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000593 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
594 // Optimistically assume that an unresolved using decl will
595 // overload; if it doesn't, we'll have to diagnose during
596 // template instantiation.
597 } else {
John McCall1f82f242009-11-18 22:49:29 +0000598 // (C++ 13p1):
599 // Only function declarations can be overloaded; object and type
600 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000603 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000604 }
John McCall1f82f242009-11-18 22:49:29 +0000605
John McCalldaa3d6b2009-12-09 03:35:25 +0000606 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000607}
608
John McCalle9cccd82010-06-16 08:42:20 +0000609bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
610 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000611 // If both of the functions are extern "C", then they are not
612 // overloads.
613 if (Old->isExternC() && New->isExternC())
614 return false;
615
John McCall1f82f242009-11-18 22:49:29 +0000616 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
617 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
618
619 // C++ [temp.fct]p2:
620 // A function template can be overloaded with other function templates
621 // and with normal (non-template) functions.
622 if ((OldTemplate == 0) != (NewTemplate == 0))
623 return true;
624
625 // Is the function New an overload of the function Old?
626 QualType OldQType = Context.getCanonicalType(Old->getType());
627 QualType NewQType = Context.getCanonicalType(New->getType());
628
629 // Compare the signatures (C++ 1.3.10) of the two functions to
630 // determine whether they are overloads. If we find any mismatch
631 // in the signature, they are overloads.
632
633 // If either of these functions is a K&R-style function (no
634 // prototype), then we consider them to have matching signatures.
635 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
636 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
637 return false;
638
639 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
640 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
641
642 // The signature of a function includes the types of its
643 // parameters (C++ 1.3.10), which includes the presence or absence
644 // of the ellipsis; see C++ DR 357).
645 if (OldQType != NewQType &&
646 (OldType->getNumArgs() != NewType->getNumArgs() ||
647 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000648 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000649 return true;
650
651 // C++ [temp.over.link]p4:
652 // The signature of a function template consists of its function
653 // signature, its return type and its template parameter list. The names
654 // of the template parameters are significant only for establishing the
655 // relationship between the template parameters and the rest of the
656 // signature.
657 //
658 // We check the return type and template parameter lists for function
659 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000660 //
661 // However, we don't consider either of these when deciding whether
662 // a member introduced by a shadow declaration is hidden.
663 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000664 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
665 OldTemplate->getTemplateParameters(),
666 false, TPL_TemplateMatch) ||
667 OldType->getResultType() != NewType->getResultType()))
668 return true;
669
670 // If the function is a class member, its signature includes the
671 // cv-qualifiers (if any) on the function itself.
672 //
673 // As part of this, also check whether one of the member functions
674 // is static, in which case they are not overloads (C++
675 // 13.1p2). While not part of the definition of the signature,
676 // this check is important to determine whether these functions
677 // can be overloaded.
678 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
679 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
680 if (OldMethod && NewMethod &&
681 !OldMethod->isStatic() && !NewMethod->isStatic() &&
682 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
683 return true;
684
685 // The signatures match; this is not an overload.
686 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687}
688
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000689/// TryImplicitConversion - Attempt to perform an implicit conversion
690/// from the given expression (Expr) to the given type (ToType). This
691/// function returns an implicit conversion sequence that can be used
692/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693///
694/// void f(float f);
695/// void g(int i) { f(i); }
696///
697/// this routine would produce an implicit conversion sequence to
698/// describe the initialization of f from i, which will be a standard
699/// conversion sequence containing an lvalue-to-rvalue conversion (C++
700/// 4.1) followed by a floating-integral conversion (C++ 4.9).
701//
702/// Note that this routine only determines how the conversion can be
703/// performed; it does not actually perform the conversion. As such,
704/// it will not produce any diagnostics if no conversion is available,
705/// but will instead return an implicit conversion sequence of kind
706/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000707///
708/// If @p SuppressUserConversions, then user-defined conversions are
709/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000710/// If @p AllowExplicit, then explicit user-defined conversions are
711/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000712static ImplicitConversionSequence
713TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
714 bool SuppressUserConversions,
715 bool AllowExplicit,
716 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000717 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000718 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
719 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000720 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000721 return ICS;
722 }
723
John McCall5c32be02010-08-24 20:38:10 +0000724 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000726 return ICS;
727 }
728
Douglas Gregor836a7e82010-08-11 02:15:33 +0000729 // C++ [over.ics.user]p4:
730 // A conversion of an expression of class type to the same class
731 // type is given Exact Match rank, and a conversion of an
732 // expression of class type to a base class of that type is
733 // given Conversion rank, in spite of the fact that a copy/move
734 // constructor (i.e., a user-defined conversion function) is
735 // called for those cases.
736 QualType FromType = From->getType();
737 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000738 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
739 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000740 ICS.setStandard();
741 ICS.Standard.setAsIdentityConversion();
742 ICS.Standard.setFromType(FromType);
743 ICS.Standard.setAllToTypes(ToType);
744
745 // We don't actually check at this point whether there is a valid
746 // copy/move constructor, since overloading just assumes that it
747 // exists. When we actually perform initialization, we'll find the
748 // appropriate constructor to copy the returned object, if needed.
749 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000750
Douglas Gregor5ab11652010-04-17 22:01:05 +0000751 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000752 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000753 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000754
755 return ICS;
756 }
757
758 if (SuppressUserConversions) {
759 // We're not in the case above, so there is no conversion that
760 // we can perform.
761 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000762 return ICS;
763 }
764
765 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000766 OverloadCandidateSet Conversions(From->getExprLoc());
767 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000768 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000769 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000770
771 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000772 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000773 // C++ [over.ics.user]p4:
774 // A conversion of an expression of class type to the same class
775 // type is given Exact Match rank, and a conversion of an
776 // expression of class type to a base class of that type is
777 // given Conversion rank, in spite of the fact that a copy
778 // constructor (i.e., a user-defined conversion function) is
779 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000780 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000781 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000782 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000783 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
784 QualType ToCanon
785 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000786 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000787 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000788 // Turn this into a "standard" conversion sequence, so that it
789 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000790 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000791 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000792 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000793 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000794 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000795 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000796 ICS.Standard.Second = ICK_Derived_To_Base;
797 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000798 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000799
800 // C++ [over.best.ics]p4:
801 // However, when considering the argument of a user-defined
802 // conversion function that is a candidate by 13.3.1.3 when
803 // invoked for the copying of the temporary in the second step
804 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
805 // 13.3.1.6 in all cases, only standard conversion sequences and
806 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000807 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000808 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000809 }
John McCalle8c8cd22010-01-13 22:30:33 +0000810 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000811 ICS.setAmbiguous();
812 ICS.Ambiguous.setFromType(From->getType());
813 ICS.Ambiguous.setToType(ToType);
814 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
815 Cand != Conversions.end(); ++Cand)
816 if (Cand->Viable)
817 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000818 } else {
John McCall65eb8792010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000820 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000821
822 return ICS;
823}
824
John McCall5c32be02010-08-24 20:38:10 +0000825bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
826 const InitializedEntity &Entity,
827 Expr *Initializer,
828 bool SuppressUserConversions,
829 bool AllowExplicitConversions,
830 bool InOverloadResolution) {
831 ImplicitConversionSequence ICS
832 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
833 SuppressUserConversions,
834 AllowExplicitConversions,
835 InOverloadResolution);
836 if (ICS.isBad()) return true;
837
838 // Perform the actual conversion.
839 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
840 return false;
841}
842
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000843/// PerformImplicitConversion - Perform an implicit conversion of the
844/// expression From to the type ToType. Returns true if there was an
845/// error, false otherwise. The expression From is replaced with the
846/// converted expression. Flavor is the kind of conversion we're
847/// performing, used in the error message. If @p AllowExplicit,
848/// explicit user-defined conversions are permitted.
849bool
850Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
851 AssignmentAction Action, bool AllowExplicit) {
852 ImplicitConversionSequence ICS;
853 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
854}
855
856bool
857Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
858 AssignmentAction Action, bool AllowExplicit,
859 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000860 ICS = clang::TryImplicitConversion(*this, From, ToType,
861 /*SuppressUserConversions=*/false,
862 AllowExplicit,
863 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000864 return PerformImplicitConversion(From, ToType, ICS, Action);
865}
866
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000867/// \brief Determine whether the conversion from FromType to ToType is a valid
868/// conversion that strips "noreturn" off the nested function type.
869static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
870 QualType ToType, QualType &ResultTy) {
871 if (Context.hasSameUnqualifiedType(FromType, ToType))
872 return false;
873
874 // Strip the noreturn off the type we're converting from; noreturn can
875 // safely be removed.
876 FromType = Context.getNoReturnType(FromType, false);
877 if (!Context.hasSameUnqualifiedType(FromType, ToType))
878 return false;
879
880 ResultTy = FromType;
881 return true;
882}
Douglas Gregor46188682010-05-18 22:42:18 +0000883
884/// \brief Determine whether the conversion from FromType to ToType is a valid
885/// vector conversion.
886///
887/// \param ICK Will be set to the vector conversion kind, if this is a vector
888/// conversion.
889static bool IsVectorConversion(ASTContext &Context, QualType FromType,
890 QualType ToType, ImplicitConversionKind &ICK) {
891 // We need at least one of these types to be a vector type to have a vector
892 // conversion.
893 if (!ToType->isVectorType() && !FromType->isVectorType())
894 return false;
895
896 // Identical types require no conversions.
897 if (Context.hasSameUnqualifiedType(FromType, ToType))
898 return false;
899
900 // There are no conversions between extended vector types, only identity.
901 if (ToType->isExtVectorType()) {
902 // There are no conversions between extended vector types other than the
903 // identity conversion.
904 if (FromType->isExtVectorType())
905 return false;
906
907 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000908 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000909 ICK = ICK_Vector_Splat;
910 return true;
911 }
912 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000913
914 // We can perform the conversion between vector types in the following cases:
915 // 1)vector types are equivalent AltiVec and GCC vector types
916 // 2)lax vector conversions are permitted and the vector types are of the
917 // same size
918 if (ToType->isVectorType() && FromType->isVectorType()) {
919 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000920 (Context.getLangOptions().LaxVectorConversions &&
921 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000922 ICK = ICK_Vector_Conversion;
923 return true;
924 }
Douglas Gregor46188682010-05-18 22:42:18 +0000925 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000926
Douglas Gregor46188682010-05-18 22:42:18 +0000927 return false;
928}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000929
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000930/// IsStandardConversion - Determines whether there is a standard
931/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
932/// expression From to the type ToType. Standard conversion sequences
933/// only consider non-class types; for conversions that involve class
934/// types, use TryImplicitConversion. If a conversion exists, SCS will
935/// contain the standard conversion sequence required to perform this
936/// conversion and this routine will return true. Otherwise, this
937/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000938static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
939 bool InOverloadResolution,
940 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000942
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000944 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000945 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000946 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000947 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000948 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000950 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000951 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000952 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000953 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000954 return false;
955
Mike Stump11289f42009-09-09 15:08:12 +0000956 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000957 }
958
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000959 // The first conversion can be an lvalue-to-rvalue conversion,
960 // array-to-pointer conversion, or function-to-pointer conversion
961 // (C++ 4p1).
962
John McCall5c32be02010-08-24 20:38:10 +0000963 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000964 DeclAccessPair AccessPair;
965 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000966 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
967 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000968 // We were able to resolve the address of the overloaded function,
969 // so we can convert to the type of that function.
970 FromType = Fn->getType();
971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
972 if (!Method->isStatic()) {
973 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000974 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
975 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000976 }
977 }
978
979 // If the "from" expression takes the address of the overloaded
980 // function, update the type of the resulting expression accordingly.
981 if (FromType->getAs<FunctionType>())
982 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000983 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000984 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000985
986 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000987 assert(S.Context.hasSameType(FromType,
988 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +0000989 } else {
990 return false;
991 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +0000992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000994 // An lvalue (3.10) of a non-function, non-array type T can be
995 // converted to an rvalue.
John McCall5c32be02010-08-24 20:38:10 +0000996 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +0000997 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000998 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +0000999 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001000 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001001
1002 // If T is a non-class type, the type of the rvalue is the
1003 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001004 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1005 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001006 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001007 } else if (FromType->isArrayType()) {
1008 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001009 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001010
1011 // An lvalue or rvalue of type "array of N T" or "array of unknown
1012 // bound of T" can be converted to an rvalue of type "pointer to
1013 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001014 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015
John McCall5c32be02010-08-24 20:38:10 +00001016 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001018 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001019
1020 // For the purpose of ranking in overload resolution
1021 // (13.3.3.1.1), this conversion is considered an
1022 // array-to-pointer conversion followed by a qualification
1023 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001024 SCS.Second = ICK_Identity;
1025 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001026 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001027 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 }
Mike Stump12b8ce12009-08-04 21:02:39 +00001029 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1030 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001031 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032
1033 // An lvalue of function type T can be converted to an rvalue of
1034 // type "pointer to T." The result is a pointer to the
1035 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001036 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001037 } else {
1038 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001039 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001040 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001041 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001042
1043 // The second conversion can be an integral promotion, floating
1044 // point promotion, integral conversion, floating point conversion,
1045 // floating-integral conversion, pointer conversion,
1046 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001047 // For overloading in C, this can also be a "compatible-type"
1048 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001049 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001050 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001051 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052 // The unqualified versions of the types are the same: there's no
1053 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001054 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001055 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001056 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001057 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001058 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001059 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001060 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001061 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001063 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001064 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001065 SCS.Second = ICK_Complex_Promotion;
1066 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001067 } else if (ToType->isBooleanType() &&
1068 (FromType->isArithmeticType() ||
1069 FromType->isAnyPointerType() ||
1070 FromType->isBlockPointerType() ||
1071 FromType->isMemberPointerType() ||
1072 FromType->isNullPtrType())) {
1073 // Boolean conversions (C++ 4.12).
1074 SCS.Second = ICK_Boolean_Conversion;
1075 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001076 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001077 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001078 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001079 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001080 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001081 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001082 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001083 SCS.Second = ICK_Complex_Conversion;
1084 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001085 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1086 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001087 // Complex-real conversions (C99 6.3.1.7)
1088 SCS.Second = ICK_Complex_Real;
1089 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001090 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001091 // Floating point conversions (C++ 4.8).
1092 SCS.Second = ICK_Floating_Conversion;
1093 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001094 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001095 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001096 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001097 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001098 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001101 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1102 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001103 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001104 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001105 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001106 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1107 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001108 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001109 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001110 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001111 SCS.Second = SecondICK;
1112 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001113 } else if (!S.getLangOptions().CPlusPlus &&
1114 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001115 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001116 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001117 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001118 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001119 // Treat a conversion that strips "noreturn" as an identity conversion.
1120 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121 } else {
1122 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001123 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001125 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001127 QualType CanonFrom;
1128 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001130 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001133 CanonFrom = S.Context.getCanonicalType(FromType);
1134 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135 } else {
1136 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001137 SCS.Third = ICK_Identity;
1138
Mike Stump11289f42009-09-09 15:08:12 +00001139 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001140 // [...] Any difference in top-level cv-qualification is
1141 // subsumed by the initialization itself and does not constitute
1142 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001143 CanonFrom = S.Context.getCanonicalType(FromType);
1144 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001145 if (CanonFrom.getLocalUnqualifiedType()
1146 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001147 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1148 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001149 FromType = ToType;
1150 CanonFrom = CanonTo;
1151 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001153 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154
1155 // If we have not converted the argument type to the parameter type,
1156 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001157 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001158 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001160 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161}
1162
1163/// IsIntegralPromotion - Determines whether the conversion from the
1164/// expression From (whose potentially-adjusted type is FromType) to
1165/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1166/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001167bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001168 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001169 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001170 if (!To) {
1171 return false;
1172 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001173
1174 // An rvalue of type char, signed char, unsigned char, short int, or
1175 // unsigned short int can be converted to an rvalue of type int if
1176 // int can represent all the values of the source type; otherwise,
1177 // the source rvalue can be converted to an rvalue of type unsigned
1178 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001179 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1180 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001181 if (// We can promote any signed, promotable integer type to an int
1182 (FromType->isSignedIntegerType() ||
1183 // We can promote any unsigned integer type whose size is
1184 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001185 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001186 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001188 }
1189
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001190 return To->getKind() == BuiltinType::UInt;
1191 }
1192
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001193 // C++0x [conv.prom]p3:
1194 // A prvalue of an unscoped enumeration type whose underlying type is not
1195 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1196 // following types that can represent all the values of the enumeration
1197 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1198 // unsigned int, long int, unsigned long int, long long int, or unsigned
1199 // long long int. If none of the types in that list can represent all the
1200 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1201 // type can be converted to an rvalue a prvalue of the extended integer type
1202 // with lowest integer conversion rank (4.13) greater than the rank of long
1203 // long in which all the values of the enumeration can be represented. If
1204 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001205 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1206 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1207 // provided for a scoped enumeration.
1208 if (FromEnumType->getDecl()->isScoped())
1209 return false;
1210
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001211 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001212 if (ToType->isIntegerType() &&
1213 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001214 return Context.hasSameUnqualifiedType(ToType,
1215 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001216 }
John McCall56774992009-12-09 09:09:27 +00001217
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001218 // C++0x [conv.prom]p2:
1219 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1220 // to an rvalue a prvalue of the first of the following types that can
1221 // represent all the values of its underlying type: int, unsigned int,
1222 // long int, unsigned long int, long long int, or unsigned long long int.
1223 // If none of the types in that list can represent all the values of its
1224 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1225 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1226 // type.
1227 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1228 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 // Determine whether the type we're converting from is signed or
1230 // unsigned.
1231 bool FromIsSigned;
1232 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001233
1234 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1235 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236
1237 // The types we'll try to promote to, in the appropriate
1238 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001239 QualType PromoteTypes[6] = {
1240 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001241 Context.LongTy, Context.UnsignedLongTy ,
1242 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001244 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1246 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001247 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001248 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1249 // We found the type that we can promote to. If this is the
1250 // type we wanted, we have a promotion. Otherwise, no
1251 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001252 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001253 }
1254 }
1255 }
1256
1257 // An rvalue for an integral bit-field (9.6) can be converted to an
1258 // rvalue of type int if int can represent all the values of the
1259 // bit-field; otherwise, it can be converted to unsigned int if
1260 // unsigned int can represent all the values of the bit-field. If
1261 // the bit-field is larger yet, no integral promotion applies to
1262 // it. If the bit-field has an enumerated type, it is treated as any
1263 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001264 // FIXME: We should delay checking of bit-fields until we actually perform the
1265 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001266 using llvm::APSInt;
1267 if (From)
1268 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001269 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001270 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001271 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1272 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1273 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001274
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001275 // Are we promoting to an int from a bitfield that fits in an int?
1276 if (BitWidth < ToSize ||
1277 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1278 return To->getKind() == BuiltinType::Int;
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001281 // Are we promoting to an unsigned int from an unsigned bitfield
1282 // that fits into an unsigned int?
1283 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1284 return To->getKind() == BuiltinType::UInt;
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001287 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001288 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001291 // An rvalue of type bool can be converted to an rvalue of type int,
1292 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001293 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001294 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001295 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001296
1297 return false;
1298}
1299
1300/// IsFloatingPointPromotion - Determines whether the conversion from
1301/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1302/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001303bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304 /// An rvalue of type float can be converted to an rvalue of type
1305 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001306 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1307 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001308 if (FromBuiltin->getKind() == BuiltinType::Float &&
1309 ToBuiltin->getKind() == BuiltinType::Double)
1310 return true;
1311
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001312 // C99 6.3.1.5p1:
1313 // When a float is promoted to double or long double, or a
1314 // double is promoted to long double [...].
1315 if (!getLangOptions().CPlusPlus &&
1316 (FromBuiltin->getKind() == BuiltinType::Float ||
1317 FromBuiltin->getKind() == BuiltinType::Double) &&
1318 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1319 return true;
1320 }
1321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322 return false;
1323}
1324
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001325/// \brief Determine if a conversion is a complex promotion.
1326///
1327/// A complex promotion is defined as a complex -> complex conversion
1328/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001329/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001330bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001331 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001332 if (!FromComplex)
1333 return false;
1334
John McCall9dd450b2009-09-21 23:43:11 +00001335 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001336 if (!ToComplex)
1337 return false;
1338
1339 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001340 ToComplex->getElementType()) ||
1341 IsIntegralPromotion(0, FromComplex->getElementType(),
1342 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001343}
1344
Douglas Gregor237f96c2008-11-26 23:31:11 +00001345/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1346/// the pointer type FromPtr to a pointer to type ToPointee, with the
1347/// same type qualifiers as FromPtr has on its pointee type. ToType,
1348/// if non-empty, will be a pointer to ToType that may or may not have
1349/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001350static QualType
1351BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001352 QualType ToPointee, QualType ToType,
1353 ASTContext &Context) {
1354 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1355 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001356 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001357
1358 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001359 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001360 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001361 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001362 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001363
1364 // Build a pointer to ToPointee. It has the right qualifiers
1365 // already.
1366 return Context.getPointerType(ToPointee);
1367 }
1368
1369 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001370 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001371 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1372 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001373}
1374
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001375/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1376/// the FromType, which is an objective-c pointer, to ToType, which may or may
1377/// not have the right set of qualifiers.
1378static QualType
1379BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1380 QualType ToType,
1381 ASTContext &Context) {
1382 QualType CanonFromType = Context.getCanonicalType(FromType);
1383 QualType CanonToType = Context.getCanonicalType(ToType);
1384 Qualifiers Quals = CanonFromType.getQualifiers();
1385
1386 // Exact qualifier match -> return the pointer type we're converting to.
1387 if (CanonToType.getLocalQualifiers() == Quals)
1388 return ToType;
1389
1390 // Just build a canonical type that has the right qualifiers.
1391 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1392}
1393
Mike Stump11289f42009-09-09 15:08:12 +00001394static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001395 bool InOverloadResolution,
1396 ASTContext &Context) {
1397 // Handle value-dependent integral null pointer constants correctly.
1398 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1399 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001400 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001401 return !InOverloadResolution;
1402
Douglas Gregor56751b52009-09-25 04:25:58 +00001403 return Expr->isNullPointerConstant(Context,
1404 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1405 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001406}
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408/// IsPointerConversion - Determines whether the conversion of the
1409/// expression From, which has the (possibly adjusted) type FromType,
1410/// can be converted to the type ToType via a pointer conversion (C++
1411/// 4.10). If so, returns true and places the converted type (that
1412/// might differ from ToType in its cv-qualifiers at some level) into
1413/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001414///
Douglas Gregora29dc052008-11-27 01:19:21 +00001415/// This routine also supports conversions to and from block pointers
1416/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1417/// pointers to interfaces. FIXME: Once we've determined the
1418/// appropriate overloading rules for Objective-C, we may want to
1419/// split the Objective-C checks into a different routine; however,
1420/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001421/// conversions, so for now they live here. IncompatibleObjC will be
1422/// set if the conversion is an allowed Objective-C conversion that
1423/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001425 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001426 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001427 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001428 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001429 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1430 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001431
Mike Stump11289f42009-09-09 15:08:12 +00001432 // Conversion from a null pointer constant to any Objective-C pointer type.
1433 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001434 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001435 ConvertedType = ToType;
1436 return true;
1437 }
1438
Douglas Gregor231d1c62008-11-27 00:15:41 +00001439 // Blocks: Block pointers can be converted to void*.
1440 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001441 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
1445 // Blocks: A null pointer constant can be converted to a block
1446 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001447 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001448 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001449 ConvertedType = ToType;
1450 return true;
1451 }
1452
Sebastian Redl576fd422009-05-10 18:38:11 +00001453 // If the left-hand-side is nullptr_t, the right side can be a null
1454 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001455 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001456 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001457 ConvertedType = ToType;
1458 return true;
1459 }
1460
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001461 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001462 if (!ToTypePtr)
1463 return false;
1464
1465 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001466 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001467 ConvertedType = ToType;
1468 return true;
1469 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001470
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001471 // Beyond this point, both types need to be pointers
1472 // , including objective-c pointers.
1473 QualType ToPointeeType = ToTypePtr->getPointeeType();
1474 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1475 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1476 ToType, Context);
1477 return true;
1478
1479 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001480 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001481 if (!FromTypePtr)
1482 return false;
1483
1484 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001485
Douglas Gregorfb640862010-08-18 21:25:30 +00001486 // If the unqualified pointee types are the same, this can't be a
1487 // pointer conversion, so don't do all of the work below.
1488 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1489 return false;
1490
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491 // An rvalue of type "pointer to cv T," where T is an object type,
1492 // can be converted to an rvalue of type "pointer to cv void" (C++
1493 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001494 if (FromPointeeType->isIncompleteOrObjectType() &&
1495 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001496 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001497 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001498 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001499 return true;
1500 }
1501
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001502 // When we're overloading in C, we allow a special kind of pointer
1503 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001504 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001505 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001506 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001507 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001508 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001509 return true;
1510 }
1511
Douglas Gregor5c407d92008-10-23 00:40:37 +00001512 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001513 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001514 // An rvalue of type "pointer to cv D," where D is a class type,
1515 // can be converted to an rvalue of type "pointer to cv B," where
1516 // B is a base class (clause 10) of D. If B is an inaccessible
1517 // (clause 11) or ambiguous (10.2) base class of D, a program that
1518 // necessitates this conversion is ill-formed. The result of the
1519 // conversion is a pointer to the base class sub-object of the
1520 // derived class object. The null pointer value is converted to
1521 // the null pointer value of the destination type.
1522 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001523 // Note that we do not check for ambiguity or inaccessibility
1524 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001525 if (getLangOptions().CPlusPlus &&
1526 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001527 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001528 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001529 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001530 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001531 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001532 ToType, Context);
1533 return true;
1534 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001535
Douglas Gregora119f102008-12-19 19:13:09 +00001536 return false;
1537}
1538
1539/// isObjCPointerConversion - Determines whether this is an
1540/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1541/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001542bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001543 QualType& ConvertedType,
1544 bool &IncompatibleObjC) {
1545 if (!getLangOptions().ObjC1)
1546 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001547
Steve Naroff7cae42b2009-07-10 23:34:53 +00001548 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001549 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001550 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001551 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001552
Steve Naroff7cae42b2009-07-10 23:34:53 +00001553 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001554 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001555 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001556 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001557 ConvertedType = ToType;
1558 return true;
1559 }
1560 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001561 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001562 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001563 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001564 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001565 ConvertedType = ToType;
1566 return true;
1567 }
1568 // Objective C++: We're able to convert from a pointer to an
1569 // interface to a pointer to a different interface.
1570 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001571 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1572 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1573 if (getLangOptions().CPlusPlus && LHS && RHS &&
1574 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1575 FromObjCPtr->getPointeeType()))
1576 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
1581 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1582 // Okay: this is some kind of implicit downcast of Objective-C
1583 // interfaces, which is permitted. However, we're going to
1584 // complain about it.
1585 IncompatibleObjC = true;
1586 ConvertedType = FromType;
1587 return true;
1588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001590 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001591 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001592 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001593 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001594 else if (const BlockPointerType *ToBlockPtr =
1595 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001596 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001597 // to a block pointer type.
1598 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1599 ConvertedType = ToType;
1600 return true;
1601 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001602 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001603 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001604 else if (FromType->getAs<BlockPointerType>() &&
1605 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1606 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001607 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001611 else
Douglas Gregora119f102008-12-19 19:13:09 +00001612 return false;
1613
Douglas Gregor033f56d2008-12-23 00:53:59 +00001614 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001615 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001616 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001617 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001618 FromPointeeType = FromBlockPtr->getPointeeType();
1619 else
Douglas Gregora119f102008-12-19 19:13:09 +00001620 return false;
1621
Douglas Gregora119f102008-12-19 19:13:09 +00001622 // If we have pointers to pointers, recursively check whether this
1623 // is an Objective-C conversion.
1624 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1625 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1626 IncompatibleObjC)) {
1627 // We always complain about this conversion.
1628 IncompatibleObjC = true;
1629 ConvertedType = ToType;
1630 return true;
1631 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001632 // Allow conversion of pointee being objective-c pointer to another one;
1633 // as in I* to id.
1634 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1635 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1636 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1637 IncompatibleObjC)) {
1638 ConvertedType = ToType;
1639 return true;
1640 }
1641
Douglas Gregor033f56d2008-12-23 00:53:59 +00001642 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001643 // differences in the argument and result types are in Objective-C
1644 // pointer conversions. If so, we permit the conversion (but
1645 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001646 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001647 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001648 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001649 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001650 if (FromFunctionType && ToFunctionType) {
1651 // If the function types are exactly the same, this isn't an
1652 // Objective-C pointer conversion.
1653 if (Context.getCanonicalType(FromPointeeType)
1654 == Context.getCanonicalType(ToPointeeType))
1655 return false;
1656
1657 // Perform the quick checks that will tell us whether these
1658 // function types are obviously different.
1659 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1660 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1661 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1662 return false;
1663
1664 bool HasObjCConversion = false;
1665 if (Context.getCanonicalType(FromFunctionType->getResultType())
1666 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1667 // Okay, the types match exactly. Nothing to do.
1668 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1669 ToFunctionType->getResultType(),
1670 ConvertedType, IncompatibleObjC)) {
1671 // Okay, we have an Objective-C pointer conversion.
1672 HasObjCConversion = true;
1673 } else {
1674 // Function types are too different. Abort.
1675 return false;
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Douglas Gregora119f102008-12-19 19:13:09 +00001678 // Check argument types.
1679 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1680 ArgIdx != NumArgs; ++ArgIdx) {
1681 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1682 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1683 if (Context.getCanonicalType(FromArgType)
1684 == Context.getCanonicalType(ToArgType)) {
1685 // Okay, the types match exactly. Nothing to do.
1686 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1687 ConvertedType, IncompatibleObjC)) {
1688 // Okay, we have an Objective-C pointer conversion.
1689 HasObjCConversion = true;
1690 } else {
1691 // Argument types are too different. Abort.
1692 return false;
1693 }
1694 }
1695
1696 if (HasObjCConversion) {
1697 // We had an Objective-C conversion. Allow this pointer
1698 // conversion, but complain about it.
1699 ConvertedType = ToType;
1700 IncompatibleObjC = true;
1701 return true;
1702 }
1703 }
1704
Sebastian Redl72b597d2009-01-25 19:43:20 +00001705 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001707
1708/// FunctionArgTypesAreEqual - This routine checks two function proto types
1709/// for equlity of their argument types. Caller has already checked that
1710/// they have same number of arguments. This routine assumes that Objective-C
1711/// pointer types which only differ in their protocol qualifiers are equal.
1712bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1713 FunctionProtoType* NewType){
1714 if (!getLangOptions().ObjC1)
1715 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1716 NewType->arg_type_begin());
1717
1718 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1719 N = NewType->arg_type_begin(),
1720 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1721 QualType ToType = (*O);
1722 QualType FromType = (*N);
1723 if (ToType != FromType) {
1724 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1725 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001726 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1727 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1728 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1729 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001730 continue;
1731 }
John McCall8b07ec22010-05-15 11:32:37 +00001732 else if (const ObjCObjectPointerType *PTTo =
1733 ToType->getAs<ObjCObjectPointerType>()) {
1734 if (const ObjCObjectPointerType *PTFr =
1735 FromType->getAs<ObjCObjectPointerType>())
1736 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1737 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001738 }
1739 return false;
1740 }
1741 }
1742 return true;
1743}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744
Douglas Gregor39c16d42008-10-24 04:54:22 +00001745/// CheckPointerConversion - Check the pointer conversion from the
1746/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001747/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001748/// conversions for which IsPointerConversion has already returned
1749/// true. It returns true and produces a diagnostic if there was an
1750/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001751bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001752 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001753 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001754 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001755 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001756 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001757
John McCall8cb679e2010-11-15 09:13:47 +00001758 Kind = CK_BitCast;
1759
Douglas Gregor4038cf42010-06-08 17:35:15 +00001760 if (CXXBoolLiteralExpr* LitBool
1761 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001762 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001763 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1764 << ToType;
1765
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001766 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1767 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001768 QualType FromPointeeType = FromPtrType->getPointeeType(),
1769 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001770
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001771 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1772 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001773 // We must have a derived-to-base conversion. Check an
1774 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001775 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1776 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001777 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001778 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001779 return true;
1780
1781 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001782 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001783 }
1784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001786 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001787 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001788 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001789 // Objective-C++ conversions are always okay.
1790 // FIXME: We should have a different class of conversions for the
1791 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001792 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001793 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001794 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001795 }
John McCall8cb679e2010-11-15 09:13:47 +00001796
1797 // We shouldn't fall into this case unless it's valid for other
1798 // reasons.
1799 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1800 Kind = CK_NullToPointer;
1801
Douglas Gregor39c16d42008-10-24 04:54:22 +00001802 return false;
1803}
1804
Sebastian Redl72b597d2009-01-25 19:43:20 +00001805/// IsMemberPointerConversion - Determines whether the conversion of the
1806/// expression From, which has the (possibly adjusted) type FromType, can be
1807/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1808/// If so, returns true and places the converted type (that might differ from
1809/// ToType in its cv-qualifiers at some level) into ConvertedType.
1810bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001811 QualType ToType,
1812 bool InOverloadResolution,
1813 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001814 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001815 if (!ToTypePtr)
1816 return false;
1817
1818 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001819 if (From->isNullPointerConstant(Context,
1820 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1821 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001822 ConvertedType = ToType;
1823 return true;
1824 }
1825
1826 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001827 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001828 if (!FromTypePtr)
1829 return false;
1830
1831 // A pointer to member of B can be converted to a pointer to member of D,
1832 // where D is derived from B (C++ 4.11p2).
1833 QualType FromClass(FromTypePtr->getClass(), 0);
1834 QualType ToClass(ToTypePtr->getClass(), 0);
1835 // FIXME: What happens when these are dependent? Is this function even called?
1836
1837 if (IsDerivedFrom(ToClass, FromClass)) {
1838 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1839 ToClass.getTypePtr());
1840 return true;
1841 }
1842
1843 return false;
1844}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001845
Sebastian Redl72b597d2009-01-25 19:43:20 +00001846/// CheckMemberPointerConversion - Check the member pointer conversion from the
1847/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001848/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001849/// for which IsMemberPointerConversion has already returned true. It returns
1850/// true and produces a diagnostic if there was an error, or returns false
1851/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001852bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001853 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001854 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001855 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001856 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001857 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001858 if (!FromPtrType) {
1859 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001860 assert(From->isNullPointerConstant(Context,
1861 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001862 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001863 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001864 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001865 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001866
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001868 assert(ToPtrType && "No member pointer cast has a target type "
1869 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001870
Sebastian Redled8f2002009-01-28 18:33:18 +00001871 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1872 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001873
Sebastian Redled8f2002009-01-28 18:33:18 +00001874 // FIXME: What about dependent types?
1875 assert(FromClass->isRecordType() && "Pointer into non-class.");
1876 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001877
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001878 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001879 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001880 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1881 assert(DerivationOkay &&
1882 "Should not have been called if derivation isn't OK.");
1883 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001884
Sebastian Redled8f2002009-01-28 18:33:18 +00001885 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1886 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001887 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1888 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1889 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1890 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001891 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001892
Douglas Gregor89ee6822009-02-28 01:32:25 +00001893 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001894 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1895 << FromClass << ToClass << QualType(VBase, 0)
1896 << From->getSourceRange();
1897 return true;
1898 }
1899
John McCall5b0829a2010-02-10 09:31:12 +00001900 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001901 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1902 Paths.front(),
1903 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001904
Anders Carlssond7923c62009-08-22 23:33:40 +00001905 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001906 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001907 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001908 return false;
1909}
1910
Douglas Gregor9a657932008-10-21 23:43:52 +00001911/// IsQualificationConversion - Determines whether the conversion from
1912/// an rvalue of type FromType to ToType is a qualification conversion
1913/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001914bool
1915Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001916 FromType = Context.getCanonicalType(FromType);
1917 ToType = Context.getCanonicalType(ToType);
1918
1919 // If FromType and ToType are the same type, this is not a
1920 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001921 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001922 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001923
Douglas Gregor9a657932008-10-21 23:43:52 +00001924 // (C++ 4.4p4):
1925 // A conversion can add cv-qualifiers at levels other than the first
1926 // in multi-level pointers, subject to the following rules: [...]
1927 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001928 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001929 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001930 // Within each iteration of the loop, we check the qualifiers to
1931 // determine if this still looks like a qualification
1932 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001933 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001934 // until there are no more pointers or pointers-to-members left to
1935 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001936 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001937
1938 // -- for every j > 0, if const is in cv 1,j then const is in cv
1939 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001940 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001941 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001942
Douglas Gregor9a657932008-10-21 23:43:52 +00001943 // -- if the cv 1,j and cv 2,j are different, then const is in
1944 // every cv for 0 < k < j.
1945 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001946 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001947 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor9a657932008-10-21 23:43:52 +00001949 // Keep track of whether all prior cv-qualifiers in the "to" type
1950 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001951 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001952 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001953 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001954
1955 // We are left with FromType and ToType being the pointee types
1956 // after unwrapping the original FromType and ToType the same number
1957 // of types. If we unwrapped any pointers, and if FromType and
1958 // ToType have the same unqualified type (since we checked
1959 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001960 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001961}
1962
Douglas Gregor576e98c2009-01-30 23:27:23 +00001963/// Determines whether there is a user-defined conversion sequence
1964/// (C++ [over.ics.user]) that converts expression From to the type
1965/// ToType. If such a conversion exists, User will contain the
1966/// user-defined conversion sequence that performs such a conversion
1967/// and this routine will return true. Otherwise, this routine returns
1968/// false and User is unspecified.
1969///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001970/// \param AllowExplicit true if the conversion should consider C++0x
1971/// "explicit" conversion functions as well as non-explicit conversion
1972/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001973static OverloadingResult
1974IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1975 UserDefinedConversionSequence& User,
1976 OverloadCandidateSet& CandidateSet,
1977 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001978 // Whether we will only visit constructors.
1979 bool ConstructorsOnly = false;
1980
1981 // If the type we are conversion to is a class type, enumerate its
1982 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001983 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001984 // C++ [over.match.ctor]p1:
1985 // When objects of class type are direct-initialized (8.5), or
1986 // copy-initialized from an expression of the same or a
1987 // derived class type (8.5), overload resolution selects the
1988 // constructor. [...] For copy-initialization, the candidate
1989 // functions are all the converting constructors (12.3.1) of
1990 // that class. The argument list is the expression-list within
1991 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00001992 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00001993 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001994 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001995 ConstructorsOnly = true;
1996
John McCall5c32be02010-08-24 20:38:10 +00001997 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001998 // We're not going to find any constructors.
1999 } else if (CXXRecordDecl *ToRecordDecl
2000 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002001 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002002 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002003 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002004 NamedDecl *D = *Con;
2005 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2006
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002007 // Find the constructor (which may be a template).
2008 CXXConstructorDecl *Constructor = 0;
2009 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002010 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002011 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002012 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002013 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2014 else
John McCalla0296f72010-03-19 07:35:19 +00002015 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002016
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002017 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002018 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002019 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002020 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2021 /*ExplicitArgs*/ 0,
2022 &From, 1, CandidateSet,
2023 /*SuppressUserConversions=*/
2024 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002025 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002026 // Allow one user-defined conversion when user specifies a
2027 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002028 S.AddOverloadCandidate(Constructor, FoundDecl,
2029 &From, 1, CandidateSet,
2030 /*SuppressUserConversions=*/
2031 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002032 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002033 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002034 }
2035 }
2036
Douglas Gregor5ab11652010-04-17 22:01:05 +00002037 // Enumerate conversion functions, if we're allowed to.
2038 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002039 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2040 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002041 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002042 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002043 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002044 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002045 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2046 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002047 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002048 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002049 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002050 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002051 DeclAccessPair FoundDecl = I.getPair();
2052 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002053 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2054 if (isa<UsingShadowDecl>(D))
2055 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2056
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002057 CXXConversionDecl *Conv;
2058 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002059 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2060 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002061 else
John McCallda4458e2010-03-31 01:36:47 +00002062 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002063
2064 if (AllowExplicit || !Conv->isExplicit()) {
2065 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002066 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2067 ActingContext, From, ToType,
2068 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002069 else
John McCall5c32be02010-08-24 20:38:10 +00002070 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2071 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002072 }
2073 }
2074 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002075 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002076
2077 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002078 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002079 case OR_Success:
2080 // Record the standard conversion we used and the conversion function.
2081 if (CXXConstructorDecl *Constructor
2082 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2083 // C++ [over.ics.user]p1:
2084 // If the user-defined conversion is specified by a
2085 // constructor (12.3.1), the initial standard conversion
2086 // sequence converts the source type to the type required by
2087 // the argument of the constructor.
2088 //
2089 QualType ThisType = Constructor->getThisType(S.Context);
2090 if (Best->Conversions[0].isEllipsis())
2091 User.EllipsisConversion = true;
2092 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002093 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002094 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002095 }
John McCall5c32be02010-08-24 20:38:10 +00002096 User.ConversionFunction = Constructor;
2097 User.After.setAsIdentityConversion();
2098 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2099 User.After.setAllToTypes(ToType);
2100 return OR_Success;
2101 } else if (CXXConversionDecl *Conversion
2102 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2103 // C++ [over.ics.user]p1:
2104 //
2105 // [...] If the user-defined conversion is specified by a
2106 // conversion function (12.3.2), the initial standard
2107 // conversion sequence converts the source type to the
2108 // implicit object parameter of the conversion function.
2109 User.Before = Best->Conversions[0].Standard;
2110 User.ConversionFunction = Conversion;
2111 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002112
John McCall5c32be02010-08-24 20:38:10 +00002113 // C++ [over.ics.user]p2:
2114 // The second standard conversion sequence converts the
2115 // result of the user-defined conversion to the target type
2116 // for the sequence. Since an implicit conversion sequence
2117 // is an initialization, the special rules for
2118 // initialization by user-defined conversion apply when
2119 // selecting the best user-defined conversion for a
2120 // user-defined conversion sequence (see 13.3.3 and
2121 // 13.3.3.1).
2122 User.After = Best->FinalConversion;
2123 return OR_Success;
2124 } else {
2125 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002126 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002127 }
2128
John McCall5c32be02010-08-24 20:38:10 +00002129 case OR_No_Viable_Function:
2130 return OR_No_Viable_Function;
2131 case OR_Deleted:
2132 // No conversion here! We're done.
2133 return OR_Deleted;
2134
2135 case OR_Ambiguous:
2136 return OR_Ambiguous;
2137 }
2138
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002139 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002140}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002141
2142bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002143Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002144 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002145 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002146 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002147 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002148 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002149 if (OvResult == OR_Ambiguous)
2150 Diag(From->getSourceRange().getBegin(),
2151 diag::err_typecheck_ambiguous_condition)
2152 << From->getType() << ToType << From->getSourceRange();
2153 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2154 Diag(From->getSourceRange().getBegin(),
2155 diag::err_typecheck_nonviable_condition)
2156 << From->getType() << ToType << From->getSourceRange();
2157 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002158 return false;
John McCall5c32be02010-08-24 20:38:10 +00002159 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002160 return true;
2161}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002162
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002163/// CompareImplicitConversionSequences - Compare two implicit
2164/// conversion sequences to determine whether one is better than the
2165/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002166static ImplicitConversionSequence::CompareKind
2167CompareImplicitConversionSequences(Sema &S,
2168 const ImplicitConversionSequence& ICS1,
2169 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002170{
2171 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2172 // conversion sequences (as defined in 13.3.3.1)
2173 // -- a standard conversion sequence (13.3.3.1.1) is a better
2174 // conversion sequence than a user-defined conversion sequence or
2175 // an ellipsis conversion sequence, and
2176 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2177 // conversion sequence than an ellipsis conversion sequence
2178 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002179 //
John McCall0d1da222010-01-12 00:44:57 +00002180 // C++0x [over.best.ics]p10:
2181 // For the purpose of ranking implicit conversion sequences as
2182 // described in 13.3.3.2, the ambiguous conversion sequence is
2183 // treated as a user-defined sequence that is indistinguishable
2184 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002185 if (ICS1.getKindRank() < ICS2.getKindRank())
2186 return ImplicitConversionSequence::Better;
2187 else if (ICS2.getKindRank() < ICS1.getKindRank())
2188 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002189
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002190 // The following checks require both conversion sequences to be of
2191 // the same kind.
2192 if (ICS1.getKind() != ICS2.getKind())
2193 return ImplicitConversionSequence::Indistinguishable;
2194
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195 // Two implicit conversion sequences of the same form are
2196 // indistinguishable conversion sequences unless one of the
2197 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002198 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002199 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002200 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002201 // User-defined conversion sequence U1 is a better conversion
2202 // sequence than another user-defined conversion sequence U2 if
2203 // they contain the same user-defined conversion function or
2204 // constructor and if the second standard conversion sequence of
2205 // U1 is better than the second standard conversion sequence of
2206 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002207 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002208 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002209 return CompareStandardConversionSequences(S,
2210 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211 ICS2.UserDefined.After);
2212 }
2213
2214 return ImplicitConversionSequence::Indistinguishable;
2215}
2216
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002217static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2218 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2219 Qualifiers Quals;
2220 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2221 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2222 }
2223
2224 return Context.hasSameUnqualifiedType(T1, T2);
2225}
2226
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002227// Per 13.3.3.2p3, compare the given standard conversion sequences to
2228// determine if one is a proper subset of the other.
2229static ImplicitConversionSequence::CompareKind
2230compareStandardConversionSubsets(ASTContext &Context,
2231 const StandardConversionSequence& SCS1,
2232 const StandardConversionSequence& SCS2) {
2233 ImplicitConversionSequence::CompareKind Result
2234 = ImplicitConversionSequence::Indistinguishable;
2235
Douglas Gregore87561a2010-05-23 22:10:15 +00002236 // the identity conversion sequence is considered to be a subsequence of
2237 // any non-identity conversion sequence
2238 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2239 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2240 return ImplicitConversionSequence::Better;
2241 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2242 return ImplicitConversionSequence::Worse;
2243 }
2244
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002245 if (SCS1.Second != SCS2.Second) {
2246 if (SCS1.Second == ICK_Identity)
2247 Result = ImplicitConversionSequence::Better;
2248 else if (SCS2.Second == ICK_Identity)
2249 Result = ImplicitConversionSequence::Worse;
2250 else
2251 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002252 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002253 return ImplicitConversionSequence::Indistinguishable;
2254
2255 if (SCS1.Third == SCS2.Third) {
2256 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2257 : ImplicitConversionSequence::Indistinguishable;
2258 }
2259
2260 if (SCS1.Third == ICK_Identity)
2261 return Result == ImplicitConversionSequence::Worse
2262 ? ImplicitConversionSequence::Indistinguishable
2263 : ImplicitConversionSequence::Better;
2264
2265 if (SCS2.Third == ICK_Identity)
2266 return Result == ImplicitConversionSequence::Better
2267 ? ImplicitConversionSequence::Indistinguishable
2268 : ImplicitConversionSequence::Worse;
2269
2270 return ImplicitConversionSequence::Indistinguishable;
2271}
2272
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002273/// CompareStandardConversionSequences - Compare two standard
2274/// conversion sequences to determine whether one is better than the
2275/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002276static ImplicitConversionSequence::CompareKind
2277CompareStandardConversionSequences(Sema &S,
2278 const StandardConversionSequence& SCS1,
2279 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002280{
2281 // Standard conversion sequence S1 is a better conversion sequence
2282 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2283
2284 // -- S1 is a proper subsequence of S2 (comparing the conversion
2285 // sequences in the canonical form defined by 13.3.3.1.1,
2286 // excluding any Lvalue Transformation; the identity conversion
2287 // sequence is considered to be a subsequence of any
2288 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002289 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002290 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002291 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292
2293 // -- the rank of S1 is better than the rank of S2 (by the rules
2294 // defined below), or, if not that,
2295 ImplicitConversionRank Rank1 = SCS1.getRank();
2296 ImplicitConversionRank Rank2 = SCS2.getRank();
2297 if (Rank1 < Rank2)
2298 return ImplicitConversionSequence::Better;
2299 else if (Rank2 < Rank1)
2300 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002301
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002302 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2303 // are indistinguishable unless one of the following rules
2304 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002305
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002306 // A conversion that is not a conversion of a pointer, or
2307 // pointer to member, to bool is better than another conversion
2308 // that is such a conversion.
2309 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2310 return SCS2.isPointerConversionToBool()
2311 ? ImplicitConversionSequence::Better
2312 : ImplicitConversionSequence::Worse;
2313
Douglas Gregor5c407d92008-10-23 00:40:37 +00002314 // C++ [over.ics.rank]p4b2:
2315 //
2316 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002317 // conversion of B* to A* is better than conversion of B* to
2318 // void*, and conversion of A* to void* is better than conversion
2319 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002320 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002321 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002322 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002323 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002324 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2325 // Exactly one of the conversion sequences is a conversion to
2326 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002327 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2328 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002329 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2330 // Neither conversion sequence converts to a void pointer; compare
2331 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002332 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002333 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002334 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002335 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2336 // Both conversion sequences are conversions to void
2337 // pointers. Compare the source types to determine if there's an
2338 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002339 QualType FromType1 = SCS1.getFromType();
2340 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341
2342 // Adjust the types we're converting from via the array-to-pointer
2343 // conversion, if we need to.
2344 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002345 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002346 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002347 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002348
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002349 QualType FromPointee1
2350 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2351 QualType FromPointee2
2352 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002353
John McCall5c32be02010-08-24 20:38:10 +00002354 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002355 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002356 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002357 return ImplicitConversionSequence::Worse;
2358
2359 // Objective-C++: If one interface is more specific than the
2360 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002361 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2362 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002363 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002364 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002365 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002366 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002367 return ImplicitConversionSequence::Worse;
2368 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002369 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002370
2371 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2372 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002373 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002374 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002375 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002376
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002377 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002378 // C++0x [over.ics.rank]p3b4:
2379 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2380 // implicit object parameter of a non-static member function declared
2381 // without a ref-qualifier, and S1 binds an rvalue reference to an
2382 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002383 // FIXME: We don't know if we're dealing with the implicit object parameter,
2384 // or if the member function in this case has a ref qualifier.
2385 // (Of course, we don't have ref qualifiers yet.)
2386 if (SCS1.RRefBinding != SCS2.RRefBinding)
2387 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2388 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002389
2390 // C++ [over.ics.rank]p3b4:
2391 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2392 // which the references refer are the same type except for
2393 // top-level cv-qualifiers, and the type to which the reference
2394 // initialized by S2 refers is more cv-qualified than the type
2395 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002396 QualType T1 = SCS1.getToType(2);
2397 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002398 T1 = S.Context.getCanonicalType(T1);
2399 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002400 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002401 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2402 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002403 if (UnqualT1 == UnqualT2) {
2404 // If the type is an array type, promote the element qualifiers to the type
2405 // for comparison.
2406 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002407 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002408 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002409 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002410 if (T2.isMoreQualifiedThan(T1))
2411 return ImplicitConversionSequence::Better;
2412 else if (T1.isMoreQualifiedThan(T2))
2413 return ImplicitConversionSequence::Worse;
2414 }
2415 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002416
2417 return ImplicitConversionSequence::Indistinguishable;
2418}
2419
2420/// CompareQualificationConversions - Compares two standard conversion
2421/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002422/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2423ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002424CompareQualificationConversions(Sema &S,
2425 const StandardConversionSequence& SCS1,
2426 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002427 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002428 // -- S1 and S2 differ only in their qualification conversion and
2429 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2430 // cv-qualification signature of type T1 is a proper subset of
2431 // the cv-qualification signature of type T2, and S1 is not the
2432 // deprecated string literal array-to-pointer conversion (4.2).
2433 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2434 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2435 return ImplicitConversionSequence::Indistinguishable;
2436
2437 // FIXME: the example in the standard doesn't use a qualification
2438 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002439 QualType T1 = SCS1.getToType(2);
2440 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002441 T1 = S.Context.getCanonicalType(T1);
2442 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002443 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002444 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2445 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002446
2447 // If the types are the same, we won't learn anything by unwrapped
2448 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002449 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002450 return ImplicitConversionSequence::Indistinguishable;
2451
Chandler Carruth607f38e2009-12-29 07:16:59 +00002452 // If the type is an array type, promote the element qualifiers to the type
2453 // for comparison.
2454 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002455 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002456 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002457 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002458
Mike Stump11289f42009-09-09 15:08:12 +00002459 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002460 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002461 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002462 // Within each iteration of the loop, we check the qualifiers to
2463 // determine if this still looks like a qualification
2464 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002465 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002466 // until there are no more pointers or pointers-to-members left
2467 // to unwrap. This essentially mimics what
2468 // IsQualificationConversion does, but here we're checking for a
2469 // strict subset of qualifiers.
2470 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2471 // The qualifiers are the same, so this doesn't tell us anything
2472 // about how the sequences rank.
2473 ;
2474 else if (T2.isMoreQualifiedThan(T1)) {
2475 // T1 has fewer qualifiers, so it could be the better sequence.
2476 if (Result == ImplicitConversionSequence::Worse)
2477 // Neither has qualifiers that are a subset of the other's
2478 // qualifiers.
2479 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002480
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002481 Result = ImplicitConversionSequence::Better;
2482 } else if (T1.isMoreQualifiedThan(T2)) {
2483 // T2 has fewer qualifiers, so it could be the better sequence.
2484 if (Result == ImplicitConversionSequence::Better)
2485 // Neither has qualifiers that are a subset of the other's
2486 // qualifiers.
2487 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002489 Result = ImplicitConversionSequence::Worse;
2490 } else {
2491 // Qualifiers are disjoint.
2492 return ImplicitConversionSequence::Indistinguishable;
2493 }
2494
2495 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002496 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002497 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002498 }
2499
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002500 // Check that the winning standard conversion sequence isn't using
2501 // the deprecated string literal array to pointer conversion.
2502 switch (Result) {
2503 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002504 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002505 Result = ImplicitConversionSequence::Indistinguishable;
2506 break;
2507
2508 case ImplicitConversionSequence::Indistinguishable:
2509 break;
2510
2511 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002512 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002513 Result = ImplicitConversionSequence::Indistinguishable;
2514 break;
2515 }
2516
2517 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002518}
2519
Douglas Gregor5c407d92008-10-23 00:40:37 +00002520/// CompareDerivedToBaseConversions - Compares two standard conversion
2521/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002522/// various kinds of derived-to-base conversions (C++
2523/// [over.ics.rank]p4b3). As part of these checks, we also look at
2524/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002525ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002526CompareDerivedToBaseConversions(Sema &S,
2527 const StandardConversionSequence& SCS1,
2528 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002529 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002530 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002531 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002532 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002533
2534 // Adjust the types we're converting from via the array-to-pointer
2535 // conversion, if we need to.
2536 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002537 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002538 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002539 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002540
2541 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002542 FromType1 = S.Context.getCanonicalType(FromType1);
2543 ToType1 = S.Context.getCanonicalType(ToType1);
2544 FromType2 = S.Context.getCanonicalType(FromType2);
2545 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002546
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002547 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002548 //
2549 // If class B is derived directly or indirectly from class A and
2550 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002551 //
2552 // For Objective-C, we let A, B, and C also be Objective-C
2553 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002554
2555 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002556 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002557 SCS2.Second == ICK_Pointer_Conversion &&
2558 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2559 FromType1->isPointerType() && FromType2->isPointerType() &&
2560 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002561 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002562 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002563 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002564 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002565 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002566 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002567 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002568 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002569
John McCall8b07ec22010-05-15 11:32:37 +00002570 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2571 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2572 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2573 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002574
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002575 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002576 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002577 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002578 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002579 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002580 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002581
2582 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002583 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002584 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002585 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002586 return ImplicitConversionSequence::Worse;
2587 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002588 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002589
2590 // -- conversion of B* to A* is better than conversion of C* to A*,
2591 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002592 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002593 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002594 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002595 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002596
Douglas Gregor237f96c2008-11-26 23:31:11 +00002597 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002598 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002599 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002600 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002601 return ImplicitConversionSequence::Worse;
2602 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002603 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002604 }
2605
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002606 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002607 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2608 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2609 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2610 const MemberPointerType * FromMemPointer1 =
2611 FromType1->getAs<MemberPointerType>();
2612 const MemberPointerType * ToMemPointer1 =
2613 ToType1->getAs<MemberPointerType>();
2614 const MemberPointerType * FromMemPointer2 =
2615 FromType2->getAs<MemberPointerType>();
2616 const MemberPointerType * ToMemPointer2 =
2617 ToType2->getAs<MemberPointerType>();
2618 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2619 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2620 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2621 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2622 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2623 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2624 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2625 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002626 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002627 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002628 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002629 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002630 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002631 return ImplicitConversionSequence::Better;
2632 }
2633 // conversion of B::* to C::* is better than conversion of A::* to C::*
2634 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002635 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002636 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002637 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002638 return ImplicitConversionSequence::Worse;
2639 }
2640 }
2641
Douglas Gregor5ab11652010-04-17 22:01:05 +00002642 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002643 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002644 // -- binding of an expression of type C to a reference of type
2645 // B& is better than binding an expression of type C to a
2646 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002647 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2648 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2649 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002650 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002651 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002652 return ImplicitConversionSequence::Worse;
2653 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002654
Douglas Gregor2fe98832008-11-03 19:09:14 +00002655 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002656 // -- binding of an expression of type B to a reference of type
2657 // A& 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(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002662 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002663 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002664 return ImplicitConversionSequence::Worse;
2665 }
2666 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002667
Douglas Gregor5c407d92008-10-23 00:40:37 +00002668 return ImplicitConversionSequence::Indistinguishable;
2669}
2670
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002671/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2672/// determine whether they are reference-related,
2673/// reference-compatible, reference-compatible with added
2674/// qualification, or incompatible, for use in C++ initialization by
2675/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2676/// type, and the first type (T1) is the pointee type of the reference
2677/// type being initialized.
2678Sema::ReferenceCompareResult
2679Sema::CompareReferenceRelationship(SourceLocation Loc,
2680 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002681 bool &DerivedToBase,
2682 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002683 assert(!OrigT1->isReferenceType() &&
2684 "T1 must be the pointee type of the reference type");
2685 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2686
2687 QualType T1 = Context.getCanonicalType(OrigT1);
2688 QualType T2 = Context.getCanonicalType(OrigT2);
2689 Qualifiers T1Quals, T2Quals;
2690 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2691 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2692
2693 // C++ [dcl.init.ref]p4:
2694 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2695 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2696 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002697 DerivedToBase = false;
2698 ObjCConversion = false;
2699 if (UnqualT1 == UnqualT2) {
2700 // Nothing to do.
2701 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002702 IsDerivedFrom(UnqualT2, UnqualT1))
2703 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002704 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2705 UnqualT2->isObjCObjectOrInterfaceType() &&
2706 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2707 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002708 else
2709 return Ref_Incompatible;
2710
2711 // At this point, we know that T1 and T2 are reference-related (at
2712 // least).
2713
2714 // If the type is an array type, promote the element qualifiers to the type
2715 // for comparison.
2716 if (isa<ArrayType>(T1) && T1Quals)
2717 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2718 if (isa<ArrayType>(T2) && T2Quals)
2719 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2720
2721 // C++ [dcl.init.ref]p4:
2722 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2723 // reference-related to T2 and cv1 is the same cv-qualification
2724 // as, or greater cv-qualification than, cv2. For purposes of
2725 // overload resolution, cases for which cv1 is greater
2726 // cv-qualification than cv2 are identified as
2727 // reference-compatible with added qualification (see 13.3.3.2).
2728 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2729 return Ref_Compatible;
2730 else if (T1.isMoreQualifiedThan(T2))
2731 return Ref_Compatible_With_Added_Qualification;
2732 else
2733 return Ref_Related;
2734}
2735
Douglas Gregor836a7e82010-08-11 02:15:33 +00002736/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002737/// with DeclType. Return true if something definite is found.
2738static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002739FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2740 QualType DeclType, SourceLocation DeclLoc,
2741 Expr *Init, QualType T2, bool AllowRvalues,
2742 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002743 assert(T2->isRecordType() && "Can only find conversions of record types.");
2744 CXXRecordDecl *T2RecordDecl
2745 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2746
Douglas Gregor836a7e82010-08-11 02:15:33 +00002747 QualType ToType
2748 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2749 : DeclType;
2750
Sebastian Redld92badf2010-06-30 18:13:39 +00002751 OverloadCandidateSet CandidateSet(DeclLoc);
2752 const UnresolvedSetImpl *Conversions
2753 = T2RecordDecl->getVisibleConversionFunctions();
2754 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2755 E = Conversions->end(); I != E; ++I) {
2756 NamedDecl *D = *I;
2757 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2758 if (isa<UsingShadowDecl>(D))
2759 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2760
2761 FunctionTemplateDecl *ConvTemplate
2762 = dyn_cast<FunctionTemplateDecl>(D);
2763 CXXConversionDecl *Conv;
2764 if (ConvTemplate)
2765 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2766 else
2767 Conv = cast<CXXConversionDecl>(D);
2768
Douglas Gregor836a7e82010-08-11 02:15:33 +00002769 // If this is an explicit conversion, and we're not allowed to consider
2770 // explicit conversions, skip it.
2771 if (!AllowExplicit && Conv->isExplicit())
2772 continue;
2773
2774 if (AllowRvalues) {
2775 bool DerivedToBase = false;
2776 bool ObjCConversion = false;
2777 if (!ConvTemplate &&
2778 S.CompareReferenceRelationship(DeclLoc,
2779 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2780 DeclType.getNonReferenceType().getUnqualifiedType(),
2781 DerivedToBase, ObjCConversion)
2782 == Sema::Ref_Incompatible)
2783 continue;
2784 } else {
2785 // If the conversion function doesn't return a reference type,
2786 // it can't be considered for this conversion. An rvalue reference
2787 // is only acceptable if its referencee is a function type.
2788
2789 const ReferenceType *RefType =
2790 Conv->getConversionType()->getAs<ReferenceType>();
2791 if (!RefType ||
2792 (!RefType->isLValueReferenceType() &&
2793 !RefType->getPointeeType()->isFunctionType()))
2794 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002795 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002796
2797 if (ConvTemplate)
2798 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2799 Init, ToType, CandidateSet);
2800 else
2801 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2802 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002803 }
2804
2805 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002806 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002807 case OR_Success:
2808 // C++ [over.ics.ref]p1:
2809 //
2810 // [...] If the parameter binds directly to the result of
2811 // applying a conversion function to the argument
2812 // expression, the implicit conversion sequence is a
2813 // user-defined conversion sequence (13.3.3.1.2), with the
2814 // second standard conversion sequence either an identity
2815 // conversion or, if the conversion function returns an
2816 // entity of a type that is a derived class of the parameter
2817 // type, a derived-to-base Conversion.
2818 if (!Best->FinalConversion.DirectBinding)
2819 return false;
2820
2821 ICS.setUserDefined();
2822 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2823 ICS.UserDefined.After = Best->FinalConversion;
2824 ICS.UserDefined.ConversionFunction = Best->Function;
2825 ICS.UserDefined.EllipsisConversion = false;
2826 assert(ICS.UserDefined.After.ReferenceBinding &&
2827 ICS.UserDefined.After.DirectBinding &&
2828 "Expected a direct reference binding!");
2829 return true;
2830
2831 case OR_Ambiguous:
2832 ICS.setAmbiguous();
2833 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2834 Cand != CandidateSet.end(); ++Cand)
2835 if (Cand->Viable)
2836 ICS.Ambiguous.addConversion(Cand->Function);
2837 return true;
2838
2839 case OR_No_Viable_Function:
2840 case OR_Deleted:
2841 // There was no suitable conversion, or we found a deleted
2842 // conversion; continue with other checks.
2843 return false;
2844 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002845
2846 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002847}
2848
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002849/// \brief Compute an implicit conversion sequence for reference
2850/// initialization.
2851static ImplicitConversionSequence
2852TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2853 SourceLocation DeclLoc,
2854 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002855 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002856 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2857
2858 // Most paths end in a failed conversion.
2859 ImplicitConversionSequence ICS;
2860 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2861
2862 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2863 QualType T2 = Init->getType();
2864
2865 // If the initializer is the address of an overloaded function, try
2866 // to resolve the overloaded function. If all goes well, T2 is the
2867 // type of the resulting function.
2868 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2869 DeclAccessPair Found;
2870 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2871 false, Found))
2872 T2 = Fn->getType();
2873 }
2874
2875 // Compute some basic properties of the types and the initializer.
2876 bool isRValRef = DeclType->isRValueReferenceType();
2877 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002878 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002879 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002880 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002881 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2882 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002883
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002884
Sebastian Redld92badf2010-06-30 18:13:39 +00002885 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002886 // A reference to type "cv1 T1" is initialized by an expression
2887 // of type "cv2 T2" as follows:
2888
Sebastian Redld92badf2010-06-30 18:13:39 +00002889 // -- If reference is an lvalue reference and the initializer expression
2890 // The next bullet point (T1 is a function) is pretty much equivalent to this
2891 // one, so it's handled here.
2892 if (!isRValRef || T1->isFunctionType()) {
2893 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2894 // reference-compatible with "cv2 T2," or
2895 //
2896 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2897 if (InitCategory.isLValue() &&
2898 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002899 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002900 // When a parameter of reference type binds directly (8.5.3)
2901 // to an argument expression, the implicit conversion sequence
2902 // is the identity conversion, unless the argument expression
2903 // has a type that is a derived class of the parameter type,
2904 // in which case the implicit conversion sequence is a
2905 // derived-to-base Conversion (13.3.3.1).
2906 ICS.setStandard();
2907 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002908 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2909 : ObjCConversion? ICK_Compatible_Conversion
2910 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002911 ICS.Standard.Third = ICK_Identity;
2912 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2913 ICS.Standard.setToType(0, T2);
2914 ICS.Standard.setToType(1, T1);
2915 ICS.Standard.setToType(2, T1);
2916 ICS.Standard.ReferenceBinding = true;
2917 ICS.Standard.DirectBinding = true;
2918 ICS.Standard.RRefBinding = isRValRef;
2919 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002920
Sebastian Redld92badf2010-06-30 18:13:39 +00002921 // Nothing more to do: the inaccessibility/ambiguity check for
2922 // derived-to-base conversions is suppressed when we're
2923 // computing the implicit conversion sequence (C++
2924 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002925 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002926 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002927
Sebastian Redld92badf2010-06-30 18:13:39 +00002928 // -- has a class type (i.e., T2 is a class type), where T1 is
2929 // not reference-related to T2, and can be implicitly
2930 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2931 // is reference-compatible with "cv3 T3" 92) (this
2932 // conversion is selected by enumerating the applicable
2933 // conversion functions (13.3.1.6) and choosing the best
2934 // one through overload resolution (13.3)),
2935 if (!SuppressUserConversions && T2->isRecordType() &&
2936 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2937 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002938 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2939 Init, T2, /*AllowRvalues=*/false,
2940 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002941 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002942 }
2943 }
2944
Sebastian Redld92badf2010-06-30 18:13:39 +00002945 // -- Otherwise, the reference shall be an lvalue reference to a
2946 // non-volatile const type (i.e., cv1 shall be const), or the reference
2947 // shall be an rvalue reference and the initializer expression shall be
2948 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002949 //
2950 // We actually handle one oddity of C++ [over.ics.ref] at this
2951 // point, which is that, due to p2 (which short-circuits reference
2952 // binding by only attempting a simple conversion for non-direct
2953 // bindings) and p3's strange wording, we allow a const volatile
2954 // reference to bind to an rvalue. Hence the check for the presence
2955 // of "const" rather than checking for "const" being the only
2956 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002957 // This is also the point where rvalue references and lvalue inits no longer
2958 // go together.
2959 if ((!isRValRef && !T1.isConstQualified()) ||
2960 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002961 return ICS;
2962
Sebastian Redld92badf2010-06-30 18:13:39 +00002963 // -- If T1 is a function type, then
2964 // -- if T2 is the same type as T1, the reference is bound to the
2965 // initializer expression lvalue;
2966 // -- if T2 is a class type and the initializer expression can be
2967 // implicitly converted to an lvalue of type T1 [...], the
2968 // reference is bound to the function lvalue that is the result
2969 // of the conversion;
2970 // This is the same as for the lvalue case above, so it was handled there.
2971 // -- otherwise, the program is ill-formed.
2972 // This is the one difference to the lvalue case.
2973 if (T1->isFunctionType())
2974 return ICS;
2975
2976 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002977 // -- the initializer expression is an rvalue and "cv1 T1"
2978 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002979 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002980 // -- T1 is not reference-related to T2 and the initializer
2981 // expression can be implicitly converted to an rvalue
2982 // of type "cv3 T3" (this conversion is selected by
2983 // enumerating the applicable conversion functions
2984 // (13.3.1.6) and choosing the best one through overload
2985 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002986 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002987 // then the reference is bound to the initializer
2988 // expression rvalue in the first case and to the object
2989 // that is the result of the conversion in the second case
2990 // (or, in either case, to the appropriate base class
2991 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002992 if (T2->isRecordType()) {
2993 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2994 // direct binding in C++0x but not in C++03.
2995 if (InitCategory.isRValue() &&
2996 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2997 ICS.setStandard();
2998 ICS.Standard.First = ICK_Identity;
2999 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3000 : ObjCConversion? ICK_Compatible_Conversion
3001 : ICK_Identity;
3002 ICS.Standard.Third = ICK_Identity;
3003 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3004 ICS.Standard.setToType(0, T2);
3005 ICS.Standard.setToType(1, T1);
3006 ICS.Standard.setToType(2, T1);
3007 ICS.Standard.ReferenceBinding = true;
3008 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3009 ICS.Standard.RRefBinding = isRValRef;
3010 ICS.Standard.CopyConstructor = 0;
3011 return ICS;
3012 }
3013
3014 // Second case: not reference-related.
3015 if (RefRelationship == Sema::Ref_Incompatible &&
3016 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3017 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3018 Init, T2, /*AllowRvalues=*/true,
3019 AllowExplicit))
3020 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003021 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003022
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003023 // -- Otherwise, a temporary of type "cv1 T1" is created and
3024 // initialized from the initializer expression using the
3025 // rules for a non-reference copy initialization (8.5). The
3026 // reference is then bound to the temporary. If T1 is
3027 // reference-related to T2, cv1 must be the same
3028 // cv-qualification as, or greater cv-qualification than,
3029 // cv2; otherwise, the program is ill-formed.
3030 if (RefRelationship == Sema::Ref_Related) {
3031 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3032 // we would be reference-compatible or reference-compatible with
3033 // added qualification. But that wasn't the case, so the reference
3034 // initialization fails.
3035 return ICS;
3036 }
3037
3038 // If at least one of the types is a class type, the types are not
3039 // related, and we aren't allowed any user conversions, the
3040 // reference binding fails. This case is important for breaking
3041 // recursion, since TryImplicitConversion below will attempt to
3042 // create a temporary through the use of a copy constructor.
3043 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3044 (T1->isRecordType() || T2->isRecordType()))
3045 return ICS;
3046
3047 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003048 // When a parameter of reference type is not bound directly to
3049 // an argument expression, the conversion sequence is the one
3050 // required to convert the argument expression to the
3051 // underlying type of the reference according to
3052 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3053 // to copy-initializing a temporary of the underlying type with
3054 // the argument expression. Any difference in top-level
3055 // cv-qualification is subsumed by the initialization itself
3056 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003057 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3058 /*AllowExplicit=*/false,
3059 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003060
3061 // Of course, that's still a reference binding.
3062 if (ICS.isStandard()) {
3063 ICS.Standard.ReferenceBinding = true;
3064 ICS.Standard.RRefBinding = isRValRef;
3065 } else if (ICS.isUserDefined()) {
3066 ICS.UserDefined.After.ReferenceBinding = true;
3067 ICS.UserDefined.After.RRefBinding = isRValRef;
3068 }
3069 return ICS;
3070}
3071
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003072/// TryCopyInitialization - Try to copy-initialize a value of type
3073/// ToType from the expression From. Return the implicit conversion
3074/// sequence required to pass this argument, which may be a bad
3075/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003076/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003077/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003078static ImplicitConversionSequence
3079TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003080 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003081 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003082 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003083 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003084 /*FIXME:*/From->getLocStart(),
3085 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003086 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003087
John McCall5c32be02010-08-24 20:38:10 +00003088 return TryImplicitConversion(S, From, ToType,
3089 SuppressUserConversions,
3090 /*AllowExplicit=*/false,
3091 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003092}
3093
Douglas Gregor436424c2008-11-18 23:14:02 +00003094/// TryObjectArgumentInitialization - Try to initialize the object
3095/// parameter of the given member function (@c Method) from the
3096/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003097static ImplicitConversionSequence
3098TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3099 CXXMethodDecl *Method,
3100 CXXRecordDecl *ActingContext) {
3101 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003102 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3103 // const volatile object.
3104 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3105 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003106 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003107
3108 // Set up the conversion sequence as a "bad" conversion, to allow us
3109 // to exit early.
3110 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003111
3112 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003113 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003114 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003115 FromType = PT->getPointeeType();
3116
3117 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003118
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003119 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003120 // where X is the class of which the function is a member
3121 // (C++ [over.match.funcs]p4). However, when finding an implicit
3122 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003123 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003124 // (C++ [over.match.funcs]p5). We perform a simplified version of
3125 // reference binding here, that allows class rvalues to bind to
3126 // non-constant references.
3127
3128 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3129 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003130 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003131 if (ImplicitParamType.getCVRQualifiers()
3132 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003133 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003134 ICS.setBad(BadConversionSequence::bad_qualifiers,
3135 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003136 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003137 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003138
3139 // Check that we have either the same type or a derived type. It
3140 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003141 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003142 ImplicitConversionKind SecondKind;
3143 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3144 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003145 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003146 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003147 else {
John McCall65eb8792010-02-25 01:37:24 +00003148 ICS.setBad(BadConversionSequence::unrelated_class,
3149 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003150 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003151 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003152
3153 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003154 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003155 ICS.Standard.setAsIdentityConversion();
3156 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003157 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003158 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003159 ICS.Standard.ReferenceBinding = true;
3160 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003161 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003162 return ICS;
3163}
3164
3165/// PerformObjectArgumentInitialization - Perform initialization of
3166/// the implicit object parameter for the given Method with the given
3167/// expression.
3168bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003169Sema::PerformObjectArgumentInitialization(Expr *&From,
3170 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003171 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003172 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003173 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003174 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003175 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003176
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003177 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003178 FromRecordType = PT->getPointeeType();
3179 DestType = Method->getThisType(Context);
3180 } else {
3181 FromRecordType = From->getType();
3182 DestType = ImplicitParamRecordType;
3183 }
3184
John McCall6e9f8f62009-12-03 04:06:58 +00003185 // Note that we always use the true parent context when performing
3186 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003187 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003188 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003189 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003190 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003191 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003192 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003193 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003194
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003195 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003196 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003197
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003198 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003199 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003200 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003201 return false;
3202}
3203
Douglas Gregor5fb53972009-01-14 15:45:31 +00003204/// TryContextuallyConvertToBool - Attempt to contextually convert the
3205/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003206static ImplicitConversionSequence
3207TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003208 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003209 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003210 // FIXME: Are these flags correct?
3211 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003212 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003213 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003214}
3215
3216/// PerformContextuallyConvertToBool - Perform a contextual conversion
3217/// of the expression From to bool (C++0x [conv]p3).
3218bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003219 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003220 if (!ICS.isBad())
3221 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003222
Fariborz Jahanian76197412009-11-18 18:26:29 +00003223 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003224 return Diag(From->getSourceRange().getBegin(),
3225 diag::err_typecheck_bool_condition)
3226 << From->getType() << From->getSourceRange();
3227 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003228}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003229
3230/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3231/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003232static ImplicitConversionSequence
3233TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3234 QualType Ty = S.Context.getObjCIdType();
3235 return TryImplicitConversion(S, From, Ty,
3236 // FIXME: Are these flags correct?
3237 /*SuppressUserConversions=*/false,
3238 /*AllowExplicit=*/true,
3239 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003240}
John McCall5c32be02010-08-24 20:38:10 +00003241
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003242/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3243/// of the expression From to 'id'.
3244bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003245 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003246 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003247 if (!ICS.isBad())
3248 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3249 return true;
3250}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003251
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003252/// \brief Attempt to convert the given expression to an integral or
3253/// enumeration type.
3254///
3255/// This routine will attempt to convert an expression of class type to an
3256/// integral or enumeration type, if that class type only has a single
3257/// conversion to an integral or enumeration type.
3258///
Douglas Gregor4799d032010-06-30 00:20:43 +00003259/// \param Loc The source location of the construct that requires the
3260/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003261///
Douglas Gregor4799d032010-06-30 00:20:43 +00003262/// \param FromE The expression we're converting from.
3263///
3264/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3265/// have integral or enumeration type.
3266///
3267/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3268/// incomplete class type.
3269///
3270/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3271/// explicit conversion function (because no implicit conversion functions
3272/// were available). This is a recovery mode.
3273///
3274/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3275/// showing which conversion was picked.
3276///
3277/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3278/// conversion function that could convert to integral or enumeration type.
3279///
3280/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3281/// usable conversion function.
3282///
3283/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3284/// function, which may be an extension in this case.
3285///
3286/// \returns The expression, converted to an integral or enumeration type if
3287/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003288ExprResult
John McCallb268a282010-08-23 23:25:46 +00003289Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003290 const PartialDiagnostic &NotIntDiag,
3291 const PartialDiagnostic &IncompleteDiag,
3292 const PartialDiagnostic &ExplicitConvDiag,
3293 const PartialDiagnostic &ExplicitConvNote,
3294 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003295 const PartialDiagnostic &AmbigNote,
3296 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003297 // We can't perform any more checking for type-dependent expressions.
3298 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003299 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003300
3301 // If the expression already has integral or enumeration type, we're golden.
3302 QualType T = From->getType();
3303 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003304 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003305
3306 // FIXME: Check for missing '()' if T is a function type?
3307
3308 // If we don't have a class type in C++, there's no way we can get an
3309 // expression of integral or enumeration type.
3310 const RecordType *RecordTy = T->getAs<RecordType>();
3311 if (!RecordTy || !getLangOptions().CPlusPlus) {
3312 Diag(Loc, NotIntDiag)
3313 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003314 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003315 }
3316
3317 // We must have a complete class type.
3318 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003319 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003320
3321 // Look for a conversion to an integral or enumeration type.
3322 UnresolvedSet<4> ViableConversions;
3323 UnresolvedSet<4> ExplicitConversions;
3324 const UnresolvedSetImpl *Conversions
3325 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3326
3327 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3328 E = Conversions->end();
3329 I != E;
3330 ++I) {
3331 if (CXXConversionDecl *Conversion
3332 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3333 if (Conversion->getConversionType().getNonReferenceType()
3334 ->isIntegralOrEnumerationType()) {
3335 if (Conversion->isExplicit())
3336 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3337 else
3338 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3339 }
3340 }
3341
3342 switch (ViableConversions.size()) {
3343 case 0:
3344 if (ExplicitConversions.size() == 1) {
3345 DeclAccessPair Found = ExplicitConversions[0];
3346 CXXConversionDecl *Conversion
3347 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3348
3349 // The user probably meant to invoke the given explicit
3350 // conversion; use it.
3351 QualType ConvTy
3352 = Conversion->getConversionType().getNonReferenceType();
3353 std::string TypeStr;
3354 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3355
3356 Diag(Loc, ExplicitConvDiag)
3357 << T << ConvTy
3358 << FixItHint::CreateInsertion(From->getLocStart(),
3359 "static_cast<" + TypeStr + ">(")
3360 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3361 ")");
3362 Diag(Conversion->getLocation(), ExplicitConvNote)
3363 << ConvTy->isEnumeralType() << ConvTy;
3364
3365 // If we aren't in a SFINAE context, build a call to the
3366 // explicit conversion function.
3367 if (isSFINAEContext())
3368 return ExprError();
3369
3370 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003371 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003372 }
3373
3374 // We'll complain below about a non-integral condition type.
3375 break;
3376
3377 case 1: {
3378 // Apply this conversion.
3379 DeclAccessPair Found = ViableConversions[0];
3380 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003381
3382 CXXConversionDecl *Conversion
3383 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3384 QualType ConvTy
3385 = Conversion->getConversionType().getNonReferenceType();
3386 if (ConvDiag.getDiagID()) {
3387 if (isSFINAEContext())
3388 return ExprError();
3389
3390 Diag(Loc, ConvDiag)
3391 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3392 }
3393
John McCallb268a282010-08-23 23:25:46 +00003394 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003395 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003396 break;
3397 }
3398
3399 default:
3400 Diag(Loc, AmbigDiag)
3401 << T << From->getSourceRange();
3402 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3403 CXXConversionDecl *Conv
3404 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3405 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3406 Diag(Conv->getLocation(), AmbigNote)
3407 << ConvTy->isEnumeralType() << ConvTy;
3408 }
John McCallb268a282010-08-23 23:25:46 +00003409 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003410 }
3411
Douglas Gregor5823da32010-06-29 23:25:20 +00003412 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003413 Diag(Loc, NotIntDiag)
3414 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003415
John McCallb268a282010-08-23 23:25:46 +00003416 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003417}
3418
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003419/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003420/// candidate functions, using the given function call arguments. If
3421/// @p SuppressUserConversions, then don't allow user-defined
3422/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003423///
3424/// \para PartialOverloading true if we are performing "partial" overloading
3425/// based on an incomplete set of function arguments. This feature is used by
3426/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003427void
3428Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003429 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003430 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003431 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003432 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003433 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003434 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003435 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003436 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003437 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003438 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003439
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003441 if (!isa<CXXConstructorDecl>(Method)) {
3442 // If we get here, it's because we're calling a member function
3443 // that is named without a member access expression (e.g.,
3444 // "this->f") that was either written explicitly or created
3445 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003446 // function, e.g., X::f(). We use an empty type for the implied
3447 // object argument (C++ [over.call.func]p3), and the acting context
3448 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003449 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003450 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003451 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003452 return;
3453 }
3454 // We treat a constructor like a non-member function, since its object
3455 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003456 }
3457
Douglas Gregorff7028a2009-11-13 23:59:09 +00003458 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003459 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003460
Douglas Gregor27381f32009-11-23 12:27:39 +00003461 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003462 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003463
Douglas Gregorffe14e32009-11-14 01:20:54 +00003464 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3465 // C++ [class.copy]p3:
3466 // A member function template is never instantiated to perform the copy
3467 // of a class object to an object of its class type.
3468 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3469 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003470 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003471 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3472 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003473 return;
3474 }
3475
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003476 // Add this candidate
3477 CandidateSet.push_back(OverloadCandidate());
3478 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003479 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003481 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003482 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003483 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003484
3485 unsigned NumArgsInProto = Proto->getNumArgs();
3486
3487 // (C++ 13.3.2p2): A candidate function having fewer than m
3488 // parameters is viable only if it has an ellipsis in its parameter
3489 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003490 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3491 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003492 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003493 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003494 return;
3495 }
3496
3497 // (C++ 13.3.2p2): A candidate function having more than m parameters
3498 // is viable only if the (m+1)st parameter has a default argument
3499 // (8.3.6). For the purposes of overload resolution, the
3500 // parameter list is truncated on the right, so that there are
3501 // exactly m parameters.
3502 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003503 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003504 // Not enough arguments.
3505 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003506 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003507 return;
3508 }
3509
3510 // Determine the implicit conversion sequences for each of the
3511 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003512 Candidate.Conversions.resize(NumArgs);
3513 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3514 if (ArgIdx < NumArgsInProto) {
3515 // (C++ 13.3.2p3): for F to be a viable function, there shall
3516 // exist for each argument an implicit conversion sequence
3517 // (13.3.3.1) that converts that argument to the corresponding
3518 // parameter of F.
3519 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003520 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003521 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003522 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003523 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003524 if (Candidate.Conversions[ArgIdx].isBad()) {
3525 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003526 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003527 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003528 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003529 } else {
3530 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3531 // argument for which there is no corresponding parameter is
3532 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003533 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003534 }
3535 }
3536}
3537
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003538/// \brief Add all of the function declarations in the given function set to
3539/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003540void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003541 Expr **Args, unsigned NumArgs,
3542 OverloadCandidateSet& CandidateSet,
3543 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003544 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003545 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003547 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003548 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003549 cast<CXXMethodDecl>(FD)->getParent(),
3550 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003551 CandidateSet, SuppressUserConversions);
3552 else
John McCalla0296f72010-03-19 07:35:19 +00003553 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003554 SuppressUserConversions);
3555 } else {
John McCalla0296f72010-03-19 07:35:19 +00003556 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003557 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3558 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003559 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003560 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003561 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003562 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003563 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003564 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003565 else
John McCalla0296f72010-03-19 07:35:19 +00003566 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003567 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003568 Args, NumArgs, CandidateSet,
3569 SuppressUserConversions);
3570 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003571 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003572}
3573
John McCallf0f1cf02009-11-17 07:50:12 +00003574/// AddMethodCandidate - Adds a named decl (which is some kind of
3575/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003576void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003577 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003578 Expr **Args, unsigned NumArgs,
3579 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003580 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003581 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003582 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003583
3584 if (isa<UsingShadowDecl>(Decl))
3585 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3586
3587 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3588 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3589 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003590 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3591 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003592 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003593 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003594 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003595 } else {
John McCalla0296f72010-03-19 07:35:19 +00003596 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003597 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003598 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003599 }
3600}
3601
Douglas Gregor436424c2008-11-18 23:14:02 +00003602/// AddMethodCandidate - Adds the given C++ member function to the set
3603/// of candidate functions, using the given function call arguments
3604/// and the object argument (@c Object). For example, in a call
3605/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3606/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3607/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003608/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003609void
John McCalla0296f72010-03-19 07:35:19 +00003610Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003611 CXXRecordDecl *ActingContext, QualType ObjectType,
3612 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003613 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003614 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003615 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003616 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003617 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003618 assert(!isa<CXXConstructorDecl>(Method) &&
3619 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003620
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003621 if (!CandidateSet.isNewCandidate(Method))
3622 return;
3623
Douglas Gregor27381f32009-11-23 12:27:39 +00003624 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003625 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003626
Douglas Gregor436424c2008-11-18 23:14:02 +00003627 // Add this candidate
3628 CandidateSet.push_back(OverloadCandidate());
3629 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003630 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003631 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003632 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003633 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003634
3635 unsigned NumArgsInProto = Proto->getNumArgs();
3636
3637 // (C++ 13.3.2p2): A candidate function having fewer than m
3638 // parameters is viable only if it has an ellipsis in its parameter
3639 // list (8.3.5).
3640 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3641 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003642 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003643 return;
3644 }
3645
3646 // (C++ 13.3.2p2): A candidate function having more than m parameters
3647 // is viable only if the (m+1)st parameter has a default argument
3648 // (8.3.6). For the purposes of overload resolution, the
3649 // parameter list is truncated on the right, so that there are
3650 // exactly m parameters.
3651 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3652 if (NumArgs < MinRequiredArgs) {
3653 // Not enough arguments.
3654 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003655 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003656 return;
3657 }
3658
3659 Candidate.Viable = true;
3660 Candidate.Conversions.resize(NumArgs + 1);
3661
John McCall6e9f8f62009-12-03 04:06:58 +00003662 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003663 // The implicit object argument is ignored.
3664 Candidate.IgnoreObjectArgument = true;
3665 else {
3666 // Determine the implicit conversion sequence for the object
3667 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003668 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003669 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3670 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003671 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003672 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003673 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003674 return;
3675 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003676 }
3677
3678 // Determine the implicit conversion sequences for each of the
3679 // arguments.
3680 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3681 if (ArgIdx < NumArgsInProto) {
3682 // (C++ 13.3.2p3): for F to be a viable function, there shall
3683 // exist for each argument an implicit conversion sequence
3684 // (13.3.3.1) that converts that argument to the corresponding
3685 // parameter of F.
3686 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003687 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003688 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003689 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003690 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003691 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003692 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003693 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003694 break;
3695 }
3696 } else {
3697 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3698 // argument for which there is no corresponding parameter is
3699 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003700 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003701 }
3702 }
3703}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003704
Douglas Gregor97628d62009-08-21 00:16:32 +00003705/// \brief Add a C++ member function template as a candidate to the candidate
3706/// set, using template argument deduction to produce an appropriate member
3707/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003708void
Douglas Gregor97628d62009-08-21 00:16:32 +00003709Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003710 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003711 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003712 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003713 QualType ObjectType,
3714 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003715 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003716 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003717 if (!CandidateSet.isNewCandidate(MethodTmpl))
3718 return;
3719
Douglas Gregor97628d62009-08-21 00:16:32 +00003720 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003721 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003722 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003723 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003724 // candidate functions in the usual way.113) A given name can refer to one
3725 // or more function templates and also to a set of overloaded non-template
3726 // functions. In such a case, the candidate functions generated from each
3727 // function template are combined with the set of non-template candidate
3728 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003729 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003730 FunctionDecl *Specialization = 0;
3731 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003732 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003733 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003734 CandidateSet.push_back(OverloadCandidate());
3735 OverloadCandidate &Candidate = CandidateSet.back();
3736 Candidate.FoundDecl = FoundDecl;
3737 Candidate.Function = MethodTmpl->getTemplatedDecl();
3738 Candidate.Viable = false;
3739 Candidate.FailureKind = ovl_fail_bad_deduction;
3740 Candidate.IsSurrogate = false;
3741 Candidate.IgnoreObjectArgument = false;
3742 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3743 Info);
3744 return;
3745 }
Mike Stump11289f42009-09-09 15:08:12 +00003746
Douglas Gregor97628d62009-08-21 00:16:32 +00003747 // Add the function template specialization produced by template argument
3748 // deduction as a candidate.
3749 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003750 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003751 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003752 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003753 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003754 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003755}
3756
Douglas Gregor05155d82009-08-21 23:19:43 +00003757/// \brief Add a C++ function template specialization as a candidate
3758/// in the candidate set, using template argument deduction to produce
3759/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003760void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003761Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003762 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003763 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003764 Expr **Args, unsigned NumArgs,
3765 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003766 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003767 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3768 return;
3769
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003770 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003771 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003772 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003773 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003774 // candidate functions in the usual way.113) A given name can refer to one
3775 // or more function templates and also to a set of overloaded non-template
3776 // functions. In such a case, the candidate functions generated from each
3777 // function template are combined with the set of non-template candidate
3778 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003779 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003780 FunctionDecl *Specialization = 0;
3781 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003782 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003783 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003784 CandidateSet.push_back(OverloadCandidate());
3785 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003786 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003787 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3788 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003789 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003790 Candidate.IsSurrogate = false;
3791 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003792 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3793 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003794 return;
3795 }
Mike Stump11289f42009-09-09 15:08:12 +00003796
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003797 // Add the function template specialization produced by template argument
3798 // deduction as a candidate.
3799 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003800 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003801 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003802}
Mike Stump11289f42009-09-09 15:08:12 +00003803
Douglas Gregora1f013e2008-11-07 22:36:19 +00003804/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003805/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003806/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003807/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003808/// (which may or may not be the same type as the type that the
3809/// conversion function produces).
3810void
3811Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003812 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003813 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003814 Expr *From, QualType ToType,
3815 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003816 assert(!Conversion->getDescribedFunctionTemplate() &&
3817 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003818 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003819 if (!CandidateSet.isNewCandidate(Conversion))
3820 return;
3821
Douglas Gregor27381f32009-11-23 12:27:39 +00003822 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003823 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003824
Douglas Gregora1f013e2008-11-07 22:36:19 +00003825 // Add this candidate
3826 CandidateSet.push_back(OverloadCandidate());
3827 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003828 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003829 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003830 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003831 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003832 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003833 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003834 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003835 Candidate.Viable = true;
3836 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003837
Douglas Gregor6affc782010-08-19 15:37:02 +00003838 // C++ [over.match.funcs]p4:
3839 // For conversion functions, the function is considered to be a member of
3840 // the class of the implicit implied object argument for the purpose of
3841 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003842 //
3843 // Determine the implicit conversion sequence for the implicit
3844 // object parameter.
3845 QualType ImplicitParamType = From->getType();
3846 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3847 ImplicitParamType = FromPtrType->getPointeeType();
3848 CXXRecordDecl *ConversionContext
3849 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3850
3851 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003852 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003853 ConversionContext);
3854
John McCall0d1da222010-01-12 00:44:57 +00003855 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003856 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003857 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003858 return;
3859 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003860
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003861 // We won't go through a user-define type conversion function to convert a
3862 // derived to base as such conversions are given Conversion Rank. They only
3863 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3864 QualType FromCanon
3865 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3866 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3867 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3868 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003869 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003870 return;
3871 }
3872
Douglas Gregora1f013e2008-11-07 22:36:19 +00003873 // To determine what the conversion from the result of calling the
3874 // conversion function to the type we're eventually trying to
3875 // convert to (ToType), we need to synthesize a call to the
3876 // conversion function and attempt copy initialization from it. This
3877 // makes sure that we get the right semantics with respect to
3878 // lvalues/rvalues and the type. Fortunately, we can allocate this
3879 // call on the stack and we don't need its arguments to be
3880 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003881 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003882 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003883 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3884 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003885 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003886 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003887
Douglas Gregor72ebdab2010-11-13 19:36:57 +00003888 QualType CallResultType
3889 = Conversion->getConversionType().getNonLValueExprType(Context);
3890 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3891 Candidate.Viable = false;
3892 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3893 return;
3894 }
3895
Mike Stump11289f42009-09-09 15:08:12 +00003896 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003897 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3898 // allocator).
Douglas Gregor72ebdab2010-11-13 19:36:57 +00003899 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType,
Douglas Gregore8f080122009-11-17 21:16:22 +00003900 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003901 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003902 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003903 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003904 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003905
John McCall0d1da222010-01-12 00:44:57 +00003906 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003907 case ImplicitConversionSequence::StandardConversion:
3908 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003909
3910 // C++ [over.ics.user]p3:
3911 // If the user-defined conversion is specified by a specialization of a
3912 // conversion function template, the second standard conversion sequence
3913 // shall have exact match rank.
3914 if (Conversion->getPrimaryTemplate() &&
3915 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3916 Candidate.Viable = false;
3917 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3918 }
3919
Douglas Gregora1f013e2008-11-07 22:36:19 +00003920 break;
3921
3922 case ImplicitConversionSequence::BadConversion:
3923 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003924 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003925 break;
3926
3927 default:
Mike Stump11289f42009-09-09 15:08:12 +00003928 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003929 "Can only end up with a standard conversion sequence or failure");
3930 }
3931}
3932
Douglas Gregor05155d82009-08-21 23:19:43 +00003933/// \brief Adds a conversion function template specialization
3934/// candidate to the overload set, using template argument deduction
3935/// to deduce the template arguments of the conversion function
3936/// template from the type that we are converting to (C++
3937/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003938void
Douglas Gregor05155d82009-08-21 23:19:43 +00003939Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003940 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003941 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003942 Expr *From, QualType ToType,
3943 OverloadCandidateSet &CandidateSet) {
3944 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3945 "Only conversion function templates permitted here");
3946
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003947 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3948 return;
3949
John McCallbc077cf2010-02-08 23:07:23 +00003950 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003951 CXXConversionDecl *Specialization = 0;
3952 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003953 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003954 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003955 CandidateSet.push_back(OverloadCandidate());
3956 OverloadCandidate &Candidate = CandidateSet.back();
3957 Candidate.FoundDecl = FoundDecl;
3958 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3959 Candidate.Viable = false;
3960 Candidate.FailureKind = ovl_fail_bad_deduction;
3961 Candidate.IsSurrogate = false;
3962 Candidate.IgnoreObjectArgument = false;
3963 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3964 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003965 return;
3966 }
Mike Stump11289f42009-09-09 15:08:12 +00003967
Douglas Gregor05155d82009-08-21 23:19:43 +00003968 // Add the conversion function template specialization produced by
3969 // template argument deduction as a candidate.
3970 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003971 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003972 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003973}
3974
Douglas Gregorab7897a2008-11-19 22:57:39 +00003975/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3976/// converts the given @c Object to a function pointer via the
3977/// conversion function @c Conversion, and then attempts to call it
3978/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3979/// the type of function that we'll eventually be calling.
3980void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003981 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003982 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003983 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003984 QualType ObjectType,
3985 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003986 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003987 if (!CandidateSet.isNewCandidate(Conversion))
3988 return;
3989
Douglas Gregor27381f32009-11-23 12:27:39 +00003990 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003991 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003992
Douglas Gregorab7897a2008-11-19 22:57:39 +00003993 CandidateSet.push_back(OverloadCandidate());
3994 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003995 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003996 Candidate.Function = 0;
3997 Candidate.Surrogate = Conversion;
3998 Candidate.Viable = true;
3999 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004000 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004001 Candidate.Conversions.resize(NumArgs + 1);
4002
4003 // Determine the implicit conversion sequence for the implicit
4004 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004005 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004006 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4007 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004008 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004009 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004010 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004011 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004012 return;
4013 }
4014
4015 // The first conversion is actually a user-defined conversion whose
4016 // first conversion is ObjectInit's standard conversion (which is
4017 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004018 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004019 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004020 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004021 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00004022 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004023 = Candidate.Conversions[0].UserDefined.Before;
4024 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4025
Mike Stump11289f42009-09-09 15:08:12 +00004026 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004027 unsigned NumArgsInProto = Proto->getNumArgs();
4028
4029 // (C++ 13.3.2p2): A candidate function having fewer than m
4030 // parameters is viable only if it has an ellipsis in its parameter
4031 // list (8.3.5).
4032 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4033 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004034 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004035 return;
4036 }
4037
4038 // Function types don't have any default arguments, so just check if
4039 // we have enough arguments.
4040 if (NumArgs < NumArgsInProto) {
4041 // Not enough arguments.
4042 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004043 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004044 return;
4045 }
4046
4047 // Determine the implicit conversion sequences for each of the
4048 // arguments.
4049 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4050 if (ArgIdx < NumArgsInProto) {
4051 // (C++ 13.3.2p3): for F to be a viable function, there shall
4052 // exist for each argument an implicit conversion sequence
4053 // (13.3.3.1) that converts that argument to the corresponding
4054 // parameter of F.
4055 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004056 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004057 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004058 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004059 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004060 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004061 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004062 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004063 break;
4064 }
4065 } else {
4066 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4067 // argument for which there is no corresponding parameter is
4068 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004069 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004070 }
4071 }
4072}
4073
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004074/// \brief Add overload candidates for overloaded operators that are
4075/// member functions.
4076///
4077/// Add the overloaded operator candidates that are member functions
4078/// for the operator Op that was used in an operator expression such
4079/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4080/// CandidateSet will store the added overload candidates. (C++
4081/// [over.match.oper]).
4082void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4083 SourceLocation OpLoc,
4084 Expr **Args, unsigned NumArgs,
4085 OverloadCandidateSet& CandidateSet,
4086 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004087 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4088
4089 // C++ [over.match.oper]p3:
4090 // For a unary operator @ with an operand of a type whose
4091 // cv-unqualified version is T1, and for a binary operator @ with
4092 // a left operand of a type whose cv-unqualified version is T1 and
4093 // a right operand of a type whose cv-unqualified version is T2,
4094 // three sets of candidate functions, designated member
4095 // candidates, non-member candidates and built-in candidates, are
4096 // constructed as follows:
4097 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004098
4099 // -- If T1 is a class type, the set of member candidates is the
4100 // result of the qualified lookup of T1::operator@
4101 // (13.3.1.1.1); otherwise, the set of member candidates is
4102 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004103 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004104 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004105 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004106 return;
Mike Stump11289f42009-09-09 15:08:12 +00004107
John McCall27b18f82009-11-17 02:14:36 +00004108 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4109 LookupQualifiedName(Operators, T1Rec->getDecl());
4110 Operators.suppressDiagnostics();
4111
Mike Stump11289f42009-09-09 15:08:12 +00004112 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004113 OperEnd = Operators.end();
4114 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004115 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004116 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004117 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004118 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004119 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004120}
4121
Douglas Gregora11693b2008-11-12 17:17:38 +00004122/// AddBuiltinCandidate - Add a candidate for a built-in
4123/// operator. ResultTy and ParamTys are the result and parameter types
4124/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004125/// arguments being passed to the candidate. IsAssignmentOperator
4126/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004127/// operator. NumContextualBoolArguments is the number of arguments
4128/// (at the beginning of the argument list) that will be contextually
4129/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004130void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004131 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004132 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004133 bool IsAssignmentOperator,
4134 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004135 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004136 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004137
Douglas Gregora11693b2008-11-12 17:17:38 +00004138 // Add this candidate
4139 CandidateSet.push_back(OverloadCandidate());
4140 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004141 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004142 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004143 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004144 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004145 Candidate.BuiltinTypes.ResultTy = ResultTy;
4146 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4147 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4148
4149 // Determine the implicit conversion sequences for each of the
4150 // arguments.
4151 Candidate.Viable = true;
4152 Candidate.Conversions.resize(NumArgs);
4153 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004154 // C++ [over.match.oper]p4:
4155 // For the built-in assignment operators, conversions of the
4156 // left operand are restricted as follows:
4157 // -- no temporaries are introduced to hold the left operand, and
4158 // -- no user-defined conversions are applied to the left
4159 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004160 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004161 //
4162 // We block these conversions by turning off user-defined
4163 // conversions, since that is the only way that initialization of
4164 // a reference to a non-class type can occur from something that
4165 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004166 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004167 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004168 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004169 Candidate.Conversions[ArgIdx]
4170 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004171 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004172 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004173 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004174 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004175 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004176 }
John McCall0d1da222010-01-12 00:44:57 +00004177 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004178 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004179 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004180 break;
4181 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004182 }
4183}
4184
4185/// BuiltinCandidateTypeSet - A set of types that will be used for the
4186/// candidate operator functions for built-in operators (C++
4187/// [over.built]). The types are separated into pointer types and
4188/// enumeration types.
4189class BuiltinCandidateTypeSet {
4190 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004191 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004192
4193 /// PointerTypes - The set of pointer types that will be used in the
4194 /// built-in candidates.
4195 TypeSet PointerTypes;
4196
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004197 /// MemberPointerTypes - The set of member pointer types that will be
4198 /// used in the built-in candidates.
4199 TypeSet MemberPointerTypes;
4200
Douglas Gregora11693b2008-11-12 17:17:38 +00004201 /// EnumerationTypes - The set of enumeration types that will be
4202 /// used in the built-in candidates.
4203 TypeSet EnumerationTypes;
4204
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004205 /// \brief The set of vector types that will be used in the built-in
4206 /// candidates.
4207 TypeSet VectorTypes;
4208
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004209 /// Sema - The semantic analysis instance where we are building the
4210 /// candidate type set.
4211 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004212
Douglas Gregora11693b2008-11-12 17:17:38 +00004213 /// Context - The AST context in which we will build the type sets.
4214 ASTContext &Context;
4215
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004216 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4217 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004218 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004219
4220public:
4221 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004222 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004223
Mike Stump11289f42009-09-09 15:08:12 +00004224 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004225 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004226
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004227 void AddTypesConvertedFrom(QualType Ty,
4228 SourceLocation Loc,
4229 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004230 bool AllowExplicitConversions,
4231 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004232
4233 /// pointer_begin - First pointer type found;
4234 iterator pointer_begin() { return PointerTypes.begin(); }
4235
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004236 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004237 iterator pointer_end() { return PointerTypes.end(); }
4238
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004239 /// member_pointer_begin - First member pointer type found;
4240 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4241
4242 /// member_pointer_end - Past the last member pointer type found;
4243 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4244
Douglas Gregora11693b2008-11-12 17:17:38 +00004245 /// enumeration_begin - First enumeration type found;
4246 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4247
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004248 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004249 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004250
4251 iterator vector_begin() { return VectorTypes.begin(); }
4252 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004253};
4254
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004255/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004256/// the set of pointer types along with any more-qualified variants of
4257/// that type. For example, if @p Ty is "int const *", this routine
4258/// will add "int const *", "int const volatile *", "int const
4259/// restrict *", and "int const volatile restrict *" to the set of
4260/// pointer types. Returns true if the add of @p Ty itself succeeded,
4261/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004262///
4263/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004264bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004265BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4266 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004267
Douglas Gregora11693b2008-11-12 17:17:38 +00004268 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004269 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004270 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004271
4272 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004273 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004274 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004275 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004276 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004277 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004278 buildObjCPtr = true;
4279 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004280 else
4281 assert(false && "type was not a pointer type!");
4282 }
4283 else
4284 PointeeTy = PointerTy->getPointeeType();
4285
Sebastian Redl4990a632009-11-18 20:39:26 +00004286 // Don't add qualified variants of arrays. For one, they're not allowed
4287 // (the qualifier would sink to the element type), and for another, the
4288 // only overload situation where it matters is subscript or pointer +- int,
4289 // and those shouldn't have qualifier variants anyway.
4290 if (PointeeTy->isArrayType())
4291 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004292 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004293 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004294 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004295 bool hasVolatile = VisibleQuals.hasVolatile();
4296 bool hasRestrict = VisibleQuals.hasRestrict();
4297
John McCall8ccfcb52009-09-24 19:53:00 +00004298 // Iterate through all strict supersets of BaseCVR.
4299 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4300 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004301 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4302 // in the types.
4303 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4304 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004305 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004306 if (!buildObjCPtr)
4307 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4308 else
4309 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004310 }
4311
4312 return true;
4313}
4314
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004315/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4316/// to the set of pointer types along with any more-qualified variants of
4317/// that type. For example, if @p Ty is "int const *", this routine
4318/// will add "int const *", "int const volatile *", "int const
4319/// restrict *", and "int const volatile restrict *" to the set of
4320/// pointer types. Returns true if the add of @p Ty itself succeeded,
4321/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004322///
4323/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004324bool
4325BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4326 QualType Ty) {
4327 // Insert this type.
4328 if (!MemberPointerTypes.insert(Ty))
4329 return false;
4330
John McCall8ccfcb52009-09-24 19:53:00 +00004331 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4332 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004333
John McCall8ccfcb52009-09-24 19:53:00 +00004334 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004335 // Don't add qualified variants of arrays. For one, they're not allowed
4336 // (the qualifier would sink to the element type), and for another, the
4337 // only overload situation where it matters is subscript or pointer +- int,
4338 // and those shouldn't have qualifier variants anyway.
4339 if (PointeeTy->isArrayType())
4340 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004341 const Type *ClassTy = PointerTy->getClass();
4342
4343 // Iterate through all strict supersets of the pointee type's CVR
4344 // qualifiers.
4345 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4346 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4347 if ((CVR | BaseCVR) != CVR) continue;
4348
4349 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4350 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004351 }
4352
4353 return true;
4354}
4355
Douglas Gregora11693b2008-11-12 17:17:38 +00004356/// AddTypesConvertedFrom - Add each of the types to which the type @p
4357/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004358/// primarily interested in pointer types and enumeration types. We also
4359/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004360/// AllowUserConversions is true if we should look at the conversion
4361/// functions of a class type, and AllowExplicitConversions if we
4362/// should also include the explicit conversion functions of a class
4363/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004364void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004365BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004366 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004367 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004368 bool AllowExplicitConversions,
4369 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004370 // Only deal with canonical types.
4371 Ty = Context.getCanonicalType(Ty);
4372
4373 // Look through reference types; they aren't part of the type of an
4374 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004375 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004376 Ty = RefTy->getPointeeType();
4377
4378 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004379 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004380
Sebastian Redl65ae2002009-11-05 16:36:20 +00004381 // If we're dealing with an array type, decay to the pointer.
4382 if (Ty->isArrayType())
4383 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004384 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4385 PointerTypes.insert(Ty);
4386 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004387 // Insert our type, and its more-qualified variants, into the set
4388 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004389 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004390 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004391 } else if (Ty->isMemberPointerType()) {
4392 // Member pointers are far easier, since the pointee can't be converted.
4393 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4394 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004395 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004396 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004397 } else if (Ty->isVectorType()) {
4398 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004399 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004400 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004401 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004402 // No conversion functions in incomplete types.
4403 return;
4404 }
Mike Stump11289f42009-09-09 15:08:12 +00004405
Douglas Gregora11693b2008-11-12 17:17:38 +00004406 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004407 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004408 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004409 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004410 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004411 NamedDecl *D = I.getDecl();
4412 if (isa<UsingShadowDecl>(D))
4413 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004414
Mike Stump11289f42009-09-09 15:08:12 +00004415 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004416 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004417 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004418 continue;
4419
John McCallda4458e2010-03-31 01:36:47 +00004420 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004421 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004422 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004423 VisibleQuals);
4424 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004425 }
4426 }
4427 }
4428}
4429
Douglas Gregor84605ae2009-08-24 13:43:27 +00004430/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4431/// the volatile- and non-volatile-qualified assignment operators for the
4432/// given type to the candidate set.
4433static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4434 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004435 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004436 unsigned NumArgs,
4437 OverloadCandidateSet &CandidateSet) {
4438 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004439
Douglas Gregor84605ae2009-08-24 13:43:27 +00004440 // T& operator=(T&, T)
4441 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4442 ParamTypes[1] = T;
4443 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4444 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004445
Douglas Gregor84605ae2009-08-24 13:43:27 +00004446 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4447 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004448 ParamTypes[0]
4449 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004450 ParamTypes[1] = T;
4451 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004452 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004453 }
4454}
Mike Stump11289f42009-09-09 15:08:12 +00004455
Sebastian Redl1054fae2009-10-25 17:03:50 +00004456/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4457/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004458static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4459 Qualifiers VRQuals;
4460 const RecordType *TyRec;
4461 if (const MemberPointerType *RHSMPType =
4462 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004463 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004464 else
4465 TyRec = ArgExpr->getType()->getAs<RecordType>();
4466 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004467 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004468 VRQuals.addVolatile();
4469 VRQuals.addRestrict();
4470 return VRQuals;
4471 }
4472
4473 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004474 if (!ClassDecl->hasDefinition())
4475 return VRQuals;
4476
John McCallad371252010-01-20 00:46:10 +00004477 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004478 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004479
John McCallad371252010-01-20 00:46:10 +00004480 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004481 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004482 NamedDecl *D = I.getDecl();
4483 if (isa<UsingShadowDecl>(D))
4484 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4485 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004486 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4487 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4488 CanTy = ResTypeRef->getPointeeType();
4489 // Need to go down the pointer/mempointer chain and add qualifiers
4490 // as see them.
4491 bool done = false;
4492 while (!done) {
4493 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4494 CanTy = ResTypePtr->getPointeeType();
4495 else if (const MemberPointerType *ResTypeMPtr =
4496 CanTy->getAs<MemberPointerType>())
4497 CanTy = ResTypeMPtr->getPointeeType();
4498 else
4499 done = true;
4500 if (CanTy.isVolatileQualified())
4501 VRQuals.addVolatile();
4502 if (CanTy.isRestrictQualified())
4503 VRQuals.addRestrict();
4504 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4505 return VRQuals;
4506 }
4507 }
4508 }
4509 return VRQuals;
4510}
John McCall52872982010-11-13 05:51:15 +00004511
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004512
Douglas Gregord08452f2008-11-19 15:42:04 +00004513/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4514/// operator overloads to the candidate set (C++ [over.built]), based
4515/// on the operator @p Op and the arguments given. For example, if the
4516/// operator is a binary '+', this routine might add "int
4517/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004518void
Mike Stump11289f42009-09-09 15:08:12 +00004519Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004520 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004521 Expr **Args, unsigned NumArgs,
4522 OverloadCandidateSet& CandidateSet) {
John McCall52872982010-11-13 05:51:15 +00004523 // Information about arithmetic types useful to builtin-type
4524 // calculations.
4525
4526 // The "promoted arithmetic types" are the arithmetic
4527 // types are that preserved by promotion (C++ [over.built]p2).
4528
4529 static const unsigned FirstIntegralType = 3;
4530 static const unsigned LastIntegralType = 18;
4531 static const unsigned FirstPromotedIntegralType = 3,
4532 LastPromotedIntegralType = 9;
4533 static const unsigned FirstPromotedArithmeticType = 0,
4534 LastPromotedArithmeticType = 9;
4535 static const unsigned NumArithmeticTypes = 18;
4536
John McCall988ffb72010-11-13 02:01:09 +00004537 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall52872982010-11-13 05:51:15 +00004538 // Start of promoted types.
4539 &ASTContext::FloatTy,
4540 &ASTContext::DoubleTy,
4541 &ASTContext::LongDoubleTy,
4542
4543 // Start of integral types.
4544 &ASTContext::IntTy,
4545 &ASTContext::LongTy,
4546 &ASTContext::LongLongTy,
4547 &ASTContext::UnsignedIntTy,
4548 &ASTContext::UnsignedLongTy,
4549 &ASTContext::UnsignedLongLongTy,
4550 // End of promoted types.
4551
John McCall988ffb72010-11-13 02:01:09 +00004552 &ASTContext::BoolTy,
4553 &ASTContext::CharTy,
4554 &ASTContext::WCharTy,
4555 &ASTContext::Char16Ty,
4556 &ASTContext::Char32Ty,
4557 &ASTContext::SignedCharTy,
4558 &ASTContext::ShortTy,
4559 &ASTContext::UnsignedCharTy,
John McCall52872982010-11-13 05:51:15 +00004560 &ASTContext::UnsignedShortTy
4561 // End of integral types.
Douglas Gregora11693b2008-11-12 17:17:38 +00004562 };
John McCall52872982010-11-13 05:51:15 +00004563 // FIXME: What about complex?
John McCall988ffb72010-11-13 02:01:09 +00004564 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004565 "Invalid first promoted integral type");
4566 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall988ffb72010-11-13 02:01:09 +00004567 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004568 "Invalid last promoted integral type");
John McCall52872982010-11-13 05:51:15 +00004569 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004570 "Invalid first promoted arithmetic type");
4571 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall52872982010-11-13 05:51:15 +00004572 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004573 "Invalid last promoted arithmetic type");
John McCall52872982010-11-13 05:51:15 +00004574
4575 // Accelerator table for performing the usual arithmetic conversions.
4576 // The rules are basically:
4577 // - if either is floating-point, use the wider floating-point
4578 // - if same signedness, use the higher rank
4579 // - if same size, use unsigned of the higher rank
4580 // - use the larger type
4581 // These rules, together with the axiom that higher ranks are
4582 // never smaller, are sufficient to precompute all of these results
4583 // *except* when dealing with signed types of higher rank.
4584 // (we could precompute SLL x UI for all known platforms, but it's
4585 // better not to make any assumptions).
4586 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4587 static PromT UsualArithmeticConversionsTypes
4588 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4589 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4590 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4591 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4592 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4593 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4594 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4595 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4596 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4597 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4598 };
4599 struct UsualArithmeticConversionsType {
4600 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4601 assert(L < LastPromotedArithmeticType);
4602 assert(R < LastPromotedArithmeticType);
4603 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4604
4605 // Fast path: the table gives us a concrete answer.
4606 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4607
4608 // Slow path: we need to compare widths.
4609 // An invariant is that the signed type has higher rank.
4610 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4611 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4612
4613 // If they're different widths, use the signed type.
4614 if (LW > RW) return LT;
4615 else if (LW > RW) return RT;
4616
4617 // Otherwise, use the unsigned type of the signed type's rank.
4618 if (L == SL || R == SL) return C.UnsignedLongTy;
4619 assert(L == SLL || R == SLL);
4620 return C.UnsignedLongLongTy;
4621 }
4622 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004623
Douglas Gregora11693b2008-11-12 17:17:38 +00004624 // Find all of the types that the arguments can convert to, but only
4625 // if the operator we're looking at has built-in operator candidates
4626 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004627 Qualifiers VisibleTypeConversionsQuals;
4628 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004629 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4630 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4631
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004632 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4633 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4634 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4635 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4636 OpLoc,
4637 true,
4638 (Op == OO_Exclaim ||
4639 Op == OO_AmpAmp ||
4640 Op == OO_PipePipe),
4641 VisibleTypeConversionsQuals);
4642 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004643
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004644 // C++ [over.built]p1:
4645 // If there is a user-written candidate with the same name and parameter
4646 // types as a built-in candidate operator function, the built-in operator
4647 // function is hidden and is not included in the set of candidate functions.
4648 //
4649 // The text is actually in a note, but if we don't implement it then we end
4650 // up with ambiguities when the user provides an overloaded operator for
4651 // an enumeration type. Note that only enumeration types have this problem,
4652 // so we track which enumeration types we've seen operators for.
4653 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4654 UserDefinedBinaryOperators;
4655
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004656 /// Set of (canonical) types that we've already handled.
4657 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4658
4659 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4660 if (CandidateTypes[ArgIdx].enumeration_begin()
4661 != CandidateTypes[ArgIdx].enumeration_end()) {
4662 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4663 CEnd = CandidateSet.end();
4664 C != CEnd; ++C) {
4665 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4666 continue;
4667
4668 // Check if the first parameter is of enumeration type.
4669 QualType FirstParamType
4670 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4671 if (!FirstParamType->isEnumeralType())
4672 continue;
4673
4674 // Check if the second parameter is of enumeration type.
4675 QualType SecondParamType
4676 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4677 if (!SecondParamType->isEnumeralType())
4678 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004679
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004680 // Add this operator to the set of known user-defined operators.
4681 UserDefinedBinaryOperators.insert(
4682 std::make_pair(Context.getCanonicalType(FirstParamType),
4683 Context.getCanonicalType(SecondParamType)));
4684 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004685 }
4686 }
4687
Douglas Gregora11693b2008-11-12 17:17:38 +00004688 bool isComparison = false;
4689 switch (Op) {
4690 case OO_None:
4691 case NUM_OVERLOADED_OPERATORS:
4692 assert(false && "Expected an overloaded operator");
4693 break;
4694
Douglas Gregord08452f2008-11-19 15:42:04 +00004695 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004696 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004697 goto UnaryStar;
4698 else
4699 goto BinaryStar;
4700 break;
4701
4702 case OO_Plus: // '+' is either unary or binary
4703 if (NumArgs == 1)
4704 goto UnaryPlus;
4705 else
4706 goto BinaryPlus;
4707 break;
4708
4709 case OO_Minus: // '-' is either unary or binary
4710 if (NumArgs == 1)
4711 goto UnaryMinus;
4712 else
4713 goto BinaryMinus;
4714 break;
4715
4716 case OO_Amp: // '&' is either unary or binary
4717 if (NumArgs == 1)
4718 goto UnaryAmp;
4719 else
4720 goto BinaryAmp;
4721
4722 case OO_PlusPlus:
4723 case OO_MinusMinus:
4724 // C++ [over.built]p3:
4725 //
4726 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4727 // is either volatile or empty, there exist candidate operator
4728 // functions of the form
4729 //
4730 // VQ T& operator++(VQ T&);
4731 // T operator++(VQ T&, int);
4732 //
4733 // C++ [over.built]p4:
4734 //
4735 // For every pair (T, VQ), where T is an arithmetic type other
4736 // than bool, and VQ is either volatile or empty, there exist
4737 // candidate operator functions of the form
4738 //
4739 // VQ T& operator--(VQ T&);
4740 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004741 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004742 Arith < NumArithmeticTypes; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004743 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004744 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004745 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004746
4747 // Non-volatile version.
4748 if (NumArgs == 1)
4749 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4750 else
4751 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004752 // heuristic to reduce number of builtin candidates in the set.
4753 // Add volatile version only if there are conversions to a volatile type.
4754 if (VisibleTypeConversionsQuals.hasVolatile()) {
4755 // Volatile version
4756 ParamTypes[0]
4757 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4758 if (NumArgs == 1)
4759 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4760 else
4761 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4762 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004763 }
4764
4765 // C++ [over.built]p5:
4766 //
4767 // For every pair (T, VQ), where T is a cv-qualified or
4768 // cv-unqualified object type, and VQ is either volatile or
4769 // empty, there exist candidate operator functions of the form
4770 //
4771 // T*VQ& operator++(T*VQ&);
4772 // T*VQ& operator--(T*VQ&);
4773 // T* operator++(T*VQ&, int);
4774 // T* operator--(T*VQ&, int);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004775 for (BuiltinCandidateTypeSet::iterator
4776 Ptr = CandidateTypes[0].pointer_begin(),
4777 PtrEnd = CandidateTypes[0].pointer_end();
4778 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004779 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004780 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004781 continue;
4782
Mike Stump11289f42009-09-09 15:08:12 +00004783 QualType ParamTypes[2] = {
4784 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004785 };
Mike Stump11289f42009-09-09 15:08:12 +00004786
Douglas Gregord08452f2008-11-19 15:42:04 +00004787 // Without volatile
4788 if (NumArgs == 1)
4789 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4790 else
4791 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4792
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004793 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4794 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004795 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004796 ParamTypes[0]
4797 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004798 if (NumArgs == 1)
4799 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4800 else
4801 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4802 }
4803 }
4804 break;
4805
4806 UnaryStar:
4807 // C++ [over.built]p6:
4808 // For every cv-qualified or cv-unqualified object type T, there
4809 // exist candidate operator functions of the form
4810 //
4811 // T& operator*(T*);
4812 //
4813 // C++ [over.built]p7:
4814 // For every function type T, there exist candidate operator
4815 // functions of the form
4816 // T& operator*(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004817 for (BuiltinCandidateTypeSet::iterator
4818 Ptr = CandidateTypes[0].pointer_begin(),
4819 PtrEnd = CandidateTypes[0].pointer_end();
4820 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004821 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004822 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004823 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004824 &ParamTy, Args, 1, CandidateSet);
4825 }
4826 break;
4827
4828 UnaryPlus:
4829 // C++ [over.built]p8:
4830 // For every type T, there exist candidate operator functions of
4831 // the form
4832 //
4833 // T* operator+(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004834 for (BuiltinCandidateTypeSet::iterator
4835 Ptr = CandidateTypes[0].pointer_begin(),
4836 PtrEnd = CandidateTypes[0].pointer_end();
4837 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004838 QualType ParamTy = *Ptr;
4839 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4840 }
Mike Stump11289f42009-09-09 15:08:12 +00004841
Douglas Gregord08452f2008-11-19 15:42:04 +00004842 // Fall through
4843
4844 UnaryMinus:
4845 // C++ [over.built]p9:
4846 // For every promoted arithmetic type T, there exist candidate
4847 // operator functions of the form
4848 //
4849 // T operator+(T);
4850 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004851 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004852 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004853 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregord08452f2008-11-19 15:42:04 +00004854 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4855 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004856
4857 // Extension: We also add these operators for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004858 for (BuiltinCandidateTypeSet::iterator
4859 Vec = CandidateTypes[0].vector_begin(),
4860 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004861 Vec != VecEnd; ++Vec) {
4862 QualType VecTy = *Vec;
4863 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4864 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004865 break;
4866
4867 case OO_Tilde:
4868 // C++ [over.built]p10:
4869 // For every promoted integral type T, there exist candidate
4870 // operator functions of the form
4871 //
4872 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004873 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004874 Int < LastPromotedIntegralType; ++Int) {
John McCall988ffb72010-11-13 02:01:09 +00004875 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregord08452f2008-11-19 15:42:04 +00004876 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4877 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004878
4879 // Extension: We also add this operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004880 for (BuiltinCandidateTypeSet::iterator
4881 Vec = CandidateTypes[0].vector_begin(),
4882 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004883 Vec != VecEnd; ++Vec) {
4884 QualType VecTy = *Vec;
4885 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4886 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004887 break;
4888
Douglas Gregora11693b2008-11-12 17:17:38 +00004889 case OO_New:
4890 case OO_Delete:
4891 case OO_Array_New:
4892 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004893 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004894 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004895 break;
4896
4897 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004898 UnaryAmp:
4899 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004900 // C++ [over.match.oper]p3:
4901 // -- For the operator ',', the unary operator '&', or the
4902 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004903 break;
4904
Douglas Gregor84605ae2009-08-24 13:43:27 +00004905 case OO_EqualEqual:
4906 case OO_ExclaimEqual:
4907 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004908 // For every pointer to member type T, there exist candidate operator
4909 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004910 //
4911 // bool operator==(T,T);
4912 // bool operator!=(T,T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004913 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4914 for (BuiltinCandidateTypeSet::iterator
4915 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4916 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4917 MemPtr != MemPtrEnd;
4918 ++MemPtr) {
4919 // Don't add the same builtin candidate twice.
4920 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4921 continue;
4922
4923 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4924 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4925 }
Douglas Gregor84605ae2009-08-24 13:43:27 +00004926 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004927 AddedTypes.clear();
4928
Douglas Gregor84605ae2009-08-24 13:43:27 +00004929 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004930
Douglas Gregora11693b2008-11-12 17:17:38 +00004931 case OO_Less:
4932 case OO_Greater:
4933 case OO_LessEqual:
4934 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004935 // C++ [over.built]p15:
4936 //
4937 // For every pointer or enumeration type T, there exist
4938 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004939 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004940 // bool operator<(T, T);
4941 // bool operator>(T, T);
4942 // bool operator<=(T, T);
4943 // bool operator>=(T, T);
4944 // bool operator==(T, T);
4945 // bool operator!=(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004946 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4947 for (BuiltinCandidateTypeSet::iterator
4948 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4949 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4950 Ptr != PtrEnd; ++Ptr) {
4951 // Don't add the same builtin candidate twice.
4952 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4953 continue;
4954
4955 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004956 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004957 }
4958 for (BuiltinCandidateTypeSet::iterator
4959 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4960 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4961 Enum != EnumEnd; ++Enum) {
4962 // Don't add the same builtin candidate twice.
4963 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4964 continue;
4965
4966 QualType ParamTypes[2] = { *Enum, *Enum };
4967 CanQualType CanonType = Context.getCanonicalType(*Enum);
4968 if (!UserDefinedBinaryOperators.count(
4969 std::make_pair(CanonType, CanonType)))
4970 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4971 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004972 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004973 AddedTypes.clear();
4974
Douglas Gregora11693b2008-11-12 17:17:38 +00004975 // Fall through.
4976 isComparison = true;
4977
Douglas Gregord08452f2008-11-19 15:42:04 +00004978 BinaryPlus:
4979 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004980 if (!isComparison) {
4981 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4982
4983 // C++ [over.built]p13:
4984 //
4985 // For every cv-qualified or cv-unqualified object type T
4986 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004987 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004988 // T* operator+(T*, ptrdiff_t);
4989 // T& operator[](T*, ptrdiff_t); [BELOW]
4990 // T* operator-(T*, ptrdiff_t);
4991 // T* operator+(ptrdiff_t, T*);
4992 // T& operator[](ptrdiff_t, T*); [BELOW]
4993 //
4994 // C++ [over.built]p14:
4995 //
4996 // For every T, where T is a pointer to object type, there
4997 // exist candidate operator functions of the form
4998 //
4999 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005000 for (BuiltinCandidateTypeSet::iterator
5001 Ptr = CandidateTypes[0].pointer_begin(),
5002 PtrEnd = CandidateTypes[0].pointer_end();
5003 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005004 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
5005
5006 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5007 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5008
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005009 if (Op == OO_Minus) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005010 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005011 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5012 continue;
5013
Douglas Gregora11693b2008-11-12 17:17:38 +00005014 ParamTypes[1] = *Ptr;
5015 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5016 Args, 2, CandidateSet);
5017 }
5018 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005019
5020 for (BuiltinCandidateTypeSet::iterator
5021 Ptr = CandidateTypes[1].pointer_begin(),
5022 PtrEnd = CandidateTypes[1].pointer_end();
5023 Ptr != PtrEnd; ++Ptr) {
5024 if (Op == OO_Plus) {
5025 // T* operator+(ptrdiff_t, T*);
5026 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5027 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5028 } else {
5029 // ptrdiff_t operator-(T, T);
5030 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5031 continue;
5032
5033 QualType ParamTypes[2] = { *Ptr, *Ptr };
5034 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5035 Args, 2, CandidateSet);
5036 }
5037 }
5038
5039 AddedTypes.clear();
Douglas Gregora11693b2008-11-12 17:17:38 +00005040 }
5041 // Fall through
5042
Douglas Gregora11693b2008-11-12 17:17:38 +00005043 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00005044 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00005045 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00005046 // C++ [over.built]p12:
5047 //
5048 // For every pair of promoted arithmetic types L and R, there
5049 // exist candidate operator functions of the form
5050 //
5051 // LR operator*(L, R);
5052 // LR operator/(L, R);
5053 // LR operator+(L, R);
5054 // LR operator-(L, R);
5055 // bool operator<(L, R);
5056 // bool operator>(L, R);
5057 // bool operator<=(L, R);
5058 // bool operator>=(L, R);
5059 // bool operator==(L, R);
5060 // bool operator!=(L, R);
5061 //
5062 // where LR is the result of the usual arithmetic conversions
5063 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005064 //
5065 // C++ [over.built]p24:
5066 //
5067 // For every pair of promoted arithmetic types L and R, there exist
5068 // candidate operator functions of the form
5069 //
5070 // LR operator?(bool, L, R);
5071 //
5072 // where LR is the result of the usual arithmetic conversions
5073 // between types L and R.
5074 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005075 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005076 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005077 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005078 Right < LastPromotedArithmeticType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005079 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5080 Context.*ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005081 QualType Result
5082 = isComparison
5083 ? Context.BoolTy
John McCall52872982010-11-13 05:51:15 +00005084 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005085 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5086 }
5087 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005088
5089 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5090 // conditional operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005091 for (BuiltinCandidateTypeSet::iterator
5092 Vec1 = CandidateTypes[0].vector_begin(),
5093 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005094 Vec1 != Vec1End; ++Vec1)
5095 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005096 Vec2 = CandidateTypes[1].vector_begin(),
5097 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005098 Vec2 != Vec2End; ++Vec2) {
5099 QualType LandR[2] = { *Vec1, *Vec2 };
5100 QualType Result;
5101 if (isComparison)
5102 Result = Context.BoolTy;
5103 else {
5104 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5105 Result = *Vec1;
5106 else
5107 Result = *Vec2;
5108 }
5109
5110 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5111 }
5112
Douglas Gregora11693b2008-11-12 17:17:38 +00005113 break;
5114
5115 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005116 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005117 case OO_Caret:
5118 case OO_Pipe:
5119 case OO_LessLess:
5120 case OO_GreaterGreater:
5121 // C++ [over.built]p17:
5122 //
5123 // For every pair of promoted integral types L and R, there
5124 // exist candidate operator functions of the form
5125 //
5126 // LR operator%(L, R);
5127 // LR operator&(L, R);
5128 // LR operator^(L, R);
5129 // LR operator|(L, R);
5130 // L operator<<(L, R);
5131 // L operator>>(L, R);
5132 //
5133 // where LR is the result of the usual arithmetic conversions
5134 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00005135 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005136 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005137 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005138 Right < LastPromotedIntegralType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005139 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5140 Context.*ArithmeticTypes[Right] };
Douglas Gregora11693b2008-11-12 17:17:38 +00005141 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5142 ? LandR[0]
John McCall52872982010-11-13 05:51:15 +00005143 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005144 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5145 }
5146 }
5147 break;
5148
5149 case OO_Equal:
5150 // C++ [over.built]p20:
5151 //
5152 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00005153 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00005154 // empty, there exist candidate operator functions of the form
5155 //
5156 // VQ T& operator=(VQ T&, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005157 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5158 for (BuiltinCandidateTypeSet::iterator
5159 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5160 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5161 Enum != EnumEnd; ++Enum) {
5162 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5163 continue;
5164
5165 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5166 CandidateSet);
5167 }
5168
5169 for (BuiltinCandidateTypeSet::iterator
5170 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5171 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5172 MemPtr != MemPtrEnd; ++MemPtr) {
5173 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5174 continue;
5175
5176 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5177 CandidateSet);
5178 }
5179 }
5180 AddedTypes.clear();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005181
5182 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005183
5184 case OO_PlusEqual:
5185 case OO_MinusEqual:
5186 // C++ [over.built]p19:
5187 //
5188 // For every pair (T, VQ), where T is any type and VQ is either
5189 // volatile or empty, there exist candidate operator functions
5190 // of the form
5191 //
5192 // T*VQ& operator=(T*VQ&, T*);
5193 //
5194 // C++ [over.built]p21:
5195 //
5196 // For every pair (T, VQ), where T is a cv-qualified or
5197 // cv-unqualified object type and VQ is either volatile or
5198 // empty, there exist candidate operator functions of the form
5199 //
5200 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5201 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005202 for (BuiltinCandidateTypeSet::iterator
5203 Ptr = CandidateTypes[0].pointer_begin(),
5204 PtrEnd = CandidateTypes[0].pointer_end();
5205 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005206 QualType ParamTypes[2];
5207 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5208
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005209 // If this is operator=, keep track of the builtin candidates we added.
5210 if (Op == OO_Equal)
5211 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5212
Douglas Gregora11693b2008-11-12 17:17:38 +00005213 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005214 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005215 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5216 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005217
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005218 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5219 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005220 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005221 ParamTypes[0]
5222 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005223 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5224 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005225 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005226 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005227
5228 if (Op == OO_Equal) {
5229 for (BuiltinCandidateTypeSet::iterator
5230 Ptr = CandidateTypes[1].pointer_begin(),
5231 PtrEnd = CandidateTypes[1].pointer_end();
5232 Ptr != PtrEnd; ++Ptr) {
5233 // Make sure we don't add the same candidate twice.
5234 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5235 continue;
5236
5237 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5238
5239 // non-volatile version
5240 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5241 /*IsAssigmentOperator=*/true);
5242
5243 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5244 VisibleTypeConversionsQuals.hasVolatile()) {
5245 // volatile version
5246 ParamTypes[0]
5247 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5248 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5249 /*IsAssigmentOperator=*/true);
5250 }
5251 }
5252 AddedTypes.clear();
5253 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005254 // Fall through.
5255
5256 case OO_StarEqual:
5257 case OO_SlashEqual:
5258 // C++ [over.built]p18:
5259 //
5260 // For every triple (L, VQ, R), where L is an arithmetic type,
5261 // VQ is either volatile or empty, and R is a promoted
5262 // arithmetic type, there exist candidate operator functions of
5263 // the form
5264 //
5265 // VQ L& operator=(VQ L&, R);
5266 // VQ L& operator*=(VQ L&, R);
5267 // VQ L& operator/=(VQ L&, R);
5268 // VQ L& operator+=(VQ L&, R);
5269 // VQ L& operator-=(VQ L&, R);
5270 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005271 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005272 Right < LastPromotedArithmeticType; ++Right) {
5273 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005274 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005275
5276 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005277 ParamTypes[0] =
5278 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005279 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5280 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005281
5282 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005283 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall988ffb72010-11-13 02:01:09 +00005284 ParamTypes[0] =
5285 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005286 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5287 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5288 /*IsAssigmentOperator=*/Op == OO_Equal);
5289 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005290 }
5291 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005292
5293 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005294 for (BuiltinCandidateTypeSet::iterator
5295 Vec1 = CandidateTypes[0].vector_begin(),
5296 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005297 Vec1 != Vec1End; ++Vec1)
5298 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005299 Vec2 = CandidateTypes[1].vector_begin(),
5300 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005301 Vec2 != Vec2End; ++Vec2) {
5302 QualType ParamTypes[2];
5303 ParamTypes[1] = *Vec2;
5304 // Add this built-in operator as a candidate (VQ is empty).
5305 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5306 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5307 /*IsAssigmentOperator=*/Op == OO_Equal);
5308
5309 // Add this built-in operator as a candidate (VQ is 'volatile').
5310 if (VisibleTypeConversionsQuals.hasVolatile()) {
5311 ParamTypes[0] = Context.getVolatileType(*Vec1);
5312 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5313 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5314 /*IsAssigmentOperator=*/Op == OO_Equal);
5315 }
5316 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005317 break;
5318
5319 case OO_PercentEqual:
5320 case OO_LessLessEqual:
5321 case OO_GreaterGreaterEqual:
5322 case OO_AmpEqual:
5323 case OO_CaretEqual:
5324 case OO_PipeEqual:
5325 // C++ [over.built]p22:
5326 //
5327 // For every triple (L, VQ, R), where L is an integral type, VQ
5328 // is either volatile or empty, and R is a promoted integral
5329 // type, there exist candidate operator functions of the form
5330 //
5331 // VQ L& operator%=(VQ L&, R);
5332 // VQ L& operator<<=(VQ L&, R);
5333 // VQ L& operator>>=(VQ L&, R);
5334 // VQ L& operator&=(VQ L&, R);
5335 // VQ L& operator^=(VQ L&, R);
5336 // VQ L& operator|=(VQ L&, R);
5337 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005338 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005339 Right < LastPromotedIntegralType; ++Right) {
5340 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005341 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005342
5343 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005344 ParamTypes[0] =
5345 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005346 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005347 if (VisibleTypeConversionsQuals.hasVolatile()) {
5348 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall988ffb72010-11-13 02:01:09 +00005349 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005350 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5351 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5352 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5353 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005354 }
5355 }
5356 break;
5357
Douglas Gregord08452f2008-11-19 15:42:04 +00005358 case OO_Exclaim: {
5359 // C++ [over.operator]p23:
5360 //
5361 // There also exist candidate operator functions of the form
5362 //
Mike Stump11289f42009-09-09 15:08:12 +00005363 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005364 // bool operator&&(bool, bool); [BELOW]
5365 // bool operator||(bool, bool); [BELOW]
5366 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005367 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5368 /*IsAssignmentOperator=*/false,
5369 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005370 break;
5371 }
5372
Douglas Gregora11693b2008-11-12 17:17:38 +00005373 case OO_AmpAmp:
5374 case OO_PipePipe: {
5375 // C++ [over.operator]p23:
5376 //
5377 // There also exist candidate operator functions of the form
5378 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005379 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005380 // bool operator&&(bool, bool);
5381 // bool operator||(bool, bool);
5382 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005383 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5384 /*IsAssignmentOperator=*/false,
5385 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005386 break;
5387 }
5388
5389 case OO_Subscript:
5390 // C++ [over.built]p13:
5391 //
5392 // For every cv-qualified or cv-unqualified object type T there
5393 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005394 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005395 // T* operator+(T*, ptrdiff_t); [ABOVE]
5396 // T& operator[](T*, ptrdiff_t);
5397 // T* operator-(T*, ptrdiff_t); [ABOVE]
5398 // T* operator+(ptrdiff_t, T*); [ABOVE]
5399 // T& operator[](ptrdiff_t, T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005400 for (BuiltinCandidateTypeSet::iterator
5401 Ptr = CandidateTypes[0].pointer_begin(),
5402 PtrEnd = CandidateTypes[0].pointer_end();
5403 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005404 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005405 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005406 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005407
5408 // T& operator[](T*, ptrdiff_t)
5409 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005410 }
5411
5412 for (BuiltinCandidateTypeSet::iterator
5413 Ptr = CandidateTypes[1].pointer_begin(),
5414 PtrEnd = CandidateTypes[1].pointer_end();
5415 Ptr != PtrEnd; ++Ptr) {
5416 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5417 QualType PointeeType = (*Ptr)->getPointeeType();
5418 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5419
5420 // T& operator[](ptrdiff_t, T*)
Douglas Gregora11693b2008-11-12 17:17:38 +00005421 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005422 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005423 break;
5424
5425 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005426 // C++ [over.built]p11:
5427 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5428 // C1 is the same type as C2 or is a derived class of C2, T is an object
5429 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5430 // there exist candidate operator functions of the form
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005431 //
5432 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5433 //
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005434 // where CV12 is the union of CV1 and CV2.
5435 {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005436 for (BuiltinCandidateTypeSet::iterator
5437 Ptr = CandidateTypes[0].pointer_begin(),
5438 PtrEnd = CandidateTypes[0].pointer_end();
5439 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005440 QualType C1Ty = (*Ptr);
5441 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005442 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005443 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5444 if (!isa<RecordType>(C1))
5445 continue;
5446 // heuristic to reduce number of builtin candidates in the set.
5447 // Add volatile/restrict version only if there are conversions to a
5448 // volatile/restrict type.
5449 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5450 continue;
5451 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5452 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005453 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005454 MemPtr = CandidateTypes[1].member_pointer_begin(),
5455 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005456 MemPtr != MemPtrEnd; ++MemPtr) {
5457 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5458 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005459 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005460 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5461 break;
5462 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5463 // build CV12 T&
5464 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005465 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5466 T.isVolatileQualified())
5467 continue;
5468 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5469 T.isRestrictQualified())
5470 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005471 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005472 QualType ResultTy = Context.getLValueReferenceType(T);
5473 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5474 }
5475 }
5476 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005477 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005478
5479 case OO_Conditional:
5480 // Note that we don't consider the first argument, since it has been
5481 // contextually converted to bool long ago. The candidates below are
5482 // therefore added as binary.
5483 //
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005484 // C++ [over.built]p25:
5485 // For every type T, where T is a pointer, pointer-to-member, or scoped
5486 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl1a99f442009-04-16 17:51:27 +00005487 //
5488 // T operator?(bool, T, T);
5489 //
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005490 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5491 for (BuiltinCandidateTypeSet::iterator
5492 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5493 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5494 Ptr != PtrEnd; ++Ptr) {
5495 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5496 continue;
5497
5498 QualType ParamTypes[2] = { *Ptr, *Ptr };
5499 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5500 }
5501
5502 for (BuiltinCandidateTypeSet::iterator
5503 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5504 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5505 MemPtr != MemPtrEnd; ++MemPtr) {
5506 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5507 continue;
5508
5509 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5510 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5511 }
5512
5513 if (getLangOptions().CPlusPlus0x) {
5514 for (BuiltinCandidateTypeSet::iterator
5515 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5516 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5517 Enum != EnumEnd; ++Enum) {
5518 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5519 continue;
5520
5521 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5522 continue;
5523
5524 QualType ParamTypes[2] = { *Enum, *Enum };
5525 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5526 }
5527 }
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005528 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005529 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005530 }
5531}
5532
Douglas Gregore254f902009-02-04 00:32:51 +00005533/// \brief Add function candidates found via argument-dependent lookup
5534/// to the set of overloading candidates.
5535///
5536/// This routine performs argument-dependent name lookup based on the
5537/// given function name (which may also be an operator name) and adds
5538/// all of the overload candidates found by ADL to the overload
5539/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005540void
Douglas Gregore254f902009-02-04 00:32:51 +00005541Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005542 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005543 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005544 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005545 OverloadCandidateSet& CandidateSet,
5546 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005547 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005548
John McCall91f61fc2010-01-26 06:04:06 +00005549 // FIXME: This approach for uniquing ADL results (and removing
5550 // redundant candidates from the set) relies on pointer-equality,
5551 // which means we need to key off the canonical decl. However,
5552 // always going back to the canonical decl might not get us the
5553 // right set of default arguments. What default arguments are
5554 // we supposed to consider on ADL candidates, anyway?
5555
Douglas Gregorcabea402009-09-22 15:41:20 +00005556 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005557 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005558
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005559 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005560 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5561 CandEnd = CandidateSet.end();
5562 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005563 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005564 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005565 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005566 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005567 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005568
5569 // For each of the ADL candidates we found, add it to the overload
5570 // set.
John McCall8fe68082010-01-26 07:16:45 +00005571 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005572 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005574 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005575 continue;
5576
John McCalla0296f72010-03-19 07:35:19 +00005577 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005578 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005579 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005580 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005581 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005582 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005583 }
Douglas Gregore254f902009-02-04 00:32:51 +00005584}
5585
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005586/// isBetterOverloadCandidate - Determines whether the first overload
5587/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005588bool
John McCall5c32be02010-08-24 20:38:10 +00005589isBetterOverloadCandidate(Sema &S,
5590 const OverloadCandidate& Cand1,
5591 const OverloadCandidate& Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005592 SourceLocation Loc,
5593 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005594 // Define viable functions to be better candidates than non-viable
5595 // functions.
5596 if (!Cand2.Viable)
5597 return Cand1.Viable;
5598 else if (!Cand1.Viable)
5599 return false;
5600
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005601 // C++ [over.match.best]p1:
5602 //
5603 // -- if F is a static member function, ICS1(F) is defined such
5604 // that ICS1(F) is neither better nor worse than ICS1(G) for
5605 // any function G, and, symmetrically, ICS1(G) is neither
5606 // better nor worse than ICS1(F).
5607 unsigned StartArg = 0;
5608 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5609 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005610
Douglas Gregord3cb3562009-07-07 23:38:56 +00005611 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005612 // A viable function F1 is defined to be a better function than another
5613 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005614 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005615 unsigned NumArgs = Cand1.Conversions.size();
5616 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5617 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005618 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005619 switch (CompareImplicitConversionSequences(S,
5620 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005621 Cand2.Conversions[ArgIdx])) {
5622 case ImplicitConversionSequence::Better:
5623 // Cand1 has a better conversion sequence.
5624 HasBetterConversion = true;
5625 break;
5626
5627 case ImplicitConversionSequence::Worse:
5628 // Cand1 can't be better than Cand2.
5629 return false;
5630
5631 case ImplicitConversionSequence::Indistinguishable:
5632 // Do nothing.
5633 break;
5634 }
5635 }
5636
Mike Stump11289f42009-09-09 15:08:12 +00005637 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005638 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005639 if (HasBetterConversion)
5640 return true;
5641
Mike Stump11289f42009-09-09 15:08:12 +00005642 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005643 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005644 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005645 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5646 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005647
5648 // -- F1 and F2 are function template specializations, and the function
5649 // template for F1 is more specialized than the template for F2
5650 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005651 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005652 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5653 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005654 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005655 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5656 Cand2.Function->getPrimaryTemplate(),
5657 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005658 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5659 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005660 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005661
Douglas Gregora1f013e2008-11-07 22:36:19 +00005662 // -- the context is an initialization by user-defined conversion
5663 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5664 // from the return type of F1 to the destination type (i.e.,
5665 // the type of the entity being initialized) is a better
5666 // conversion sequence than the standard conversion sequence
5667 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005668 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005669 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005670 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005671 switch (CompareStandardConversionSequences(S,
5672 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005673 Cand2.FinalConversion)) {
5674 case ImplicitConversionSequence::Better:
5675 // Cand1 has a better conversion sequence.
5676 return true;
5677
5678 case ImplicitConversionSequence::Worse:
5679 // Cand1 can't be better than Cand2.
5680 return false;
5681
5682 case ImplicitConversionSequence::Indistinguishable:
5683 // Do nothing
5684 break;
5685 }
5686 }
5687
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005688 return false;
5689}
5690
Mike Stump11289f42009-09-09 15:08:12 +00005691/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005692/// within an overload candidate set.
5693///
5694/// \param CandidateSet the set of candidate functions.
5695///
5696/// \param Loc the location of the function name (or operator symbol) for
5697/// which overload resolution occurs.
5698///
Mike Stump11289f42009-09-09 15:08:12 +00005699/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005700/// function, Best points to the candidate function found.
5701///
5702/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005703OverloadingResult
5704OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005705 iterator& Best,
5706 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005707 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005708 Best = end();
5709 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5710 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005711 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5712 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005713 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005714 }
5715
5716 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005717 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005718 return OR_No_Viable_Function;
5719
5720 // Make sure that this function is better than every other viable
5721 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005722 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005723 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005724 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005725 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5726 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005727 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005728 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005729 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005730 }
Mike Stump11289f42009-09-09 15:08:12 +00005731
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005732 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005733 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005734 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005735 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005736 return OR_Deleted;
5737
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005738 // C++ [basic.def.odr]p2:
5739 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005740 // when referred to from a potentially-evaluated expression. [Note: this
5741 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005742 // (clause 13), user-defined conversions (12.3.2), allocation function for
5743 // placement new (5.3.4), as well as non-default initialization (8.5).
5744 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005745 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005746
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005747 return OR_Success;
5748}
5749
John McCall53262c92010-01-12 02:15:36 +00005750namespace {
5751
5752enum OverloadCandidateKind {
5753 oc_function,
5754 oc_method,
5755 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005756 oc_function_template,
5757 oc_method_template,
5758 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005759 oc_implicit_default_constructor,
5760 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005761 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005762};
5763
John McCalle1ac8d12010-01-13 00:25:19 +00005764OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5765 FunctionDecl *Fn,
5766 std::string &Description) {
5767 bool isTemplate = false;
5768
5769 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5770 isTemplate = true;
5771 Description = S.getTemplateArgumentBindingsText(
5772 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5773 }
John McCallfd0b2f82010-01-06 09:43:14 +00005774
5775 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005776 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005777 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005778
John McCall53262c92010-01-12 02:15:36 +00005779 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5780 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005781 }
5782
5783 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5784 // This actually gets spelled 'candidate function' for now, but
5785 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005786 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005787 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005788
Douglas Gregorec3bec02010-09-27 22:37:28 +00005789 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005790 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005791 return oc_implicit_copy_assignment;
5792 }
5793
John McCalle1ac8d12010-01-13 00:25:19 +00005794 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005795}
5796
5797} // end anonymous namespace
5798
5799// Notes the location of an overload candidate.
5800void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005801 std::string FnDesc;
5802 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5803 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5804 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005805}
5806
John McCall0d1da222010-01-12 00:44:57 +00005807/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5808/// "lead" diagnostic; it will be given two arguments, the source and
5809/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005810void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5811 Sema &S,
5812 SourceLocation CaretLoc,
5813 const PartialDiagnostic &PDiag) const {
5814 S.Diag(CaretLoc, PDiag)
5815 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005816 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005817 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5818 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005819 }
John McCall12f97bc2010-01-08 04:41:39 +00005820}
5821
John McCall0d1da222010-01-12 00:44:57 +00005822namespace {
5823
John McCall6a61b522010-01-13 09:16:55 +00005824void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5825 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5826 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005827 assert(Cand->Function && "for now, candidate must be a function");
5828 FunctionDecl *Fn = Cand->Function;
5829
5830 // There's a conversion slot for the object argument if this is a
5831 // non-constructor method. Note that 'I' corresponds the
5832 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005833 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005834 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005835 if (I == 0)
5836 isObjectArgument = true;
5837 else
5838 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005839 }
5840
John McCalle1ac8d12010-01-13 00:25:19 +00005841 std::string FnDesc;
5842 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5843
John McCall6a61b522010-01-13 09:16:55 +00005844 Expr *FromExpr = Conv.Bad.FromExpr;
5845 QualType FromTy = Conv.Bad.getFromType();
5846 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005847
John McCallfb7ad0f2010-02-02 02:42:52 +00005848 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005849 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005850 Expr *E = FromExpr->IgnoreParens();
5851 if (isa<UnaryOperator>(E))
5852 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005853 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005854
5855 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5856 << (unsigned) FnKind << FnDesc
5857 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5858 << ToTy << Name << I+1;
5859 return;
5860 }
5861
John McCall6d174642010-01-23 08:10:49 +00005862 // Do some hand-waving analysis to see if the non-viability is due
5863 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005864 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5865 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5866 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5867 CToTy = RT->getPointeeType();
5868 else {
5869 // TODO: detect and diagnose the full richness of const mismatches.
5870 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5871 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5872 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5873 }
5874
5875 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5876 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5877 // It is dumb that we have to do this here.
5878 while (isa<ArrayType>(CFromTy))
5879 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5880 while (isa<ArrayType>(CToTy))
5881 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5882
5883 Qualifiers FromQs = CFromTy.getQualifiers();
5884 Qualifiers ToQs = CToTy.getQualifiers();
5885
5886 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5888 << (unsigned) FnKind << FnDesc
5889 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5890 << FromTy
5891 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5892 << (unsigned) isObjectArgument << I+1;
5893 return;
5894 }
5895
5896 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5897 assert(CVR && "unexpected qualifiers mismatch");
5898
5899 if (isObjectArgument) {
5900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5901 << (unsigned) FnKind << FnDesc
5902 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5903 << FromTy << (CVR - 1);
5904 } else {
5905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5906 << (unsigned) FnKind << FnDesc
5907 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5908 << FromTy << (CVR - 1) << I+1;
5909 }
5910 return;
5911 }
5912
John McCall6d174642010-01-23 08:10:49 +00005913 // Diagnose references or pointers to incomplete types differently,
5914 // since it's far from impossible that the incompleteness triggered
5915 // the failure.
5916 QualType TempFromTy = FromTy.getNonReferenceType();
5917 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5918 TempFromTy = PTy->getPointeeType();
5919 if (TempFromTy->isIncompleteType()) {
5920 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5921 << (unsigned) FnKind << FnDesc
5922 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5923 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5924 return;
5925 }
5926
Douglas Gregor56f2e342010-06-30 23:01:39 +00005927 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005928 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005929 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5930 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5931 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5932 FromPtrTy->getPointeeType()) &&
5933 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5934 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5935 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5936 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005937 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005938 }
5939 } else if (const ObjCObjectPointerType *FromPtrTy
5940 = FromTy->getAs<ObjCObjectPointerType>()) {
5941 if (const ObjCObjectPointerType *ToPtrTy
5942 = ToTy->getAs<ObjCObjectPointerType>())
5943 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5944 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5945 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5946 FromPtrTy->getPointeeType()) &&
5947 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005948 BaseToDerivedConversion = 2;
5949 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5950 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5951 !FromTy->isIncompleteType() &&
5952 !ToRefTy->getPointeeType()->isIncompleteType() &&
5953 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5954 BaseToDerivedConversion = 3;
5955 }
5956
5957 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005958 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005959 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005960 << (unsigned) FnKind << FnDesc
5961 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005962 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005963 << FromTy << ToTy << I+1;
5964 return;
5965 }
5966
John McCall47000992010-01-14 03:28:57 +00005967 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005968 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5969 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005970 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005971 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005972}
5973
5974void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5975 unsigned NumFormalArgs) {
5976 // TODO: treat calls to a missing default constructor as a special case
5977
5978 FunctionDecl *Fn = Cand->Function;
5979 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5980
5981 unsigned MinParams = Fn->getMinRequiredArguments();
5982
5983 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005984 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005985 unsigned mode, modeCount;
5986 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005987 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5988 (Cand->FailureKind == ovl_fail_bad_deduction &&
5989 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005990 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5991 mode = 0; // "at least"
5992 else
5993 mode = 2; // "exactly"
5994 modeCount = MinParams;
5995 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005996 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5997 (Cand->FailureKind == ovl_fail_bad_deduction &&
5998 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005999 if (MinParams != FnTy->getNumArgs())
6000 mode = 1; // "at most"
6001 else
6002 mode = 2; // "exactly"
6003 modeCount = FnTy->getNumArgs();
6004 }
6005
6006 std::string Description;
6007 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6008
6009 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006010 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6011 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006012}
6013
John McCall8b9ed552010-02-01 18:53:26 +00006014/// Diagnose a failed template-argument deduction.
6015void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6016 Expr **Args, unsigned NumArgs) {
6017 FunctionDecl *Fn = Cand->Function; // pattern
6018
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006019 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006020 NamedDecl *ParamD;
6021 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6022 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6023 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006024 switch (Cand->DeductionFailure.Result) {
6025 case Sema::TDK_Success:
6026 llvm_unreachable("TDK_success while diagnosing bad deduction");
6027
6028 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006029 assert(ParamD && "no parameter found for incomplete deduction result");
6030 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6031 << ParamD->getDeclName();
6032 return;
6033 }
6034
John McCall42d7d192010-08-05 09:05:08 +00006035 case Sema::TDK_Underqualified: {
6036 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6037 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6038
6039 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6040
6041 // Param will have been canonicalized, but it should just be a
6042 // qualified version of ParamD, so move the qualifiers to that.
6043 QualifierCollector Qs(S.Context);
6044 Qs.strip(Param);
6045 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6046 assert(S.Context.hasSameType(Param, NonCanonParam));
6047
6048 // Arg has also been canonicalized, but there's nothing we can do
6049 // about that. It also doesn't matter as much, because it won't
6050 // have any template parameters in it (because deduction isn't
6051 // done on dependent types).
6052 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6053
6054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6055 << ParamD->getDeclName() << Arg << NonCanonParam;
6056 return;
6057 }
6058
6059 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006060 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006061 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006062 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006063 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006064 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006065 which = 1;
6066 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006067 which = 2;
6068 }
6069
6070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6071 << which << ParamD->getDeclName()
6072 << *Cand->DeductionFailure.getFirstArg()
6073 << *Cand->DeductionFailure.getSecondArg();
6074 return;
6075 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006076
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006077 case Sema::TDK_InvalidExplicitArguments:
6078 assert(ParamD && "no parameter found for invalid explicit arguments");
6079 if (ParamD->getDeclName())
6080 S.Diag(Fn->getLocation(),
6081 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6082 << ParamD->getDeclName();
6083 else {
6084 int index = 0;
6085 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6086 index = TTP->getIndex();
6087 else if (NonTypeTemplateParmDecl *NTTP
6088 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6089 index = NTTP->getIndex();
6090 else
6091 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6092 S.Diag(Fn->getLocation(),
6093 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6094 << (index + 1);
6095 }
6096 return;
6097
Douglas Gregor02eb4832010-05-08 18:13:28 +00006098 case Sema::TDK_TooManyArguments:
6099 case Sema::TDK_TooFewArguments:
6100 DiagnoseArityMismatch(S, Cand, NumArgs);
6101 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006102
6103 case Sema::TDK_InstantiationDepth:
6104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6105 return;
6106
6107 case Sema::TDK_SubstitutionFailure: {
6108 std::string ArgString;
6109 if (TemplateArgumentList *Args
6110 = Cand->DeductionFailure.getTemplateArgumentList())
6111 ArgString = S.getTemplateArgumentBindingsText(
6112 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6113 *Args);
6114 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6115 << ArgString;
6116 return;
6117 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006118
John McCall8b9ed552010-02-01 18:53:26 +00006119 // TODO: diagnose these individually, then kill off
6120 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006121 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006122 case Sema::TDK_FailedOverloadResolution:
6123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6124 return;
6125 }
6126}
6127
6128/// Generates a 'note' diagnostic for an overload candidate. We've
6129/// already generated a primary error at the call site.
6130///
6131/// It really does need to be a single diagnostic with its caret
6132/// pointed at the candidate declaration. Yes, this creates some
6133/// major challenges of technical writing. Yes, this makes pointing
6134/// out problems with specific arguments quite awkward. It's still
6135/// better than generating twenty screens of text for every failed
6136/// overload.
6137///
6138/// It would be great to be able to express per-candidate problems
6139/// more richly for those diagnostic clients that cared, but we'd
6140/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006141void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6142 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006143 FunctionDecl *Fn = Cand->Function;
6144
John McCall12f97bc2010-01-08 04:41:39 +00006145 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006146 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006147 std::string FnDesc;
6148 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006149
6150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006151 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006152 return;
John McCall12f97bc2010-01-08 04:41:39 +00006153 }
6154
John McCalle1ac8d12010-01-13 00:25:19 +00006155 // We don't really have anything else to say about viable candidates.
6156 if (Cand->Viable) {
6157 S.NoteOverloadCandidate(Fn);
6158 return;
6159 }
John McCall0d1da222010-01-12 00:44:57 +00006160
John McCall6a61b522010-01-13 09:16:55 +00006161 switch (Cand->FailureKind) {
6162 case ovl_fail_too_many_arguments:
6163 case ovl_fail_too_few_arguments:
6164 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006165
John McCall6a61b522010-01-13 09:16:55 +00006166 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006167 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6168
John McCallfe796dd2010-01-23 05:17:32 +00006169 case ovl_fail_trivial_conversion:
6170 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006171 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006172 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006173
John McCall65eb8792010-02-25 01:37:24 +00006174 case ovl_fail_bad_conversion: {
6175 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6176 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006177 if (Cand->Conversions[I].isBad())
6178 return DiagnoseBadConversion(S, Cand, I);
6179
6180 // FIXME: this currently happens when we're called from SemaInit
6181 // when user-conversion overload fails. Figure out how to handle
6182 // those conditions and diagnose them well.
6183 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006184 }
John McCall65eb8792010-02-25 01:37:24 +00006185 }
John McCalld3224162010-01-08 00:58:21 +00006186}
6187
6188void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6189 // Desugar the type of the surrogate down to a function type,
6190 // retaining as many typedefs as possible while still showing
6191 // the function type (and, therefore, its parameter types).
6192 QualType FnType = Cand->Surrogate->getConversionType();
6193 bool isLValueReference = false;
6194 bool isRValueReference = false;
6195 bool isPointer = false;
6196 if (const LValueReferenceType *FnTypeRef =
6197 FnType->getAs<LValueReferenceType>()) {
6198 FnType = FnTypeRef->getPointeeType();
6199 isLValueReference = true;
6200 } else if (const RValueReferenceType *FnTypeRef =
6201 FnType->getAs<RValueReferenceType>()) {
6202 FnType = FnTypeRef->getPointeeType();
6203 isRValueReference = true;
6204 }
6205 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6206 FnType = FnTypePtr->getPointeeType();
6207 isPointer = true;
6208 }
6209 // Desugar down to a function type.
6210 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6211 // Reconstruct the pointer/reference as appropriate.
6212 if (isPointer) FnType = S.Context.getPointerType(FnType);
6213 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6214 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6215
6216 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6217 << FnType;
6218}
6219
6220void NoteBuiltinOperatorCandidate(Sema &S,
6221 const char *Opc,
6222 SourceLocation OpLoc,
6223 OverloadCandidate *Cand) {
6224 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6225 std::string TypeStr("operator");
6226 TypeStr += Opc;
6227 TypeStr += "(";
6228 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6229 if (Cand->Conversions.size() == 1) {
6230 TypeStr += ")";
6231 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6232 } else {
6233 TypeStr += ", ";
6234 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6235 TypeStr += ")";
6236 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6237 }
6238}
6239
6240void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6241 OverloadCandidate *Cand) {
6242 unsigned NoOperands = Cand->Conversions.size();
6243 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6244 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006245 if (ICS.isBad()) break; // all meaningless after first invalid
6246 if (!ICS.isAmbiguous()) continue;
6247
John McCall5c32be02010-08-24 20:38:10 +00006248 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006249 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006250 }
6251}
6252
John McCall3712d9e2010-01-15 23:32:50 +00006253SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6254 if (Cand->Function)
6255 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006256 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006257 return Cand->Surrogate->getLocation();
6258 return SourceLocation();
6259}
6260
John McCallad2587a2010-01-12 00:48:53 +00006261struct CompareOverloadCandidatesForDisplay {
6262 Sema &S;
6263 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006264
6265 bool operator()(const OverloadCandidate *L,
6266 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006267 // Fast-path this check.
6268 if (L == R) return false;
6269
John McCall12f97bc2010-01-08 04:41:39 +00006270 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006271 if (L->Viable) {
6272 if (!R->Viable) return true;
6273
6274 // TODO: introduce a tri-valued comparison for overload
6275 // candidates. Would be more worthwhile if we had a sort
6276 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006277 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6278 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006279 } else if (R->Viable)
6280 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006281
John McCall3712d9e2010-01-15 23:32:50 +00006282 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006283
John McCall3712d9e2010-01-15 23:32:50 +00006284 // Criteria by which we can sort non-viable candidates:
6285 if (!L->Viable) {
6286 // 1. Arity mismatches come after other candidates.
6287 if (L->FailureKind == ovl_fail_too_many_arguments ||
6288 L->FailureKind == ovl_fail_too_few_arguments)
6289 return false;
6290 if (R->FailureKind == ovl_fail_too_many_arguments ||
6291 R->FailureKind == ovl_fail_too_few_arguments)
6292 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006293
John McCallfe796dd2010-01-23 05:17:32 +00006294 // 2. Bad conversions come first and are ordered by the number
6295 // of bad conversions and quality of good conversions.
6296 if (L->FailureKind == ovl_fail_bad_conversion) {
6297 if (R->FailureKind != ovl_fail_bad_conversion)
6298 return true;
6299
6300 // If there's any ordering between the defined conversions...
6301 // FIXME: this might not be transitive.
6302 assert(L->Conversions.size() == R->Conversions.size());
6303
6304 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006305 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6306 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006307 switch (CompareImplicitConversionSequences(S,
6308 L->Conversions[I],
6309 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006310 case ImplicitConversionSequence::Better:
6311 leftBetter++;
6312 break;
6313
6314 case ImplicitConversionSequence::Worse:
6315 leftBetter--;
6316 break;
6317
6318 case ImplicitConversionSequence::Indistinguishable:
6319 break;
6320 }
6321 }
6322 if (leftBetter > 0) return true;
6323 if (leftBetter < 0) return false;
6324
6325 } else if (R->FailureKind == ovl_fail_bad_conversion)
6326 return false;
6327
John McCall3712d9e2010-01-15 23:32:50 +00006328 // TODO: others?
6329 }
6330
6331 // Sort everything else by location.
6332 SourceLocation LLoc = GetLocationForCandidate(L);
6333 SourceLocation RLoc = GetLocationForCandidate(R);
6334
6335 // Put candidates without locations (e.g. builtins) at the end.
6336 if (LLoc.isInvalid()) return false;
6337 if (RLoc.isInvalid()) return true;
6338
6339 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006340 }
6341};
6342
John McCallfe796dd2010-01-23 05:17:32 +00006343/// CompleteNonViableCandidate - Normally, overload resolution only
6344/// computes up to the first
6345void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6346 Expr **Args, unsigned NumArgs) {
6347 assert(!Cand->Viable);
6348
6349 // Don't do anything on failures other than bad conversion.
6350 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6351
6352 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006353 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006354 unsigned ConvCount = Cand->Conversions.size();
6355 while (true) {
6356 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6357 ConvIdx++;
6358 if (Cand->Conversions[ConvIdx - 1].isBad())
6359 break;
6360 }
6361
6362 if (ConvIdx == ConvCount)
6363 return;
6364
John McCall65eb8792010-02-25 01:37:24 +00006365 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6366 "remaining conversion is initialized?");
6367
Douglas Gregoradc7a702010-04-16 17:45:54 +00006368 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006369 // operation somehow.
6370 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006371
6372 const FunctionProtoType* Proto;
6373 unsigned ArgIdx = ConvIdx;
6374
6375 if (Cand->IsSurrogate) {
6376 QualType ConvType
6377 = Cand->Surrogate->getConversionType().getNonReferenceType();
6378 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6379 ConvType = ConvPtrType->getPointeeType();
6380 Proto = ConvType->getAs<FunctionProtoType>();
6381 ArgIdx--;
6382 } else if (Cand->Function) {
6383 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6384 if (isa<CXXMethodDecl>(Cand->Function) &&
6385 !isa<CXXConstructorDecl>(Cand->Function))
6386 ArgIdx--;
6387 } else {
6388 // Builtin binary operator with a bad first conversion.
6389 assert(ConvCount <= 3);
6390 for (; ConvIdx != ConvCount; ++ConvIdx)
6391 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006392 = TryCopyInitialization(S, Args[ConvIdx],
6393 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6394 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006395 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006396 return;
6397 }
6398
6399 // Fill in the rest of the conversions.
6400 unsigned NumArgsInProto = Proto->getNumArgs();
6401 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6402 if (ArgIdx < NumArgsInProto)
6403 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006404 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6405 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006406 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006407 else
6408 Cand->Conversions[ConvIdx].setEllipsis();
6409 }
6410}
6411
John McCalld3224162010-01-08 00:58:21 +00006412} // end anonymous namespace
6413
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006414/// PrintOverloadCandidates - When overload resolution fails, prints
6415/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006416/// set.
John McCall5c32be02010-08-24 20:38:10 +00006417void OverloadCandidateSet::NoteCandidates(Sema &S,
6418 OverloadCandidateDisplayKind OCD,
6419 Expr **Args, unsigned NumArgs,
6420 const char *Opc,
6421 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006422 // Sort the candidates by viability and position. Sorting directly would
6423 // be prohibitive, so we make a set of pointers and sort those.
6424 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006425 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6426 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006427 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006428 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006429 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006430 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006431 if (Cand->Function || Cand->IsSurrogate)
6432 Cands.push_back(Cand);
6433 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6434 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006435 }
6436 }
6437
John McCallad2587a2010-01-12 00:48:53 +00006438 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006439 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006440
John McCall0d1da222010-01-12 00:44:57 +00006441 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006442
John McCall12f97bc2010-01-08 04:41:39 +00006443 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006444 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006445 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006446 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6447 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006448
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006449 // Set an arbitrary limit on the number of candidate functions we'll spam
6450 // the user with. FIXME: This limit should depend on details of the
6451 // candidate list.
6452 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6453 break;
6454 }
6455 ++CandsShown;
6456
John McCalld3224162010-01-08 00:58:21 +00006457 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006458 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006459 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006460 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006461 else {
6462 assert(Cand->Viable &&
6463 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006464 // Generally we only see ambiguities including viable builtin
6465 // operators if overload resolution got screwed up by an
6466 // ambiguous user-defined conversion.
6467 //
6468 // FIXME: It's quite possible for different conversions to see
6469 // different ambiguities, though.
6470 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006471 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006472 ReportedAmbiguousConversions = true;
6473 }
John McCalld3224162010-01-08 00:58:21 +00006474
John McCall0d1da222010-01-12 00:44:57 +00006475 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006476 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006477 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006478 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006479
6480 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006481 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006482}
6483
John McCalla0296f72010-03-19 07:35:19 +00006484static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006485 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006486 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006487
John McCalla0296f72010-03-19 07:35:19 +00006488 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006489}
6490
Douglas Gregorcd695e52008-11-10 20:40:00 +00006491/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6492/// an overloaded function (C++ [over.over]), where @p From is an
6493/// expression with overloaded function type and @p ToType is the type
6494/// we're trying to resolve to. For example:
6495///
6496/// @code
6497/// int f(double);
6498/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006499///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006500/// int (*pfd)(double) = f; // selects f(double)
6501/// @endcode
6502///
6503/// This routine returns the resulting FunctionDecl if it could be
6504/// resolved, and NULL otherwise. When @p Complain is true, this
6505/// routine will emit diagnostics if there is an error.
6506FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006507Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006508 bool Complain,
6509 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006510 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006511 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006512 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006513 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006514 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006515 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006516 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006517 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006518 FunctionType = MemTypePtr->getPointeeType();
6519 IsMember = true;
6520 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006521
Douglas Gregorcd695e52008-11-10 20:40:00 +00006522 // C++ [over.over]p1:
6523 // [...] [Note: any redundant set of parentheses surrounding the
6524 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006525 // C++ [over.over]p1:
6526 // [...] The overloaded function name can be preceded by the &
6527 // operator.
John McCall7d460512010-08-24 23:26:21 +00006528 // However, remember whether the expression has member-pointer form:
6529 // C++ [expr.unary.op]p4:
6530 // A pointer to member is only formed when an explicit & is used
6531 // and its operand is a qualified-id not enclosed in
6532 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006533 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6534 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006535
Douglas Gregor064fdb22010-04-14 23:11:21 +00006536 // We expect a pointer or reference to function, or a function pointer.
6537 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6538 if (!FunctionType->isFunctionType()) {
6539 if (Complain)
6540 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6541 << OvlExpr->getName() << ToType;
6542
6543 return 0;
6544 }
6545
John McCall24d18942010-08-24 22:52:39 +00006546 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006547 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006548 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006549 if (!Complain) return 0;
6550
6551 // TODO: Should we condition this on whether any functions might
6552 // have matched, or is it more appropriate to do that in callers?
6553 // TODO: a fixit wouldn't hurt.
6554 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6555 << ToType << OvlExpr->getSourceRange();
6556 return 0;
6557 }
6558
6559 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6560 if (OvlExpr->hasExplicitTemplateArgs()) {
6561 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6562 ExplicitTemplateArgs = &ETABuffer;
6563 }
6564
Douglas Gregor064fdb22010-04-14 23:11:21 +00006565 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006566
Douglas Gregorcd695e52008-11-10 20:40:00 +00006567 // Look through all of the overloaded functions, searching for one
6568 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006569 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006570 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006571
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006572 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006573 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6574 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006575 // Look through any using declarations to find the underlying function.
6576 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6577
Douglas Gregorcd695e52008-11-10 20:40:00 +00006578 // C++ [over.over]p3:
6579 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006580 // targets of type "pointer-to-function" or "reference-to-function."
6581 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006582 // type "pointer-to-member-function."
6583 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006584
Mike Stump11289f42009-09-09 15:08:12 +00006585 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006586 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006587 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006588 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006589 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006590 // static when converting to member pointer.
6591 if (Method->isStatic() == IsMember)
6592 continue;
6593 } else if (IsMember)
6594 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006595
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006596 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006597 // If the name is a function template, template argument deduction is
6598 // done (14.8.2.2), and if the argument deduction succeeds, the
6599 // resulting template argument list is used to generate a single
6600 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006601 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006602 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006603 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006604 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006605 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006606 FunctionType, Specialization, Info)) {
6607 // FIXME: make a note of the failed deduction for diagnostics.
6608 (void)Result;
6609 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006610 // Template argument deduction ensures that we have an exact match.
6611 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006612 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006613 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006614 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006615 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006616 }
John McCalld14a8642009-11-21 08:51:07 +00006617
6618 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006619 }
Mike Stump11289f42009-09-09 15:08:12 +00006620
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006621 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006622 // Skip non-static functions when converting to pointer, and static
6623 // when converting to member pointer.
6624 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006625 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006626
6627 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006628 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006629 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006630 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006631 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006632
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006633 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006634 QualType ResultTy;
6635 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6636 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6637 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006638 Matches.push_back(std::make_pair(I.getPair(),
6639 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006640 FoundNonTemplateFunction = true;
6641 }
Mike Stump11289f42009-09-09 15:08:12 +00006642 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006643 }
6644
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006645 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006646 if (Matches.empty()) {
6647 if (Complain) {
6648 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6649 << OvlExpr->getName() << FunctionType;
6650 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6651 E = OvlExpr->decls_end();
6652 I != E; ++I)
6653 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6654 NoteOverloadCandidate(F);
6655 }
6656
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006657 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006658 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006659 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006660 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006661 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006662 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006663 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006664 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006665 return Result;
6666 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006667
6668 // C++ [over.over]p4:
6669 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006670 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006671 // [...] and any given function template specialization F1 is
6672 // eliminated if the set contains a second function template
6673 // specialization whose function template is more specialized
6674 // than the function template of F1 according to the partial
6675 // ordering rules of 14.5.5.2.
6676
6677 // The algorithm specified above is quadratic. We instead use a
6678 // two-pass algorithm (similar to the one used to identify the
6679 // best viable function in an overload set) that identifies the
6680 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006681
6682 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6683 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6684 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006685
6686 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006687 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006688 TPOC_Other, From->getLocStart(),
6689 PDiag(),
6690 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006691 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006692 PDiag(diag::note_ovl_candidate)
6693 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006694 if (Result == MatchesCopy.end())
6695 return 0;
6696
John McCall58cc69d2010-01-27 01:50:18 +00006697 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006698 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006699 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006700 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006701 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006702 }
Mike Stump11289f42009-09-09 15:08:12 +00006703
Douglas Gregorfae1d712009-09-26 03:56:17 +00006704 // [...] any function template specializations in the set are
6705 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006706 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006707 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006708 ++I;
6709 else {
John McCalla0296f72010-03-19 07:35:19 +00006710 Matches[I] = Matches[--N];
6711 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006712 }
6713 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006714
Mike Stump11289f42009-09-09 15:08:12 +00006715 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006716 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006717 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006718 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006719 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006720 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006721 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6722 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006723 }
Mike Stump11289f42009-09-09 15:08:12 +00006724
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006725 // FIXME: We should probably return the same thing that BestViableFunction
6726 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006727 if (Complain) {
6728 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6729 << Matches[0].second->getDeclName();
6730 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6731 NoteOverloadCandidate(Matches[I].second);
6732 }
6733
Douglas Gregorcd695e52008-11-10 20:40:00 +00006734 return 0;
6735}
6736
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006737/// \brief Given an expression that refers to an overloaded function, try to
6738/// resolve that overloaded function expression down to a single function.
6739///
6740/// This routine can only resolve template-ids that refer to a single function
6741/// template, where that template-id refers to a single template whose template
6742/// arguments are either provided by the template-id or have defaults,
6743/// as described in C++0x [temp.arg.explicit]p3.
6744FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6745 // C++ [over.over]p1:
6746 // [...] [Note: any redundant set of parentheses surrounding the
6747 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006748 // C++ [over.over]p1:
6749 // [...] The overloaded function name can be preceded by the &
6750 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006751
6752 if (From->getType() != Context.OverloadTy)
6753 return 0;
6754
John McCall8d08b9b2010-08-27 09:08:28 +00006755 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006756
6757 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006758 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006759 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006760
6761 TemplateArgumentListInfo ExplicitTemplateArgs;
6762 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006763
6764 // Look through all of the overloaded functions, searching for one
6765 // whose type matches exactly.
6766 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006767 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6768 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006769 // C++0x [temp.arg.explicit]p3:
6770 // [...] In contexts where deduction is done and fails, or in contexts
6771 // where deduction is not done, if a template argument list is
6772 // specified and it, along with any default template arguments,
6773 // identifies a single function template specialization, then the
6774 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006775 FunctionTemplateDecl *FunctionTemplate
6776 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006777
6778 // C++ [over.over]p2:
6779 // If the name is a function template, template argument deduction is
6780 // done (14.8.2.2), and if the argument deduction succeeds, the
6781 // resulting template argument list is used to generate a single
6782 // function template specialization, which is added to the set of
6783 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006784 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006785 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006786 if (TemplateDeductionResult Result
6787 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6788 Specialization, Info)) {
6789 // FIXME: make a note of the failed deduction for diagnostics.
6790 (void)Result;
6791 continue;
6792 }
6793
6794 // Multiple matches; we can't resolve to a single declaration.
6795 if (Matched)
6796 return 0;
6797
6798 Matched = Specialization;
6799 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006800
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006801 return Matched;
6802}
6803
Douglas Gregorcabea402009-09-22 15:41:20 +00006804/// \brief Add a single candidate to the overload set.
6805static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006806 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006807 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006808 Expr **Args, unsigned NumArgs,
6809 OverloadCandidateSet &CandidateSet,
6810 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006811 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006812 if (isa<UsingShadowDecl>(Callee))
6813 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6814
Douglas Gregorcabea402009-09-22 15:41:20 +00006815 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006816 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006817 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006818 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006819 return;
John McCalld14a8642009-11-21 08:51:07 +00006820 }
6821
6822 if (FunctionTemplateDecl *FuncTemplate
6823 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006824 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6825 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006826 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006827 return;
6828 }
6829
6830 assert(false && "unhandled case in overloaded call candidate");
6831
6832 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006833}
6834
6835/// \brief Add the overload candidates named by callee and/or found by argument
6836/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006837void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006838 Expr **Args, unsigned NumArgs,
6839 OverloadCandidateSet &CandidateSet,
6840 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006841
6842#ifndef NDEBUG
6843 // Verify that ArgumentDependentLookup is consistent with the rules
6844 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006845 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006846 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6847 // and let Y be the lookup set produced by argument dependent
6848 // lookup (defined as follows). If X contains
6849 //
6850 // -- a declaration of a class member, or
6851 //
6852 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006853 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006854 //
6855 // -- a declaration that is neither a function or a function
6856 // template
6857 //
6858 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006859
John McCall57500772009-12-16 12:17:52 +00006860 if (ULE->requiresADL()) {
6861 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6862 E = ULE->decls_end(); I != E; ++I) {
6863 assert(!(*I)->getDeclContext()->isRecord());
6864 assert(isa<UsingShadowDecl>(*I) ||
6865 !(*I)->getDeclContext()->isFunctionOrMethod());
6866 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006867 }
6868 }
6869#endif
6870
John McCall57500772009-12-16 12:17:52 +00006871 // It would be nice to avoid this copy.
6872 TemplateArgumentListInfo TABuffer;
6873 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6874 if (ULE->hasExplicitTemplateArgs()) {
6875 ULE->copyTemplateArgumentsInto(TABuffer);
6876 ExplicitTemplateArgs = &TABuffer;
6877 }
6878
6879 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6880 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006881 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006882 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006883 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006884
John McCall57500772009-12-16 12:17:52 +00006885 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006886 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6887 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006888 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006889 CandidateSet,
6890 PartialOverloading);
6891}
John McCalld681c392009-12-16 08:11:27 +00006892
6893/// Attempts to recover from a call where no functions were found.
6894///
6895/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006896static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006897BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006898 UnresolvedLookupExpr *ULE,
6899 SourceLocation LParenLoc,
6900 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006901 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006902
6903 CXXScopeSpec SS;
6904 if (ULE->getQualifier()) {
6905 SS.setScopeRep(ULE->getQualifier());
6906 SS.setRange(ULE->getQualifierRange());
6907 }
6908
John McCall57500772009-12-16 12:17:52 +00006909 TemplateArgumentListInfo TABuffer;
6910 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6911 if (ULE->hasExplicitTemplateArgs()) {
6912 ULE->copyTemplateArgumentsInto(TABuffer);
6913 ExplicitTemplateArgs = &TABuffer;
6914 }
6915
John McCalld681c392009-12-16 08:11:27 +00006916 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6917 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006918 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006919 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006920
John McCall57500772009-12-16 12:17:52 +00006921 assert(!R.empty() && "lookup results empty despite recovery");
6922
6923 // Build an implicit member call if appropriate. Just drop the
6924 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006925 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006926 if ((*R.begin())->isCXXClassMember())
6927 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6928 else if (ExplicitTemplateArgs)
6929 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6930 else
6931 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6932
6933 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006934 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006935
6936 // This shouldn't cause an infinite loop because we're giving it
6937 // an expression with non-empty lookup results, which should never
6938 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006939 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006940 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006941}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006942
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006943/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006944/// (which eventually refers to the declaration Func) and the call
6945/// arguments Args/NumArgs, attempt to resolve the function call down
6946/// to a specific function. If overload resolution succeeds, returns
6947/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006948/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006949/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006950ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006951Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006952 SourceLocation LParenLoc,
6953 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006954 SourceLocation RParenLoc) {
6955#ifndef NDEBUG
6956 if (ULE->requiresADL()) {
6957 // To do ADL, we must have found an unqualified name.
6958 assert(!ULE->getQualifier() && "qualified name with ADL");
6959
6960 // We don't perform ADL for implicit declarations of builtins.
6961 // Verify that this was correctly set up.
6962 FunctionDecl *F;
6963 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6964 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6965 F->getBuiltinID() && F->isImplicit())
6966 assert(0 && "performing ADL for builtin");
6967
6968 // We don't perform ADL in C.
6969 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6970 }
6971#endif
6972
John McCallbc077cf2010-02-08 23:07:23 +00006973 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006974
John McCall57500772009-12-16 12:17:52 +00006975 // Add the functions denoted by the callee to the set of candidate
6976 // functions, including those from argument-dependent lookup.
6977 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006978
6979 // If we found nothing, try to recover.
6980 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6981 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006982 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006983 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006984 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006985
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006986 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006987 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006988 case OR_Success: {
6989 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006990 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00006991 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006992 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006993 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6994 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006995
6996 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006997 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006998 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006999 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007000 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007001 break;
7002
7003 case OR_Ambiguous:
7004 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007005 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007006 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007007 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007008
7009 case OR_Deleted:
7010 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7011 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007012 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007013 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007014 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007015 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007016 }
7017
Douglas Gregorb412e172010-07-25 18:17:45 +00007018 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007019 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007020}
7021
John McCall4c4c1df2010-01-26 03:27:55 +00007022static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007023 return Functions.size() > 1 ||
7024 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7025}
7026
Douglas Gregor084d8552009-03-13 23:49:33 +00007027/// \brief Create a unary operation that may resolve to an overloaded
7028/// operator.
7029///
7030/// \param OpLoc The location of the operator itself (e.g., '*').
7031///
7032/// \param OpcIn The UnaryOperator::Opcode that describes this
7033/// operator.
7034///
7035/// \param Functions The set of non-member functions that will be
7036/// considered by overload resolution. The caller needs to build this
7037/// set based on the context using, e.g.,
7038/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7039/// set should not contain any member functions; those will be added
7040/// by CreateOverloadedUnaryOp().
7041///
7042/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007043ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007044Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7045 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007046 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007047 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007048
7049 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7050 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7051 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007052 // TODO: provide better source location info.
7053 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007054
7055 Expr *Args[2] = { Input, 0 };
7056 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007057
Douglas Gregor084d8552009-03-13 23:49:33 +00007058 // For post-increment and post-decrement, add the implicit '0' as
7059 // the second argument, so that we know this is a post-increment or
7060 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007061 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007062 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007063 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7064 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007065 NumArgs = 2;
7066 }
7067
7068 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007069 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007070 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007071 Opc,
7072 Context.DependentTy,
7073 OpLoc));
7074
John McCall58cc69d2010-01-27 01:50:18 +00007075 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007076 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007077 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007078 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007079 /*ADL*/ true, IsOverloaded(Fns),
7080 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007081 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7082 &Args[0], NumArgs,
7083 Context.DependentTy,
7084 OpLoc));
7085 }
7086
7087 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007088 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007089
7090 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007091 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007092
7093 // Add operator candidates that are member functions.
7094 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7095
John McCall4c4c1df2010-01-26 03:27:55 +00007096 // Add candidates from ADL.
7097 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007098 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007099 /*ExplicitTemplateArgs*/ 0,
7100 CandidateSet);
7101
Douglas Gregor084d8552009-03-13 23:49:33 +00007102 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007103 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007104
7105 // Perform overload resolution.
7106 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007107 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007108 case OR_Success: {
7109 // We found a built-in operator or an overloaded operator.
7110 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007111
Douglas Gregor084d8552009-03-13 23:49:33 +00007112 if (FnDecl) {
7113 // We matched an overloaded operator. Build a call to that
7114 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007115
Douglas Gregor084d8552009-03-13 23:49:33 +00007116 // Convert the arguments.
7117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007118 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007119
John McCall16df1e52010-03-30 21:47:33 +00007120 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7121 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007122 return ExprError();
7123 } else {
7124 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007125 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007126 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007127 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007128 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007129 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007130 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007131 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007132 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007133 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007134 }
7135
John McCall4fa0d5f2010-05-06 18:15:07 +00007136 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7137
Douglas Gregor084d8552009-03-13 23:49:33 +00007138 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00007139 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007140
Douglas Gregor084d8552009-03-13 23:49:33 +00007141 // Build the actual expression node.
7142 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7143 SourceLocation());
7144 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00007145
Eli Friedman030eee42009-11-18 03:58:17 +00007146 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007147 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007148 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00007149 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007150
John McCallb268a282010-08-23 23:25:46 +00007151 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007152 FnDecl))
7153 return ExprError();
7154
John McCallb268a282010-08-23 23:25:46 +00007155 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007156 } else {
7157 // We matched a built-in operator. Convert the arguments, then
7158 // break out so that we will build the appropriate built-in
7159 // operator node.
7160 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007161 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007162 return ExprError();
7163
7164 break;
7165 }
7166 }
7167
7168 case OR_No_Viable_Function:
7169 // No viable function; fall through to handling this as a
7170 // built-in operator, which will produce an error message for us.
7171 break;
7172
7173 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007174 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007175 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007176 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007177 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007178 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7179 Args, NumArgs,
7180 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007181 return ExprError();
7182
7183 case OR_Deleted:
7184 Diag(OpLoc, diag::err_ovl_deleted_oper)
7185 << Best->Function->isDeleted()
7186 << UnaryOperator::getOpcodeStr(Opc)
7187 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007188 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007189 return ExprError();
7190 }
7191
7192 // Either we found no viable overloaded operator or we matched a
7193 // built-in operator. In either case, fall through to trying to
7194 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007195 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007196}
7197
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007198/// \brief Create a binary operation that may resolve to an overloaded
7199/// operator.
7200///
7201/// \param OpLoc The location of the operator itself (e.g., '+').
7202///
7203/// \param OpcIn The BinaryOperator::Opcode that describes this
7204/// operator.
7205///
7206/// \param Functions The set of non-member functions that will be
7207/// considered by overload resolution. The caller needs to build this
7208/// set based on the context using, e.g.,
7209/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7210/// set should not contain any member functions; those will be added
7211/// by CreateOverloadedBinOp().
7212///
7213/// \param LHS Left-hand argument.
7214/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007215ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007216Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007217 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007218 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007219 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007220 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007221 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007222
7223 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7224 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7225 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7226
7227 // If either side is type-dependent, create an appropriate dependent
7228 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007229 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007230 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007231 // If there are no functions to store, just build a dependent
7232 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007233 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007234 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7235 Context.DependentTy, OpLoc));
7236
7237 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7238 Context.DependentTy,
7239 Context.DependentTy,
7240 Context.DependentTy,
7241 OpLoc));
7242 }
John McCall4c4c1df2010-01-26 03:27:55 +00007243
7244 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007245 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007246 // TODO: provide better source location info in DNLoc component.
7247 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007248 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007249 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007250 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007251 /*ADL*/ true, IsOverloaded(Fns),
7252 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007253 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007254 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007255 Context.DependentTy,
7256 OpLoc));
7257 }
7258
7259 // If this is the .* operator, which is not overloadable, just
7260 // create a built-in binary operator.
John McCalle3027922010-08-25 11:45:40 +00007261 if (Opc == BO_PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00007262 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007263
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007264 // If this is the assignment operator, we only perform overload resolution
7265 // if the left-hand side is a class or enumeration type. This is actually
7266 // a hack. The standard requires that we do overload resolution between the
7267 // various built-in candidates, but as DR507 points out, this can lead to
7268 // problems. So we do it this way, which pretty much follows what GCC does.
7269 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007270 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007271 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007272
Douglas Gregor084d8552009-03-13 23:49:33 +00007273 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007274 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007275
7276 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007277 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007278
7279 // Add operator candidates that are member functions.
7280 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7281
John McCall4c4c1df2010-01-26 03:27:55 +00007282 // Add candidates from ADL.
7283 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7284 Args, 2,
7285 /*ExplicitTemplateArgs*/ 0,
7286 CandidateSet);
7287
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007288 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007289 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007290
7291 // Perform overload resolution.
7292 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007293 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007294 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007295 // We found a built-in operator or an overloaded operator.
7296 FunctionDecl *FnDecl = Best->Function;
7297
7298 if (FnDecl) {
7299 // We matched an overloaded operator. Build a call to that
7300 // operator.
7301
7302 // Convert the arguments.
7303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007304 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007305 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007306
John McCalldadc5752010-08-24 06:29:42 +00007307 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007308 = PerformCopyInitialization(
7309 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007310 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007311 FnDecl->getParamDecl(0)),
7312 SourceLocation(),
7313 Owned(Args[1]));
7314 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007315 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007316
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007317 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007318 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007319 return ExprError();
7320
7321 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007322 } else {
7323 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007324 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007325 = PerformCopyInitialization(
7326 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007327 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007328 FnDecl->getParamDecl(0)),
7329 SourceLocation(),
7330 Owned(Args[0]));
7331 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007332 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007333
John McCalldadc5752010-08-24 06:29:42 +00007334 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007335 = PerformCopyInitialization(
7336 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007337 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007338 FnDecl->getParamDecl(1)),
7339 SourceLocation(),
7340 Owned(Args[1]));
7341 if (Arg1.isInvalid())
7342 return ExprError();
7343 Args[0] = LHS = Arg0.takeAs<Expr>();
7344 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007345 }
7346
John McCall4fa0d5f2010-05-06 18:15:07 +00007347 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7348
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007349 // Determine the result type
7350 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007351 = FnDecl->getType()->getAs<FunctionType>()
7352 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007353
7354 // Build the actual expression node.
7355 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00007356 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007357 UsualUnaryConversions(FnExpr);
7358
John McCallb268a282010-08-23 23:25:46 +00007359 CXXOperatorCallExpr *TheCall =
7360 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7361 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007362
John McCallb268a282010-08-23 23:25:46 +00007363 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007364 FnDecl))
7365 return ExprError();
7366
John McCallb268a282010-08-23 23:25:46 +00007367 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007368 } else {
7369 // We matched a built-in operator. Convert the arguments, then
7370 // break out so that we will build the appropriate built-in
7371 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007372 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007373 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007374 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007375 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007376 return ExprError();
7377
7378 break;
7379 }
7380 }
7381
Douglas Gregor66950a32009-09-30 21:46:01 +00007382 case OR_No_Viable_Function: {
7383 // C++ [over.match.oper]p9:
7384 // If the operator is the operator , [...] and there are no
7385 // viable functions, then the operator is assumed to be the
7386 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007387 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007388 break;
7389
Sebastian Redl027de2a2009-05-21 11:50:50 +00007390 // For class as left operand for assignment or compound assigment operator
7391 // do not fall through to handling in built-in, but report that no overloaded
7392 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007393 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007394 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007395 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007396 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7397 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007398 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007399 } else {
7400 // No viable function; try to create a built-in operation, which will
7401 // produce an error. Then, show the non-viable candidates.
7402 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007403 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007404 assert(Result.isInvalid() &&
7405 "C++ binary operator overloading is missing candidates!");
7406 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007407 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7408 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007409 return move(Result);
7410 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007411
7412 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007413 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007414 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007415 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007416 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007417 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7418 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007419 return ExprError();
7420
7421 case OR_Deleted:
7422 Diag(OpLoc, diag::err_ovl_deleted_oper)
7423 << Best->Function->isDeleted()
7424 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007425 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007426 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007427 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007428 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007429
Douglas Gregor66950a32009-09-30 21:46:01 +00007430 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007431 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007432}
7433
John McCalldadc5752010-08-24 06:29:42 +00007434ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007435Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7436 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007437 Expr *Base, Expr *Idx) {
7438 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007439 DeclarationName OpName =
7440 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7441
7442 // If either side is type-dependent, create an appropriate dependent
7443 // expression.
7444 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7445
John McCall58cc69d2010-01-27 01:50:18 +00007446 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007447 // CHECKME: no 'operator' keyword?
7448 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7449 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007450 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007451 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007452 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007453 /*ADL*/ true, /*Overloaded*/ false,
7454 UnresolvedSetIterator(),
7455 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007456 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007457
Sebastian Redladba46e2009-10-29 20:17:01 +00007458 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7459 Args, 2,
7460 Context.DependentTy,
7461 RLoc));
7462 }
7463
7464 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007465 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007466
7467 // Subscript can only be overloaded as a member function.
7468
7469 // Add operator candidates that are member functions.
7470 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7471
7472 // Add builtin operator candidates.
7473 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7474
7475 // Perform overload resolution.
7476 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007477 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007478 case OR_Success: {
7479 // We found a built-in operator or an overloaded operator.
7480 FunctionDecl *FnDecl = Best->Function;
7481
7482 if (FnDecl) {
7483 // We matched an overloaded operator. Build a call to that
7484 // operator.
7485
John McCalla0296f72010-03-19 07:35:19 +00007486 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007487 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007488
Sebastian Redladba46e2009-10-29 20:17:01 +00007489 // Convert the arguments.
7490 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007491 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007492 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007493 return ExprError();
7494
Anders Carlssona68e51e2010-01-29 18:37:50 +00007495 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007496 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007497 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007498 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007499 FnDecl->getParamDecl(0)),
7500 SourceLocation(),
7501 Owned(Args[1]));
7502 if (InputInit.isInvalid())
7503 return ExprError();
7504
7505 Args[1] = InputInit.takeAs<Expr>();
7506
Sebastian Redladba46e2009-10-29 20:17:01 +00007507 // Determine the result type
7508 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007509 = FnDecl->getType()->getAs<FunctionType>()
7510 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007511
7512 // Build the actual expression node.
7513 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7514 LLoc);
7515 UsualUnaryConversions(FnExpr);
7516
John McCallb268a282010-08-23 23:25:46 +00007517 CXXOperatorCallExpr *TheCall =
7518 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7519 FnExpr, Args, 2,
7520 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007521
John McCallb268a282010-08-23 23:25:46 +00007522 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007523 FnDecl))
7524 return ExprError();
7525
John McCallb268a282010-08-23 23:25:46 +00007526 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007527 } else {
7528 // We matched a built-in operator. Convert the arguments, then
7529 // break out so that we will build the appropriate built-in
7530 // operator node.
7531 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007532 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007533 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007534 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007535 return ExprError();
7536
7537 break;
7538 }
7539 }
7540
7541 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007542 if (CandidateSet.empty())
7543 Diag(LLoc, diag::err_ovl_no_oper)
7544 << Args[0]->getType() << /*subscript*/ 0
7545 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7546 else
7547 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7548 << Args[0]->getType()
7549 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007550 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7551 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007552 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007553 }
7554
7555 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007556 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7557 << "[]"
7558 << Args[0]->getType() << Args[1]->getType()
7559 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007560 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7561 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007562 return ExprError();
7563
7564 case OR_Deleted:
7565 Diag(LLoc, diag::err_ovl_deleted_oper)
7566 << Best->Function->isDeleted() << "[]"
7567 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007568 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7569 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007570 return ExprError();
7571 }
7572
7573 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007574 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007575}
7576
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007577/// BuildCallToMemberFunction - Build a call to a member
7578/// function. MemExpr is the expression that refers to the member
7579/// function (and includes the object parameter), Args/NumArgs are the
7580/// arguments to the function call (not including the object
7581/// parameter). The caller needs to validate that the member
7582/// expression refers to a member function or an overloaded member
7583/// function.
John McCalldadc5752010-08-24 06:29:42 +00007584ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007585Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7586 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007587 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007588 // Dig out the member expression. This holds both the object
7589 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007590 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7591
John McCall10eae182009-11-30 22:42:35 +00007592 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007593 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007594 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007595 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007596 if (isa<MemberExpr>(NakedMemExpr)) {
7597 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007598 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007599 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007600 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007601 } else {
7602 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007603 Qualifier = UnresExpr->getQualifier();
7604
John McCall6e9f8f62009-12-03 04:06:58 +00007605 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007606
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007607 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007608 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007609
John McCall2d74de92009-12-01 22:10:20 +00007610 // FIXME: avoid copy.
7611 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7612 if (UnresExpr->hasExplicitTemplateArgs()) {
7613 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7614 TemplateArgs = &TemplateArgsBuffer;
7615 }
7616
John McCall10eae182009-11-30 22:42:35 +00007617 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7618 E = UnresExpr->decls_end(); I != E; ++I) {
7619
John McCall6e9f8f62009-12-03 04:06:58 +00007620 NamedDecl *Func = *I;
7621 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7622 if (isa<UsingShadowDecl>(Func))
7623 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7624
John McCall10eae182009-11-30 22:42:35 +00007625 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007626 // If explicit template arguments were provided, we can't call a
7627 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007628 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007629 continue;
7630
John McCalla0296f72010-03-19 07:35:19 +00007631 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007632 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007633 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007634 } else {
John McCall10eae182009-11-30 22:42:35 +00007635 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007636 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007637 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007638 CandidateSet,
7639 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007640 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007641 }
Mike Stump11289f42009-09-09 15:08:12 +00007642
John McCall10eae182009-11-30 22:42:35 +00007643 DeclarationName DeclName = UnresExpr->getMemberName();
7644
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007645 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007646 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7647 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007648 case OR_Success:
7649 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007650 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007651 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007652 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007653 break;
7654
7655 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007656 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007657 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007658 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007659 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007660 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007661 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007662
7663 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007664 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007665 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007666 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007667 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007668 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007669
7670 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007671 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007672 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007673 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007674 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007675 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007676 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007677 }
7678
John McCall16df1e52010-03-30 21:47:33 +00007679 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007680
John McCall2d74de92009-12-01 22:10:20 +00007681 // If overload resolution picked a static member, build a
7682 // non-member call based on that function.
7683 if (Method->isStatic()) {
7684 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7685 Args, NumArgs, RParenLoc);
7686 }
7687
John McCall10eae182009-11-30 22:42:35 +00007688 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007689 }
7690
7691 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007692 CXXMemberCallExpr *TheCall =
7693 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7694 Method->getCallResultType(),
7695 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007696
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007697 // Check for a valid return type.
7698 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007699 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007700 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007701
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007702 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007703 // We only need to do this if there was actually an overload; otherwise
7704 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007705 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007706 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007707 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7708 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007709 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007710 MemExpr->setBase(ObjectArg);
7711
7712 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007713 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007714 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007715 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007716 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007717
John McCallb268a282010-08-23 23:25:46 +00007718 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007719 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007720
John McCallb268a282010-08-23 23:25:46 +00007721 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007722}
7723
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007724/// BuildCallToObjectOfClassType - Build a call to an object of class
7725/// type (C++ [over.call.object]), which can end up invoking an
7726/// overloaded function call operator (@c operator()) or performing a
7727/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007728ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007729Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007730 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007731 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007732 SourceLocation RParenLoc) {
7733 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007734 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007735
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007736 // C++ [over.call.object]p1:
7737 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007738 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007739 // candidate functions includes at least the function call
7740 // operators of T. The function call operators of T are obtained by
7741 // ordinary lookup of the name operator() in the context of
7742 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007743 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007744 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007745
7746 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007747 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007748 << Object->getSourceRange()))
7749 return true;
7750
John McCall27b18f82009-11-17 02:14:36 +00007751 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7752 LookupQualifiedName(R, Record->getDecl());
7753 R.suppressDiagnostics();
7754
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007755 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007756 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007757 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007758 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007759 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007760 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007761
Douglas Gregorab7897a2008-11-19 22:57:39 +00007762 // C++ [over.call.object]p2:
7763 // In addition, for each conversion function declared in T of the
7764 // form
7765 //
7766 // operator conversion-type-id () cv-qualifier;
7767 //
7768 // where cv-qualifier is the same cv-qualification as, or a
7769 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007770 // denotes the type "pointer to function of (P1,...,Pn) returning
7771 // R", or the type "reference to pointer to function of
7772 // (P1,...,Pn) returning R", or the type "reference to function
7773 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007774 // is also considered as a candidate function. Similarly,
7775 // surrogate call functions are added to the set of candidate
7776 // functions for each conversion function declared in an
7777 // accessible base class provided the function is not hidden
7778 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007779 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007780 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007781 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007782 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007783 NamedDecl *D = *I;
7784 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7785 if (isa<UsingShadowDecl>(D))
7786 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7787
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007788 // Skip over templated conversion functions; they aren't
7789 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007790 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007791 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007792
John McCall6e9f8f62009-12-03 04:06:58 +00007793 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007794
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007795 // Strip the reference type (if any) and then the pointer type (if
7796 // any) to get down to what might be a function type.
7797 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7798 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7799 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007800
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007801 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007802 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007803 Object->getType(), Args, NumArgs,
7804 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007805 }
Mike Stump11289f42009-09-09 15:08:12 +00007806
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007807 // Perform overload resolution.
7808 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007809 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7810 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007811 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007812 // Overload resolution succeeded; we'll build the appropriate call
7813 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007814 break;
7815
7816 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007817 if (CandidateSet.empty())
7818 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7819 << Object->getType() << /*call*/ 1
7820 << Object->getSourceRange();
7821 else
7822 Diag(Object->getSourceRange().getBegin(),
7823 diag::err_ovl_no_viable_object_call)
7824 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007825 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007826 break;
7827
7828 case OR_Ambiguous:
7829 Diag(Object->getSourceRange().getBegin(),
7830 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007831 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007832 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007833 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007834
7835 case OR_Deleted:
7836 Diag(Object->getSourceRange().getBegin(),
7837 diag::err_ovl_deleted_object_call)
7838 << Best->Function->isDeleted()
7839 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007840 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007841 break;
Mike Stump11289f42009-09-09 15:08:12 +00007842 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007843
Douglas Gregorb412e172010-07-25 18:17:45 +00007844 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007845 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007846
Douglas Gregorab7897a2008-11-19 22:57:39 +00007847 if (Best->Function == 0) {
7848 // Since there is no function declaration, this is one of the
7849 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007850 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007851 = cast<CXXConversionDecl>(
7852 Best->Conversions[0].UserDefined.ConversionFunction);
7853
John McCalla0296f72010-03-19 07:35:19 +00007854 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007855 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007856
Douglas Gregorab7897a2008-11-19 22:57:39 +00007857 // We selected one of the surrogate functions that converts the
7858 // object parameter to a function pointer. Perform the conversion
7859 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007860
7861 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007862 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007863 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7864 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007865
John McCallfaf5fb42010-08-26 23:41:50 +00007866 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007867 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007868 }
7869
John McCalla0296f72010-03-19 07:35:19 +00007870 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007871 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007872
Douglas Gregorab7897a2008-11-19 22:57:39 +00007873 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7874 // that calls this method, using Object for the implicit object
7875 // parameter and passing along the remaining arguments.
7876 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007877 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007878
7879 unsigned NumArgsInProto = Proto->getNumArgs();
7880 unsigned NumArgsToCheck = NumArgs;
7881
7882 // Build the full argument list for the method call (the
7883 // implicit object parameter is placed at the beginning of the
7884 // list).
7885 Expr **MethodArgs;
7886 if (NumArgs < NumArgsInProto) {
7887 NumArgsToCheck = NumArgsInProto;
7888 MethodArgs = new Expr*[NumArgsInProto + 1];
7889 } else {
7890 MethodArgs = new Expr*[NumArgs + 1];
7891 }
7892 MethodArgs[0] = Object;
7893 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7894 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007895
7896 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007897 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007898 UsualUnaryConversions(NewFn);
7899
7900 // Once we've built TheCall, all of the expressions are properly
7901 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007902 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007903 CXXOperatorCallExpr *TheCall =
7904 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7905 MethodArgs, NumArgs + 1,
7906 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007907 delete [] MethodArgs;
7908
John McCallb268a282010-08-23 23:25:46 +00007909 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007910 Method))
7911 return true;
7912
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007913 // We may have default arguments. If so, we need to allocate more
7914 // slots in the call for them.
7915 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007916 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007917 else if (NumArgs > NumArgsInProto)
7918 NumArgsToCheck = NumArgsInProto;
7919
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007920 bool IsError = false;
7921
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007922 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007923 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007924 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007925 TheCall->setArg(0, Object);
7926
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007927
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007928 // Check the argument types.
7929 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007930 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007931 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007932 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007933
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007934 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007935
John McCalldadc5752010-08-24 06:29:42 +00007936 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007937 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007938 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007939 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007940 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007941
7942 IsError |= InputInit.isInvalid();
7943 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007944 } else {
John McCalldadc5752010-08-24 06:29:42 +00007945 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007946 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7947 if (DefArg.isInvalid()) {
7948 IsError = true;
7949 break;
7950 }
7951
7952 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007953 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007954
7955 TheCall->setArg(i + 1, Arg);
7956 }
7957
7958 // If this is a variadic call, handle args passed through "...".
7959 if (Proto->isVariadic()) {
7960 // Promote the arguments (C99 6.5.2.2p7).
7961 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7962 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007963 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007964 TheCall->setArg(i + 1, Arg);
7965 }
7966 }
7967
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007968 if (IsError) return true;
7969
John McCallb268a282010-08-23 23:25:46 +00007970 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007971 return true;
7972
John McCalle172be52010-08-24 06:09:16 +00007973 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007974}
7975
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007976/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007977/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007978/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007979ExprResult
John McCallb268a282010-08-23 23:25:46 +00007980Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007981 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007982
John McCallbc077cf2010-02-08 23:07:23 +00007983 SourceLocation Loc = Base->getExprLoc();
7984
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007985 // C++ [over.ref]p1:
7986 //
7987 // [...] An expression x->m is interpreted as (x.operator->())->m
7988 // for a class object x of type T if T::operator->() exists and if
7989 // the operator is selected as the best match function by the
7990 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007991 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007992 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007993 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007994
John McCallbc077cf2010-02-08 23:07:23 +00007995 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007996 PDiag(diag::err_typecheck_incomplete_tag)
7997 << Base->getSourceRange()))
7998 return ExprError();
7999
John McCall27b18f82009-11-17 02:14:36 +00008000 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8001 LookupQualifiedName(R, BaseRecord->getDecl());
8002 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008003
8004 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008005 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008006 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008007 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008008 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008009
8010 // Perform overload resolution.
8011 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008012 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008013 case OR_Success:
8014 // Overload resolution succeeded; we'll build the call below.
8015 break;
8016
8017 case OR_No_Viable_Function:
8018 if (CandidateSet.empty())
8019 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008020 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008021 else
8022 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008023 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008024 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008025 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008026
8027 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008028 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8029 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008030 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008031 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008032
8033 case OR_Deleted:
8034 Diag(OpLoc, diag::err_ovl_deleted_oper)
8035 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008036 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008037 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008038 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008039 }
8040
John McCalla0296f72010-03-19 07:35:19 +00008041 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008042 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008043
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008044 // Convert the object parameter.
8045 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008046 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8047 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008048 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008049
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008050 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00008051 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
8052 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008053 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008054
Douglas Gregor603d81b2010-07-13 08:18:22 +00008055 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00008056 CXXOperatorCallExpr *TheCall =
8057 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
8058 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008059
John McCallb268a282010-08-23 23:25:46 +00008060 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008061 Method))
8062 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008063 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008064}
8065
Douglas Gregorcd695e52008-11-10 20:40:00 +00008066/// FixOverloadedFunctionReference - E is an expression that refers to
8067/// a C++ overloaded function (possibly with some parentheses and
8068/// perhaps a '&' around it). We have resolved the overloaded function
8069/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008070/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008071Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008072 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008073 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008074 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8075 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008076 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008077 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008078
8079 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8080 }
8081
8082 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008083 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8084 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008085 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008086 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008087 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008088 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008089 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008090 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008091
John McCallcf142162010-08-07 06:22:56 +00008092 return ImplicitCastExpr::Create(Context, ICE->getType(),
8093 ICE->getCastKind(),
8094 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008095 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008096 }
8097
8098 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008099 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008100 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008101 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8102 if (Method->isStatic()) {
8103 // Do nothing: static member functions aren't any different
8104 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008105 } else {
John McCalle66edc12009-11-24 19:00:30 +00008106 // Fix the sub expression, which really has to be an
8107 // UnresolvedLookupExpr holding an overloaded member function
8108 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008109 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8110 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008111 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008112 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008113
John McCalld14a8642009-11-21 08:51:07 +00008114 assert(isa<DeclRefExpr>(SubExpr)
8115 && "fixed to something other than a decl ref");
8116 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8117 && "fixed to a member ref with no nested name qualifier");
8118
8119 // We have taken the address of a pointer to member
8120 // function. Perform the computation here so that we get the
8121 // appropriate pointer to member type.
8122 QualType ClassType
8123 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8124 QualType MemPtrType
8125 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8126
John McCalle3027922010-08-25 11:45:40 +00008127 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCalld14a8642009-11-21 08:51:07 +00008128 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008129 }
8130 }
John McCall16df1e52010-03-30 21:47:33 +00008131 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8132 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008133 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008134 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008135
John McCalle3027922010-08-25 11:45:40 +00008136 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008137 Context.getPointerType(SubExpr->getType()),
8138 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008139 }
John McCalld14a8642009-11-21 08:51:07 +00008140
8141 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008142 // FIXME: avoid copy.
8143 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008144 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008145 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8146 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008147 }
8148
John McCalld14a8642009-11-21 08:51:07 +00008149 return DeclRefExpr::Create(Context,
8150 ULE->getQualifier(),
8151 ULE->getQualifierRange(),
8152 Fn,
8153 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008154 Fn->getType(),
8155 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008156 }
8157
John McCall10eae182009-11-30 22:42:35 +00008158 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008159 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008160 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8161 if (MemExpr->hasExplicitTemplateArgs()) {
8162 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8163 TemplateArgs = &TemplateArgsBuffer;
8164 }
John McCall6b51f282009-11-23 01:53:49 +00008165
John McCall2d74de92009-12-01 22:10:20 +00008166 Expr *Base;
8167
8168 // If we're filling in
8169 if (MemExpr->isImplicitAccess()) {
8170 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8171 return DeclRefExpr::Create(Context,
8172 MemExpr->getQualifier(),
8173 MemExpr->getQualifierRange(),
8174 Fn,
8175 MemExpr->getMemberLoc(),
8176 Fn->getType(),
8177 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008178 } else {
8179 SourceLocation Loc = MemExpr->getMemberLoc();
8180 if (MemExpr->getQualifier())
8181 Loc = MemExpr->getQualifierRange().getBegin();
8182 Base = new (Context) CXXThisExpr(Loc,
8183 MemExpr->getBaseType(),
8184 /*isImplicit=*/true);
8185 }
John McCall2d74de92009-12-01 22:10:20 +00008186 } else
John McCallc3007a22010-10-26 07:05:15 +00008187 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008188
8189 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008190 MemExpr->isArrow(),
8191 MemExpr->getQualifier(),
8192 MemExpr->getQualifierRange(),
8193 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008194 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008195 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008196 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008197 Fn->getType());
8198 }
8199
John McCallc3007a22010-10-26 07:05:15 +00008200 llvm_unreachable("Invalid reference to overloaded function");
8201 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008202}
8203
John McCalldadc5752010-08-24 06:29:42 +00008204ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8205 DeclAccessPair Found,
8206 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008207 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008208}
8209
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008210} // end namespace clang