blob: 9fb53c6a182f26693c89e3161db77068d98a9a8d [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() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000193 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
194 return true;
195
196 return false;
197}
198
Douglas Gregor5c407d92008-10-23 00:40:37 +0000199/// isPointerConversionToVoidPointer - Determines whether this
200/// conversion is a conversion of a pointer to a void pointer. This is
201/// used as part of the ranking of standard conversion sequences (C++
202/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000203bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000204StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000205isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000206 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000207 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000208
209 // Note that FromType has not necessarily been transformed by the
210 // array-to-pointer implicit conversion, so check for its presence
211 // and redo the conversion to get a pointer.
212 if (First == ICK_Array_To_Pointer)
213 FromType = Context.getArrayDecayedType(FromType);
214
John McCall75851b12010-10-26 06:40:27 +0000215 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000216 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000217 return ToPtrType->getPointeeType()->isVoidType();
218
219 return false;
220}
221
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// DebugPrint - Print this standard conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000225 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 bool PrintedSomething = false;
227 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000228 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 PrintedSomething = true;
230 }
231
232 if (Second != ICK_Identity) {
233 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000234 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000235 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000236 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000237
238 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000240 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000241 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000242 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000243 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000244 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000245 PrintedSomething = true;
246 }
247
248 if (Third != ICK_Identity) {
249 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000253 PrintedSomething = true;
254 }
255
256 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000257 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000258 }
259}
260
261/// DebugPrint - Print this user-defined conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 if (Before.First || Before.Second || Before.Third) {
266 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000268 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000269 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000270 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000272 After.DebugPrint();
273 }
274}
275
276/// DebugPrint - Print this implicit conversion sequence to standard
277/// error. Useful for debugging overloading issues.
278void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000280 switch (ConversionKind) {
281 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000282 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000283 Standard.DebugPrint();
284 break;
285 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000286 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287 UserDefined.DebugPrint();
288 break;
289 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000290 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000291 break;
John McCall0d1da222010-01-12 00:44:57 +0000292 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000294 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000295 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 break;
298 }
299
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000300 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301}
302
John McCall0d1da222010-01-12 00:44:57 +0000303void AmbiguousConversionSequence::construct() {
304 new (&conversions()) ConversionSet();
305}
306
307void AmbiguousConversionSequence::destruct() {
308 conversions().~ConversionSet();
309}
310
311void
312AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
313 FromTypePtr = O.FromTypePtr;
314 ToTypePtr = O.ToTypePtr;
315 new (&conversions()) ConversionSet(O.conversions());
316}
317
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000318namespace {
319 // Structure used by OverloadCandidate::DeductionFailureInfo to store
320 // template parameter and template argument information.
321 struct DFIParamWithArguments {
322 TemplateParameter Param;
323 TemplateArgument FirstArg;
324 TemplateArgument SecondArg;
325 };
326}
327
328/// \brief Convert from Sema's representation of template deduction information
329/// to the form used in overload-candidate information.
330OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000331static MakeDeductionFailureInfo(ASTContext &Context,
332 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000333 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000334 OverloadCandidate::DeductionFailureInfo Result;
335 Result.Result = static_cast<unsigned>(TDK);
336 Result.Data = 0;
337 switch (TDK) {
338 case Sema::TDK_Success:
339 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000340 case Sema::TDK_TooManyArguments:
341 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000342 break;
343
344 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000345 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346 Result.Data = Info.Param.getOpaqueValue();
347 break;
348
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000349 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000350 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000351 // FIXME: Should allocate from normal heap so that we can free this later.
352 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 Saved->Param = Info.Param;
354 Saved->FirstArg = Info.FirstArg;
355 Saved->SecondArg = Info.SecondArg;
356 Result.Data = Saved;
357 break;
358 }
359
360 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000361 Result.Data = Info.take();
362 break;
363
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_FailedOverloadResolution:
366 break;
367 }
368
369 return Result;
370}
John McCall0d1da222010-01-12 00:44:57 +0000371
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372void OverloadCandidate::DeductionFailureInfo::Destroy() {
373 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
376 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000377 case Sema::TDK_TooManyArguments:
378 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 break;
381
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000382 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000384 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 Data = 0;
386 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000387
388 case Sema::TDK_SubstitutionFailure:
389 // FIXME: Destroy the template arugment list?
390 Data = 0;
391 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392
Douglas Gregor461761d2010-05-08 18:20:53 +0000393 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 case Sema::TDK_FailedOverloadResolution:
396 break;
397 }
398}
399
400TemplateParameter
401OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
402 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
403 case Sema::TDK_Success:
404 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000407 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 return TemplateParameter();
409
410 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000411 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000412 return TemplateParameter::getFromOpaqueValue(Data);
413
414 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000415 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000416 return static_cast<DFIParamWithArguments*>(Data)->Param;
417
418 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 case Sema::TDK_FailedOverloadResolution:
421 break;
422 }
423
424 return TemplateParameter();
425}
Douglas Gregord09efd42010-05-08 20:07:26 +0000426
427TemplateArgumentList *
428OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
429 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
430 case Sema::TDK_Success:
431 case Sema::TDK_InstantiationDepth:
432 case Sema::TDK_TooManyArguments:
433 case Sema::TDK_TooFewArguments:
434 case Sema::TDK_Incomplete:
435 case Sema::TDK_InvalidExplicitArguments:
436 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000437 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000438 return 0;
439
440 case Sema::TDK_SubstitutionFailure:
441 return static_cast<TemplateArgumentList*>(Data);
442
443 // Unhandled
444 case Sema::TDK_NonDeducedMismatch:
445 case Sema::TDK_FailedOverloadResolution:
446 break;
447 }
448
449 return 0;
450}
451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
453 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
454 case Sema::TDK_Success:
455 case Sema::TDK_InstantiationDepth:
456 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000457 case Sema::TDK_TooManyArguments:
458 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000459 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000460 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 return 0;
462
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000463 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000464 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000465 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
466
Douglas Gregor461761d2010-05-08 18:20:53 +0000467 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000469 case Sema::TDK_FailedOverloadResolution:
470 break;
471 }
472
473 return 0;
474}
475
476const TemplateArgument *
477OverloadCandidate::DeductionFailureInfo::getSecondArg() {
478 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
479 case Sema::TDK_Success:
480 case Sema::TDK_InstantiationDepth:
481 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000482 case Sema::TDK_TooManyArguments:
483 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000484 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000485 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000486 return 0;
487
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000488 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000489 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000490 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
491
Douglas Gregor461761d2010-05-08 18:20:53 +0000492 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000493 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494 case Sema::TDK_FailedOverloadResolution:
495 break;
496 }
497
498 return 0;
499}
500
501void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 inherited::clear();
503 Functions.clear();
504}
505
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000507// overload of the declarations in Old. This routine returns false if
508// New and Old cannot be overloaded, e.g., if New has the same
509// signature as some function in Old (C++ 1.3.10) or if the Old
510// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000511// it does return false, MatchedDecl will point to the decl that New
512// cannot be overloaded with. This decl may be a UsingShadowDecl on
513// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514//
515// Example: Given the following input:
516//
517// void f(int, float); // #1
518// void f(int, int); // #2
519// int f(int, int); // #3
520//
521// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000522// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000523//
John McCall3d988d92009-12-02 08:47:38 +0000524// When we process #2, Old contains only the FunctionDecl for #1. By
525// comparing the parameter types, we see that #1 and #2 are overloaded
526// (since they have different signatures), so this routine returns
527// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528//
John McCall3d988d92009-12-02 08:47:38 +0000529// When we process #3, Old is an overload set containing #1 and #2. We
530// compare the signatures of #3 to #1 (they're overloaded, so we do
531// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
532// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533// signature), IsOverload returns false and MatchedDecl will be set to
534// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000535//
536// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
537// into a class by a using declaration. The rules for whether to hide
538// shadow declarations ignore some properties which otherwise figure
539// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000540Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000541Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
542 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000543 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000544 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 NamedDecl *OldD = *I;
546
547 bool OldIsUsingDecl = false;
548 if (isa<UsingShadowDecl>(OldD)) {
549 OldIsUsingDecl = true;
550
551 // We can always introduce two using declarations into the same
552 // context, even if they have identical signatures.
553 if (NewIsUsingDecl) continue;
554
555 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
556 }
557
558 // If either declaration was introduced by a using declaration,
559 // we'll need to use slightly different rules for matching.
560 // Essentially, these rules are the normal rules, except that
561 // function templates hide function templates with different
562 // return types or template parameter lists.
563 bool UseMemberUsingDeclRules =
564 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
565
John McCall3d988d92009-12-02 08:47:38 +0000566 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000567 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
568 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
569 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
570 continue;
571 }
572
John McCalldaa3d6b2009-12-09 03:35:25 +0000573 Match = *I;
574 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000575 }
John McCall3d988d92009-12-02 08:47:38 +0000576 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000577 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
578 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
579 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
580 continue;
581 }
582
John McCalldaa3d6b2009-12-09 03:35:25 +0000583 Match = *I;
584 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000585 }
John McCall84d87672009-12-10 09:41:52 +0000586 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
587 // We can overload with these, which can show up when doing
588 // redeclaration checks for UsingDecls.
589 assert(Old.getLookupKind() == LookupUsingDeclName);
590 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
591 // Optimistically assume that an unresolved using decl will
592 // overload; if it doesn't, we'll have to diagnose during
593 // template instantiation.
594 } else {
John McCall1f82f242009-11-18 22:49:29 +0000595 // (C++ 13p1):
596 // Only function declarations can be overloaded; object and type
597 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000598 Match = *I;
599 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000600 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000601 }
John McCall1f82f242009-11-18 22:49:29 +0000602
John McCalldaa3d6b2009-12-09 03:35:25 +0000603 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000604}
605
John McCalle9cccd82010-06-16 08:42:20 +0000606bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
607 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000608 // If both of the functions are extern "C", then they are not
609 // overloads.
610 if (Old->isExternC() && New->isExternC())
611 return false;
612
John McCall1f82f242009-11-18 22:49:29 +0000613 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
614 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
615
616 // C++ [temp.fct]p2:
617 // A function template can be overloaded with other function templates
618 // and with normal (non-template) functions.
619 if ((OldTemplate == 0) != (NewTemplate == 0))
620 return true;
621
622 // Is the function New an overload of the function Old?
623 QualType OldQType = Context.getCanonicalType(Old->getType());
624 QualType NewQType = Context.getCanonicalType(New->getType());
625
626 // Compare the signatures (C++ 1.3.10) of the two functions to
627 // determine whether they are overloads. If we find any mismatch
628 // in the signature, they are overloads.
629
630 // If either of these functions is a K&R-style function (no
631 // prototype), then we consider them to have matching signatures.
632 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
633 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
634 return false;
635
636 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
637 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
638
639 // The signature of a function includes the types of its
640 // parameters (C++ 1.3.10), which includes the presence or absence
641 // of the ellipsis; see C++ DR 357).
642 if (OldQType != NewQType &&
643 (OldType->getNumArgs() != NewType->getNumArgs() ||
644 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000645 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000646 return true;
647
648 // C++ [temp.over.link]p4:
649 // The signature of a function template consists of its function
650 // signature, its return type and its template parameter list. The names
651 // of the template parameters are significant only for establishing the
652 // relationship between the template parameters and the rest of the
653 // signature.
654 //
655 // We check the return type and template parameter lists for function
656 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000657 //
658 // However, we don't consider either of these when deciding whether
659 // a member introduced by a shadow declaration is hidden.
660 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000661 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
662 OldTemplate->getTemplateParameters(),
663 false, TPL_TemplateMatch) ||
664 OldType->getResultType() != NewType->getResultType()))
665 return true;
666
667 // If the function is a class member, its signature includes the
668 // cv-qualifiers (if any) on the function itself.
669 //
670 // As part of this, also check whether one of the member functions
671 // is static, in which case they are not overloads (C++
672 // 13.1p2). While not part of the definition of the signature,
673 // this check is important to determine whether these functions
674 // can be overloaded.
675 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
676 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
677 if (OldMethod && NewMethod &&
678 !OldMethod->isStatic() && !NewMethod->isStatic() &&
679 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
680 return true;
681
682 // The signatures match; this is not an overload.
683 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000684}
685
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000686/// TryImplicitConversion - Attempt to perform an implicit conversion
687/// from the given expression (Expr) to the given type (ToType). This
688/// function returns an implicit conversion sequence that can be used
689/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000690///
691/// void f(float f);
692/// void g(int i) { f(i); }
693///
694/// this routine would produce an implicit conversion sequence to
695/// describe the initialization of f from i, which will be a standard
696/// conversion sequence containing an lvalue-to-rvalue conversion (C++
697/// 4.1) followed by a floating-integral conversion (C++ 4.9).
698//
699/// Note that this routine only determines how the conversion can be
700/// performed; it does not actually perform the conversion. As such,
701/// it will not produce any diagnostics if no conversion is available,
702/// but will instead return an implicit conversion sequence of kind
703/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000704///
705/// If @p SuppressUserConversions, then user-defined conversions are
706/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000707/// If @p AllowExplicit, then explicit user-defined conversions are
708/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000709static ImplicitConversionSequence
710TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
711 bool SuppressUserConversions,
712 bool AllowExplicit,
713 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000715 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
716 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000717 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000718 return ICS;
719 }
720
John McCall5c32be02010-08-24 20:38:10 +0000721 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000722 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000723 return ICS;
724 }
725
Douglas Gregor836a7e82010-08-11 02:15:33 +0000726 // C++ [over.ics.user]p4:
727 // A conversion of an expression of class type to the same class
728 // type is given Exact Match rank, and a conversion of an
729 // expression of class type to a base class of that type is
730 // given Conversion rank, in spite of the fact that a copy/move
731 // constructor (i.e., a user-defined conversion function) is
732 // called for those cases.
733 QualType FromType = From->getType();
734 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000735 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
736 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000737 ICS.setStandard();
738 ICS.Standard.setAsIdentityConversion();
739 ICS.Standard.setFromType(FromType);
740 ICS.Standard.setAllToTypes(ToType);
741
742 // We don't actually check at this point whether there is a valid
743 // copy/move constructor, since overloading just assumes that it
744 // exists. When we actually perform initialization, we'll find the
745 // appropriate constructor to copy the returned object, if needed.
746 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000747
Douglas Gregor5ab11652010-04-17 22:01:05 +0000748 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000749 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000750 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000751
752 return ICS;
753 }
754
755 if (SuppressUserConversions) {
756 // We're not in the case above, so there is no conversion that
757 // we can perform.
758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000759 return ICS;
760 }
761
762 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000763 OverloadCandidateSet Conversions(From->getExprLoc());
764 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000765 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000766 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000767
768 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000769 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000770 // C++ [over.ics.user]p4:
771 // A conversion of an expression of class type to the same class
772 // type is given Exact Match rank, and a conversion of an
773 // expression of class type to a base class of that type is
774 // given Conversion rank, in spite of the fact that a copy
775 // constructor (i.e., a user-defined conversion function) is
776 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000777 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000778 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000779 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000780 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
781 QualType ToCanon
782 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000783 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000784 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000785 // Turn this into a "standard" conversion sequence, so that it
786 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000787 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000788 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000789 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000790 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000791 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000792 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000793 ICS.Standard.Second = ICK_Derived_To_Base;
794 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000795 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000796
797 // C++ [over.best.ics]p4:
798 // However, when considering the argument of a user-defined
799 // conversion function that is a candidate by 13.3.1.3 when
800 // invoked for the copying of the temporary in the second step
801 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
802 // 13.3.1.6 in all cases, only standard conversion sequences and
803 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000804 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000805 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000806 }
John McCalle8c8cd22010-01-13 22:30:33 +0000807 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000808 ICS.setAmbiguous();
809 ICS.Ambiguous.setFromType(From->getType());
810 ICS.Ambiguous.setToType(ToType);
811 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
812 Cand != Conversions.end(); ++Cand)
813 if (Cand->Viable)
814 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000815 } else {
John McCall65eb8792010-02-25 01:37:24 +0000816 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000817 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000818
819 return ICS;
820}
821
John McCall5c32be02010-08-24 20:38:10 +0000822bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
823 const InitializedEntity &Entity,
824 Expr *Initializer,
825 bool SuppressUserConversions,
826 bool AllowExplicitConversions,
827 bool InOverloadResolution) {
828 ImplicitConversionSequence ICS
829 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
830 SuppressUserConversions,
831 AllowExplicitConversions,
832 InOverloadResolution);
833 if (ICS.isBad()) return true;
834
835 // Perform the actual conversion.
836 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
837 return false;
838}
839
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000840/// PerformImplicitConversion - Perform an implicit conversion of the
841/// expression From to the type ToType. Returns true if there was an
842/// error, false otherwise. The expression From is replaced with the
843/// converted expression. Flavor is the kind of conversion we're
844/// performing, used in the error message. If @p AllowExplicit,
845/// explicit user-defined conversions are permitted.
846bool
847Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
848 AssignmentAction Action, bool AllowExplicit) {
849 ImplicitConversionSequence ICS;
850 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
851}
852
853bool
854Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
855 AssignmentAction Action, bool AllowExplicit,
856 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000857 ICS = clang::TryImplicitConversion(*this, From, ToType,
858 /*SuppressUserConversions=*/false,
859 AllowExplicit,
860 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000861 return PerformImplicitConversion(From, ToType, ICS, Action);
862}
863
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000864/// \brief Determine whether the conversion from FromType to ToType is a valid
865/// conversion that strips "noreturn" off the nested function type.
866static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
867 QualType ToType, QualType &ResultTy) {
868 if (Context.hasSameUnqualifiedType(FromType, ToType))
869 return false;
870
871 // Strip the noreturn off the type we're converting from; noreturn can
872 // safely be removed.
873 FromType = Context.getNoReturnType(FromType, false);
874 if (!Context.hasSameUnqualifiedType(FromType, ToType))
875 return false;
876
877 ResultTy = FromType;
878 return true;
879}
Douglas Gregor46188682010-05-18 22:42:18 +0000880
881/// \brief Determine whether the conversion from FromType to ToType is a valid
882/// vector conversion.
883///
884/// \param ICK Will be set to the vector conversion kind, if this is a vector
885/// conversion.
886static bool IsVectorConversion(ASTContext &Context, QualType FromType,
887 QualType ToType, ImplicitConversionKind &ICK) {
888 // We need at least one of these types to be a vector type to have a vector
889 // conversion.
890 if (!ToType->isVectorType() && !FromType->isVectorType())
891 return false;
892
893 // Identical types require no conversions.
894 if (Context.hasSameUnqualifiedType(FromType, ToType))
895 return false;
896
897 // There are no conversions between extended vector types, only identity.
898 if (ToType->isExtVectorType()) {
899 // There are no conversions between extended vector types other than the
900 // identity conversion.
901 if (FromType->isExtVectorType())
902 return false;
903
904 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000905 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000906 ICK = ICK_Vector_Splat;
907 return true;
908 }
909 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000910
911 // We can perform the conversion between vector types in the following cases:
912 // 1)vector types are equivalent AltiVec and GCC vector types
913 // 2)lax vector conversions are permitted and the vector types are of the
914 // same size
915 if (ToType->isVectorType() && FromType->isVectorType()) {
916 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000917 (Context.getLangOptions().LaxVectorConversions &&
918 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000919 ICK = ICK_Vector_Conversion;
920 return true;
921 }
Douglas Gregor46188682010-05-18 22:42:18 +0000922 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000923
Douglas Gregor46188682010-05-18 22:42:18 +0000924 return false;
925}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000926
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000927/// IsStandardConversion - Determines whether there is a standard
928/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
929/// expression From to the type ToType. Standard conversion sequences
930/// only consider non-class types; for conversions that involve class
931/// types, use TryImplicitConversion. If a conversion exists, SCS will
932/// contain the standard conversion sequence required to perform this
933/// conversion and this routine will return true. Otherwise, this
934/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000935static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
936 bool InOverloadResolution,
937 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000939
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000940 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000941 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000942 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000943 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000944 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000945 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000946
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000947 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000948 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000949 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000950 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000951 return false;
952
Mike Stump11289f42009-09-09 15:08:12 +0000953 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000954 }
955
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956 // The first conversion can be an lvalue-to-rvalue conversion,
957 // array-to-pointer conversion, or function-to-pointer conversion
958 // (C++ 4p1).
959
John McCall5c32be02010-08-24 20:38:10 +0000960 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000961 DeclAccessPair AccessPair;
962 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000963 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
964 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000965 // We were able to resolve the address of the overloaded function,
966 // so we can convert to the type of that function.
967 FromType = Fn->getType();
968 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
969 if (!Method->isStatic()) {
970 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000971 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
972 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000973 }
974 }
975
976 // If the "from" expression takes the address of the overloaded
977 // function, update the type of the resulting expression accordingly.
978 if (FromType->getAs<FunctionType>())
979 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000980 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000981 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000982
983 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000984 assert(S.Context.hasSameType(FromType,
985 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +0000986 } else {
987 return false;
988 }
989 }
Mike Stump11289f42009-09-09 15:08:12 +0000990 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000991 // An lvalue (3.10) of a non-function, non-array type T can be
992 // converted to an rvalue.
John McCall5c32be02010-08-24 20:38:10 +0000993 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +0000994 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000995 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +0000996 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000997 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
999 // If T is a non-class type, the type of the rvalue is the
1000 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001001 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1002 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001003 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001004 } else if (FromType->isArrayType()) {
1005 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001006 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001007
1008 // An lvalue or rvalue of type "array of N T" or "array of unknown
1009 // bound of T" can be converted to an rvalue of type "pointer to
1010 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001011 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012
John McCall5c32be02010-08-24 20:38:10 +00001013 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001014 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001015 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001016
1017 // For the purpose of ranking in overload resolution
1018 // (13.3.3.1.1), this conversion is considered an
1019 // array-to-pointer conversion followed by a qualification
1020 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001021 SCS.Second = ICK_Identity;
1022 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001023 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001024 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025 }
Mike Stump12b8ce12009-08-04 21:02:39 +00001026 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1027 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001028 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001029
1030 // An lvalue of function type T can be converted to an rvalue of
1031 // type "pointer to T." The result is a pointer to the
1032 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001033 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001034 } else {
1035 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001036 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001038 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039
1040 // The second conversion can be an integral promotion, floating
1041 // point promotion, integral conversion, floating point conversion,
1042 // floating-integral conversion, pointer conversion,
1043 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044 // For overloading in C, this can also be a "compatible-type"
1045 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001046 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001047 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001048 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049 // The unqualified versions of the types are the same: there's no
1050 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001051 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001052 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001054 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001056 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001057 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001058 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001060 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001061 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001062 SCS.Second = ICK_Complex_Promotion;
1063 FromType = ToType.getUnqualifiedType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00001064 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001065 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001066 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001067 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001069 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1070 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001071 SCS.Second = ICK_Complex_Conversion;
1072 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001073 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1074 (ToType->isComplexType() && FromType->isArithmeticType())) {
1075 // Complex-real conversions (C99 6.3.1.7)
1076 SCS.Second = ICK_Complex_Real;
1077 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001078 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001079 // Floating point conversions (C++ 4.8).
1080 SCS.Second = ICK_Floating_Conversion;
1081 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001082 } else if ((FromType->isRealFloatingType() &&
John McCall5c32be02010-08-24 20:38:10 +00001083 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001084 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001085 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001086 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001087 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001088 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001089 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1090 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001091 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001092 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001093 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001094 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1095 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001096 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001097 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001098 } else if (ToType->isBooleanType() &&
1099 (FromType->isArithmeticType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001100 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001101 FromType->isBlockPointerType() ||
1102 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001103 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001104 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001105 SCS.Second = ICK_Boolean_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001106 FromType = S.Context.BoolTy;
1107 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001108 SCS.Second = SecondICK;
1109 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001110 } else if (!S.getLangOptions().CPlusPlus &&
1111 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001112 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001113 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001114 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001115 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001116 // Treat a conversion that strips "noreturn" as an identity conversion.
1117 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001118 } else {
1119 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001120 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001122 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001124 QualType CanonFrom;
1125 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001127 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001128 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001130 CanonFrom = S.Context.getCanonicalType(FromType);
1131 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 } else {
1133 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001134 SCS.Third = ICK_Identity;
1135
Mike Stump11289f42009-09-09 15:08:12 +00001136 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001137 // [...] Any difference in top-level cv-qualification is
1138 // subsumed by the initialization itself and does not constitute
1139 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001140 CanonFrom = S.Context.getCanonicalType(FromType);
1141 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001142 if (CanonFrom.getLocalUnqualifiedType()
1143 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001144 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1145 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001146 FromType = ToType;
1147 CanonFrom = CanonTo;
1148 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001150 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151
1152 // If we have not converted the argument type to the parameter type,
1153 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001154 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158}
1159
1160/// IsIntegralPromotion - Determines whether the conversion from the
1161/// expression From (whose potentially-adjusted type is FromType) to
1162/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1163/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001164bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001165 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001166 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001167 if (!To) {
1168 return false;
1169 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
1171 // An rvalue of type char, signed char, unsigned char, short int, or
1172 // unsigned short int can be converted to an rvalue of type int if
1173 // int can represent all the values of the source type; otherwise,
1174 // the source rvalue can be converted to an rvalue of type unsigned
1175 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001176 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1177 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001178 if (// We can promote any signed, promotable integer type to an int
1179 (FromType->isSignedIntegerType() ||
1180 // We can promote any unsigned integer type whose size is
1181 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001182 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001183 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001185 }
1186
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::UInt;
1188 }
1189
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001190 // C++0x [conv.prom]p3:
1191 // A prvalue of an unscoped enumeration type whose underlying type is not
1192 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1193 // following types that can represent all the values of the enumeration
1194 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1195 // unsigned int, long int, unsigned long int, long long int, or unsigned
1196 // long long int. If none of the types in that list can represent all the
1197 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1198 // type can be converted to an rvalue a prvalue of the extended integer type
1199 // with lowest integer conversion rank (4.13) greater than the rank of long
1200 // long in which all the values of the enumeration can be represented. If
1201 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001202 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1203 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1204 // provided for a scoped enumeration.
1205 if (FromEnumType->getDecl()->isScoped())
1206 return false;
1207
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001208 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001209 if (ToType->isIntegerType() &&
1210 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001211 return Context.hasSameUnqualifiedType(ToType,
1212 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001213 }
John McCall56774992009-12-09 09:09:27 +00001214
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001215 // C++0x [conv.prom]p2:
1216 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1217 // to an rvalue a prvalue of the first of the following types that can
1218 // represent all the values of its underlying type: int, unsigned int,
1219 // long int, unsigned long int, long long int, or unsigned long long int.
1220 // If none of the types in that list can represent all the values of its
1221 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1222 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1223 // type.
1224 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1225 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 // Determine whether the type we're converting from is signed or
1227 // unsigned.
1228 bool FromIsSigned;
1229 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001230
1231 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1232 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233
1234 // The types we'll try to promote to, in the appropriate
1235 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001236 QualType PromoteTypes[6] = {
1237 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001238 Context.LongTy, Context.UnsignedLongTy ,
1239 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001241 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001242 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1243 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001244 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1246 // We found the type that we can promote to. If this is the
1247 // type we wanted, we have a promotion. Otherwise, no
1248 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001249 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001250 }
1251 }
1252 }
1253
1254 // An rvalue for an integral bit-field (9.6) can be converted to an
1255 // rvalue of type int if int can represent all the values of the
1256 // bit-field; otherwise, it can be converted to unsigned int if
1257 // unsigned int can represent all the values of the bit-field. If
1258 // the bit-field is larger yet, no integral promotion applies to
1259 // it. If the bit-field has an enumerated type, it is treated as any
1260 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001261 // FIXME: We should delay checking of bit-fields until we actually perform the
1262 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001263 using llvm::APSInt;
1264 if (From)
1265 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001266 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001267 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001268 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1269 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1270 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001272 // Are we promoting to an int from a bitfield that fits in an int?
1273 if (BitWidth < ToSize ||
1274 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1275 return To->getKind() == BuiltinType::Int;
1276 }
Mike Stump11289f42009-09-09 15:08:12 +00001277
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001278 // Are we promoting to an unsigned int from an unsigned bitfield
1279 // that fits into an unsigned int?
1280 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1281 return To->getKind() == BuiltinType::UInt;
1282 }
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001284 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001285 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 // An rvalue of type bool can be converted to an rvalue of type int,
1289 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001290 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001291 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001292 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293
1294 return false;
1295}
1296
1297/// IsFloatingPointPromotion - Determines whether the conversion from
1298/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1299/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001300bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001301 /// An rvalue of type float can be converted to an rvalue of type
1302 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001303 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1304 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305 if (FromBuiltin->getKind() == BuiltinType::Float &&
1306 ToBuiltin->getKind() == BuiltinType::Double)
1307 return true;
1308
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001309 // C99 6.3.1.5p1:
1310 // When a float is promoted to double or long double, or a
1311 // double is promoted to long double [...].
1312 if (!getLangOptions().CPlusPlus &&
1313 (FromBuiltin->getKind() == BuiltinType::Float ||
1314 FromBuiltin->getKind() == BuiltinType::Double) &&
1315 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1316 return true;
1317 }
1318
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 return false;
1320}
1321
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001322/// \brief Determine if a conversion is a complex promotion.
1323///
1324/// A complex promotion is defined as a complex -> complex conversion
1325/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001326/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001327bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001328 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001329 if (!FromComplex)
1330 return false;
1331
John McCall9dd450b2009-09-21 23:43:11 +00001332 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001333 if (!ToComplex)
1334 return false;
1335
1336 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001337 ToComplex->getElementType()) ||
1338 IsIntegralPromotion(0, FromComplex->getElementType(),
1339 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001340}
1341
Douglas Gregor237f96c2008-11-26 23:31:11 +00001342/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1343/// the pointer type FromPtr to a pointer to type ToPointee, with the
1344/// same type qualifiers as FromPtr has on its pointee type. ToType,
1345/// if non-empty, will be a pointer to ToType that may or may not have
1346/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001347static QualType
1348BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001349 QualType ToPointee, QualType ToType,
1350 ASTContext &Context) {
1351 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1352 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001353 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001354
1355 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001356 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001357 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001358 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001359 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001360
1361 // Build a pointer to ToPointee. It has the right qualifiers
1362 // already.
1363 return Context.getPointerType(ToPointee);
1364 }
1365
1366 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001367 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001368 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1369 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001370}
1371
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001372/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1373/// the FromType, which is an objective-c pointer, to ToType, which may or may
1374/// not have the right set of qualifiers.
1375static QualType
1376BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1377 QualType ToType,
1378 ASTContext &Context) {
1379 QualType CanonFromType = Context.getCanonicalType(FromType);
1380 QualType CanonToType = Context.getCanonicalType(ToType);
1381 Qualifiers Quals = CanonFromType.getQualifiers();
1382
1383 // Exact qualifier match -> return the pointer type we're converting to.
1384 if (CanonToType.getLocalQualifiers() == Quals)
1385 return ToType;
1386
1387 // Just build a canonical type that has the right qualifiers.
1388 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1389}
1390
Mike Stump11289f42009-09-09 15:08:12 +00001391static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001392 bool InOverloadResolution,
1393 ASTContext &Context) {
1394 // Handle value-dependent integral null pointer constants correctly.
1395 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1396 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001397 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001398 return !InOverloadResolution;
1399
Douglas Gregor56751b52009-09-25 04:25:58 +00001400 return Expr->isNullPointerConstant(Context,
1401 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1402 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001403}
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405/// IsPointerConversion - Determines whether the conversion of the
1406/// expression From, which has the (possibly adjusted) type FromType,
1407/// can be converted to the type ToType via a pointer conversion (C++
1408/// 4.10). If so, returns true and places the converted type (that
1409/// might differ from ToType in its cv-qualifiers at some level) into
1410/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001411///
Douglas Gregora29dc052008-11-27 01:19:21 +00001412/// This routine also supports conversions to and from block pointers
1413/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1414/// pointers to interfaces. FIXME: Once we've determined the
1415/// appropriate overloading rules for Objective-C, we may want to
1416/// split the Objective-C checks into a different routine; however,
1417/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001418/// conversions, so for now they live here. IncompatibleObjC will be
1419/// set if the conversion is an allowed Objective-C conversion that
1420/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001422 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001423 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001424 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001425 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001426 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1427 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001428
Mike Stump11289f42009-09-09 15:08:12 +00001429 // Conversion from a null pointer constant to any Objective-C pointer type.
1430 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001431 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001432 ConvertedType = ToType;
1433 return true;
1434 }
1435
Douglas Gregor231d1c62008-11-27 00:15:41 +00001436 // Blocks: Block pointers can be converted to void*.
1437 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001438 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001439 ConvertedType = ToType;
1440 return true;
1441 }
1442 // Blocks: A null pointer constant can be converted to a block
1443 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001444 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001445 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001446 ConvertedType = ToType;
1447 return true;
1448 }
1449
Sebastian Redl576fd422009-05-10 18:38:11 +00001450 // If the left-hand-side is nullptr_t, the right side can be a null
1451 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001452 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001453 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001454 ConvertedType = ToType;
1455 return true;
1456 }
1457
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001458 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 if (!ToTypePtr)
1460 return false;
1461
1462 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001463 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001464 ConvertedType = ToType;
1465 return true;
1466 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001467
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001468 // Beyond this point, both types need to be pointers
1469 // , including objective-c pointers.
1470 QualType ToPointeeType = ToTypePtr->getPointeeType();
1471 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1472 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1473 ToType, Context);
1474 return true;
1475
1476 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001477 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001478 if (!FromTypePtr)
1479 return false;
1480
1481 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001482
Douglas Gregorfb640862010-08-18 21:25:30 +00001483 // If the unqualified pointee types are the same, this can't be a
1484 // pointer conversion, so don't do all of the work below.
1485 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1486 return false;
1487
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 // An rvalue of type "pointer to cv T," where T is an object type,
1489 // can be converted to an rvalue of type "pointer to cv void" (C++
1490 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001491 if (FromPointeeType->isIncompleteOrObjectType() &&
1492 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001493 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001494 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001495 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001496 return true;
1497 }
1498
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001499 // When we're overloading in C, we allow a special kind of pointer
1500 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001501 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001502 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001503 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001504 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001505 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001506 return true;
1507 }
1508
Douglas Gregor5c407d92008-10-23 00:40:37 +00001509 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001510 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001511 // An rvalue of type "pointer to cv D," where D is a class type,
1512 // can be converted to an rvalue of type "pointer to cv B," where
1513 // B is a base class (clause 10) of D. If B is an inaccessible
1514 // (clause 11) or ambiguous (10.2) base class of D, a program that
1515 // necessitates this conversion is ill-formed. The result of the
1516 // conversion is a pointer to the base class sub-object of the
1517 // derived class object. The null pointer value is converted to
1518 // the null pointer value of the destination type.
1519 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001520 // Note that we do not check for ambiguity or inaccessibility
1521 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001522 if (getLangOptions().CPlusPlus &&
1523 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001524 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001525 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001526 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001527 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001528 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001529 ToType, Context);
1530 return true;
1531 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001532
Douglas Gregora119f102008-12-19 19:13:09 +00001533 return false;
1534}
1535
1536/// isObjCPointerConversion - Determines whether this is an
1537/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1538/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001539bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001540 QualType& ConvertedType,
1541 bool &IncompatibleObjC) {
1542 if (!getLangOptions().ObjC1)
1543 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001544
Steve Naroff7cae42b2009-07-10 23:34:53 +00001545 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001546 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001547 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001548 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001549
Steve Naroff7cae42b2009-07-10 23:34:53 +00001550 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001551 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001552 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001553 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001554 ConvertedType = ToType;
1555 return true;
1556 }
1557 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001558 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001559 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001560 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001561 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001562 ConvertedType = ToType;
1563 return true;
1564 }
1565 // Objective C++: We're able to convert from a pointer to an
1566 // interface to a pointer to a different interface.
1567 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001568 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1569 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1570 if (getLangOptions().CPlusPlus && LHS && RHS &&
1571 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1572 FromObjCPtr->getPointeeType()))
1573 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001574 ConvertedType = ToType;
1575 return true;
1576 }
1577
1578 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1579 // Okay: this is some kind of implicit downcast of Objective-C
1580 // interfaces, which is permitted. However, we're going to
1581 // complain about it.
1582 IncompatibleObjC = true;
1583 ConvertedType = FromType;
1584 return true;
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001587 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001588 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001589 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001590 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001591 else if (const BlockPointerType *ToBlockPtr =
1592 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001593 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001594 // to a block pointer type.
1595 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1596 ConvertedType = ToType;
1597 return true;
1598 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001599 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001600 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001601 else if (FromType->getAs<BlockPointerType>() &&
1602 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1603 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001604 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001605 ConvertedType = ToType;
1606 return true;
1607 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001608 else
Douglas Gregora119f102008-12-19 19:13:09 +00001609 return false;
1610
Douglas Gregor033f56d2008-12-23 00:53:59 +00001611 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001612 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001613 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001614 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001615 FromPointeeType = FromBlockPtr->getPointeeType();
1616 else
Douglas Gregora119f102008-12-19 19:13:09 +00001617 return false;
1618
Douglas Gregora119f102008-12-19 19:13:09 +00001619 // If we have pointers to pointers, recursively check whether this
1620 // is an Objective-C conversion.
1621 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1622 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1623 IncompatibleObjC)) {
1624 // We always complain about this conversion.
1625 IncompatibleObjC = true;
1626 ConvertedType = ToType;
1627 return true;
1628 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001629 // Allow conversion of pointee being objective-c pointer to another one;
1630 // as in I* to id.
1631 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1632 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1633 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1634 IncompatibleObjC)) {
1635 ConvertedType = ToType;
1636 return true;
1637 }
1638
Douglas Gregor033f56d2008-12-23 00:53:59 +00001639 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001640 // differences in the argument and result types are in Objective-C
1641 // pointer conversions. If so, we permit the conversion (but
1642 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001643 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001644 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001646 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001647 if (FromFunctionType && ToFunctionType) {
1648 // If the function types are exactly the same, this isn't an
1649 // Objective-C pointer conversion.
1650 if (Context.getCanonicalType(FromPointeeType)
1651 == Context.getCanonicalType(ToPointeeType))
1652 return false;
1653
1654 // Perform the quick checks that will tell us whether these
1655 // function types are obviously different.
1656 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1657 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1658 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1659 return false;
1660
1661 bool HasObjCConversion = false;
1662 if (Context.getCanonicalType(FromFunctionType->getResultType())
1663 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1664 // Okay, the types match exactly. Nothing to do.
1665 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1666 ToFunctionType->getResultType(),
1667 ConvertedType, IncompatibleObjC)) {
1668 // Okay, we have an Objective-C pointer conversion.
1669 HasObjCConversion = true;
1670 } else {
1671 // Function types are too different. Abort.
1672 return false;
1673 }
Mike Stump11289f42009-09-09 15:08:12 +00001674
Douglas Gregora119f102008-12-19 19:13:09 +00001675 // Check argument types.
1676 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1677 ArgIdx != NumArgs; ++ArgIdx) {
1678 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1679 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1680 if (Context.getCanonicalType(FromArgType)
1681 == Context.getCanonicalType(ToArgType)) {
1682 // Okay, the types match exactly. Nothing to do.
1683 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1684 ConvertedType, IncompatibleObjC)) {
1685 // Okay, we have an Objective-C pointer conversion.
1686 HasObjCConversion = true;
1687 } else {
1688 // Argument types are too different. Abort.
1689 return false;
1690 }
1691 }
1692
1693 if (HasObjCConversion) {
1694 // We had an Objective-C conversion. Allow this pointer
1695 // conversion, but complain about it.
1696 ConvertedType = ToType;
1697 IncompatibleObjC = true;
1698 return true;
1699 }
1700 }
1701
Sebastian Redl72b597d2009-01-25 19:43:20 +00001702 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001704
1705/// FunctionArgTypesAreEqual - This routine checks two function proto types
1706/// for equlity of their argument types. Caller has already checked that
1707/// they have same number of arguments. This routine assumes that Objective-C
1708/// pointer types which only differ in their protocol qualifiers are equal.
1709bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1710 FunctionProtoType* NewType){
1711 if (!getLangOptions().ObjC1)
1712 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1713 NewType->arg_type_begin());
1714
1715 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1716 N = NewType->arg_type_begin(),
1717 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1718 QualType ToType = (*O);
1719 QualType FromType = (*N);
1720 if (ToType != FromType) {
1721 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1722 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001723 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1724 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1725 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1726 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001727 continue;
1728 }
John McCall8b07ec22010-05-15 11:32:37 +00001729 else if (const ObjCObjectPointerType *PTTo =
1730 ToType->getAs<ObjCObjectPointerType>()) {
1731 if (const ObjCObjectPointerType *PTFr =
1732 FromType->getAs<ObjCObjectPointerType>())
1733 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1734 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001735 }
1736 return false;
1737 }
1738 }
1739 return true;
1740}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001741
Douglas Gregor39c16d42008-10-24 04:54:22 +00001742/// CheckPointerConversion - Check the pointer conversion from the
1743/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001744/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001745/// conversions for which IsPointerConversion has already returned
1746/// true. It returns true and produces a diagnostic if there was an
1747/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001748bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001749 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001750 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001751 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001752 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001753 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001754
Douglas Gregor4038cf42010-06-08 17:35:15 +00001755 if (CXXBoolLiteralExpr* LitBool
1756 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001757 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001758 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1759 << ToType;
1760
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001761 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1762 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001763 QualType FromPointeeType = FromPtrType->getPointeeType(),
1764 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001765
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001766 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1767 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001768 // We must have a derived-to-base conversion. Check an
1769 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001770 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1771 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001772 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001773 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001774 return true;
1775
1776 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001777 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001778 }
1779 }
Mike Stump11289f42009-09-09 15:08:12 +00001780 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001781 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001782 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001783 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001784 // Objective-C++ conversions are always okay.
1785 // FIXME: We should have a different class of conversions for the
1786 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001787 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001788 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001789
Steve Naroff7cae42b2009-07-10 23:34:53 +00001790 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001791 return false;
1792}
1793
Sebastian Redl72b597d2009-01-25 19:43:20 +00001794/// IsMemberPointerConversion - Determines whether the conversion of the
1795/// expression From, which has the (possibly adjusted) type FromType, can be
1796/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1797/// If so, returns true and places the converted type (that might differ from
1798/// ToType in its cv-qualifiers at some level) into ConvertedType.
1799bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001800 QualType ToType,
1801 bool InOverloadResolution,
1802 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001803 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001804 if (!ToTypePtr)
1805 return false;
1806
1807 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001808 if (From->isNullPointerConstant(Context,
1809 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1810 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001811 ConvertedType = ToType;
1812 return true;
1813 }
1814
1815 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001816 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001817 if (!FromTypePtr)
1818 return false;
1819
1820 // A pointer to member of B can be converted to a pointer to member of D,
1821 // where D is derived from B (C++ 4.11p2).
1822 QualType FromClass(FromTypePtr->getClass(), 0);
1823 QualType ToClass(ToTypePtr->getClass(), 0);
1824 // FIXME: What happens when these are dependent? Is this function even called?
1825
1826 if (IsDerivedFrom(ToClass, FromClass)) {
1827 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1828 ToClass.getTypePtr());
1829 return true;
1830 }
1831
1832 return false;
1833}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001834
Sebastian Redl72b597d2009-01-25 19:43:20 +00001835/// CheckMemberPointerConversion - Check the member pointer conversion from the
1836/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001837/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001838/// for which IsMemberPointerConversion has already returned true. It returns
1839/// true and produces a diagnostic if there was an error, or returns false
1840/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001841bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001842 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001843 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001844 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001845 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001846 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001847 if (!FromPtrType) {
1848 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001849 assert(From->isNullPointerConstant(Context,
1850 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001851 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001852 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001853 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001854 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001855
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001856 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001857 assert(ToPtrType && "No member pointer cast has a target type "
1858 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001859
Sebastian Redled8f2002009-01-28 18:33:18 +00001860 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1861 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001862
Sebastian Redled8f2002009-01-28 18:33:18 +00001863 // FIXME: What about dependent types?
1864 assert(FromClass->isRecordType() && "Pointer into non-class.");
1865 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001866
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001867 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001868 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001869 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1870 assert(DerivationOkay &&
1871 "Should not have been called if derivation isn't OK.");
1872 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001873
Sebastian Redled8f2002009-01-28 18:33:18 +00001874 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1875 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001876 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1877 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1878 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1879 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001880 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001881
Douglas Gregor89ee6822009-02-28 01:32:25 +00001882 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001883 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1884 << FromClass << ToClass << QualType(VBase, 0)
1885 << From->getSourceRange();
1886 return true;
1887 }
1888
John McCall5b0829a2010-02-10 09:31:12 +00001889 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001890 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1891 Paths.front(),
1892 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001893
Anders Carlssond7923c62009-08-22 23:33:40 +00001894 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001895 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001896 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001897 return false;
1898}
1899
Douglas Gregor9a657932008-10-21 23:43:52 +00001900/// IsQualificationConversion - Determines whether the conversion from
1901/// an rvalue of type FromType to ToType is a qualification conversion
1902/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001903bool
1904Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001905 FromType = Context.getCanonicalType(FromType);
1906 ToType = Context.getCanonicalType(ToType);
1907
1908 // If FromType and ToType are the same type, this is not a
1909 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001910 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001911 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001912
Douglas Gregor9a657932008-10-21 23:43:52 +00001913 // (C++ 4.4p4):
1914 // A conversion can add cv-qualifiers at levels other than the first
1915 // in multi-level pointers, subject to the following rules: [...]
1916 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001917 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001918 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001919 // Within each iteration of the loop, we check the qualifiers to
1920 // determine if this still looks like a qualification
1921 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001922 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001923 // until there are no more pointers or pointers-to-members left to
1924 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001925 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001926
1927 // -- for every j > 0, if const is in cv 1,j then const is in cv
1928 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001929 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001930 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001931
Douglas Gregor9a657932008-10-21 23:43:52 +00001932 // -- if the cv 1,j and cv 2,j are different, then const is in
1933 // every cv for 0 < k < j.
1934 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001935 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001936 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregor9a657932008-10-21 23:43:52 +00001938 // Keep track of whether all prior cv-qualifiers in the "to" type
1939 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001940 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001941 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001942 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001943
1944 // We are left with FromType and ToType being the pointee types
1945 // after unwrapping the original FromType and ToType the same number
1946 // of types. If we unwrapped any pointers, and if FromType and
1947 // ToType have the same unqualified type (since we checked
1948 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001949 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001950}
1951
Douglas Gregor576e98c2009-01-30 23:27:23 +00001952/// Determines whether there is a user-defined conversion sequence
1953/// (C++ [over.ics.user]) that converts expression From to the type
1954/// ToType. If such a conversion exists, User will contain the
1955/// user-defined conversion sequence that performs such a conversion
1956/// and this routine will return true. Otherwise, this routine returns
1957/// false and User is unspecified.
1958///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001959/// \param AllowExplicit true if the conversion should consider C++0x
1960/// "explicit" conversion functions as well as non-explicit conversion
1961/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001962static OverloadingResult
1963IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1964 UserDefinedConversionSequence& User,
1965 OverloadCandidateSet& CandidateSet,
1966 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001967 // Whether we will only visit constructors.
1968 bool ConstructorsOnly = false;
1969
1970 // If the type we are conversion to is a class type, enumerate its
1971 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001972 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001973 // C++ [over.match.ctor]p1:
1974 // When objects of class type are direct-initialized (8.5), or
1975 // copy-initialized from an expression of the same or a
1976 // derived class type (8.5), overload resolution selects the
1977 // constructor. [...] For copy-initialization, the candidate
1978 // functions are all the converting constructors (12.3.1) of
1979 // that class. The argument list is the expression-list within
1980 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00001981 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00001982 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001983 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001984 ConstructorsOnly = true;
1985
John McCall5c32be02010-08-24 20:38:10 +00001986 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001987 // We're not going to find any constructors.
1988 } else if (CXXRecordDecl *ToRecordDecl
1989 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001990 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00001991 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001992 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001993 NamedDecl *D = *Con;
1994 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1995
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001996 // Find the constructor (which may be a template).
1997 CXXConstructorDecl *Constructor = 0;
1998 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001999 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002000 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002001 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002002 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2003 else
John McCalla0296f72010-03-19 07:35:19 +00002004 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002005
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002006 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002007 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002008 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002009 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2010 /*ExplicitArgs*/ 0,
2011 &From, 1, CandidateSet,
2012 /*SuppressUserConversions=*/
2013 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002014 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002015 // Allow one user-defined conversion when user specifies a
2016 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002017 S.AddOverloadCandidate(Constructor, FoundDecl,
2018 &From, 1, CandidateSet,
2019 /*SuppressUserConversions=*/
2020 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002021 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002022 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002023 }
2024 }
2025
Douglas Gregor5ab11652010-04-17 22:01:05 +00002026 // Enumerate conversion functions, if we're allowed to.
2027 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002028 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2029 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002030 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002031 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002032 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002033 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002034 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2035 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002036 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002037 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002038 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002039 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002040 DeclAccessPair FoundDecl = I.getPair();
2041 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002042 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2043 if (isa<UsingShadowDecl>(D))
2044 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2045
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002046 CXXConversionDecl *Conv;
2047 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002048 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002050 else
John McCallda4458e2010-03-31 01:36:47 +00002051 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002052
2053 if (AllowExplicit || !Conv->isExplicit()) {
2054 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002055 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2056 ActingContext, From, ToType,
2057 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002058 else
John McCall5c32be02010-08-24 20:38:10 +00002059 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2060 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002061 }
2062 }
2063 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002064 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002065
2066 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002067 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002068 case OR_Success:
2069 // Record the standard conversion we used and the conversion function.
2070 if (CXXConstructorDecl *Constructor
2071 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2072 // C++ [over.ics.user]p1:
2073 // If the user-defined conversion is specified by a
2074 // constructor (12.3.1), the initial standard conversion
2075 // sequence converts the source type to the type required by
2076 // the argument of the constructor.
2077 //
2078 QualType ThisType = Constructor->getThisType(S.Context);
2079 if (Best->Conversions[0].isEllipsis())
2080 User.EllipsisConversion = true;
2081 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002082 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002083 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002084 }
John McCall5c32be02010-08-24 20:38:10 +00002085 User.ConversionFunction = Constructor;
2086 User.After.setAsIdentityConversion();
2087 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2088 User.After.setAllToTypes(ToType);
2089 return OR_Success;
2090 } else if (CXXConversionDecl *Conversion
2091 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2092 // C++ [over.ics.user]p1:
2093 //
2094 // [...] If the user-defined conversion is specified by a
2095 // conversion function (12.3.2), the initial standard
2096 // conversion sequence converts the source type to the
2097 // implicit object parameter of the conversion function.
2098 User.Before = Best->Conversions[0].Standard;
2099 User.ConversionFunction = Conversion;
2100 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002101
John McCall5c32be02010-08-24 20:38:10 +00002102 // C++ [over.ics.user]p2:
2103 // The second standard conversion sequence converts the
2104 // result of the user-defined conversion to the target type
2105 // for the sequence. Since an implicit conversion sequence
2106 // is an initialization, the special rules for
2107 // initialization by user-defined conversion apply when
2108 // selecting the best user-defined conversion for a
2109 // user-defined conversion sequence (see 13.3.3 and
2110 // 13.3.3.1).
2111 User.After = Best->FinalConversion;
2112 return OR_Success;
2113 } else {
2114 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002115 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002116 }
2117
John McCall5c32be02010-08-24 20:38:10 +00002118 case OR_No_Viable_Function:
2119 return OR_No_Viable_Function;
2120 case OR_Deleted:
2121 // No conversion here! We're done.
2122 return OR_Deleted;
2123
2124 case OR_Ambiguous:
2125 return OR_Ambiguous;
2126 }
2127
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002128 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002129}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002130
2131bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002132Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002133 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002134 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002135 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002136 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002137 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002138 if (OvResult == OR_Ambiguous)
2139 Diag(From->getSourceRange().getBegin(),
2140 diag::err_typecheck_ambiguous_condition)
2141 << From->getType() << ToType << From->getSourceRange();
2142 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2143 Diag(From->getSourceRange().getBegin(),
2144 diag::err_typecheck_nonviable_condition)
2145 << From->getType() << ToType << From->getSourceRange();
2146 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002147 return false;
John McCall5c32be02010-08-24 20:38:10 +00002148 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002149 return true;
2150}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002151
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002152/// CompareImplicitConversionSequences - Compare two implicit
2153/// conversion sequences to determine whether one is better than the
2154/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002155static ImplicitConversionSequence::CompareKind
2156CompareImplicitConversionSequences(Sema &S,
2157 const ImplicitConversionSequence& ICS1,
2158 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002159{
2160 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2161 // conversion sequences (as defined in 13.3.3.1)
2162 // -- a standard conversion sequence (13.3.3.1.1) is a better
2163 // conversion sequence than a user-defined conversion sequence or
2164 // an ellipsis conversion sequence, and
2165 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2166 // conversion sequence than an ellipsis conversion sequence
2167 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002168 //
John McCall0d1da222010-01-12 00:44:57 +00002169 // C++0x [over.best.ics]p10:
2170 // For the purpose of ranking implicit conversion sequences as
2171 // described in 13.3.3.2, the ambiguous conversion sequence is
2172 // treated as a user-defined sequence that is indistinguishable
2173 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002174 if (ICS1.getKindRank() < ICS2.getKindRank())
2175 return ImplicitConversionSequence::Better;
2176 else if (ICS2.getKindRank() < ICS1.getKindRank())
2177 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002178
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002179 // The following checks require both conversion sequences to be of
2180 // the same kind.
2181 if (ICS1.getKind() != ICS2.getKind())
2182 return ImplicitConversionSequence::Indistinguishable;
2183
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002184 // Two implicit conversion sequences of the same form are
2185 // indistinguishable conversion sequences unless one of the
2186 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002187 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002188 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002189 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002190 // User-defined conversion sequence U1 is a better conversion
2191 // sequence than another user-defined conversion sequence U2 if
2192 // they contain the same user-defined conversion function or
2193 // constructor and if the second standard conversion sequence of
2194 // U1 is better than the second standard conversion sequence of
2195 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002196 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002197 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002198 return CompareStandardConversionSequences(S,
2199 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200 ICS2.UserDefined.After);
2201 }
2202
2203 return ImplicitConversionSequence::Indistinguishable;
2204}
2205
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002206static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2207 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2208 Qualifiers Quals;
2209 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2210 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2211 }
2212
2213 return Context.hasSameUnqualifiedType(T1, T2);
2214}
2215
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002216// Per 13.3.3.2p3, compare the given standard conversion sequences to
2217// determine if one is a proper subset of the other.
2218static ImplicitConversionSequence::CompareKind
2219compareStandardConversionSubsets(ASTContext &Context,
2220 const StandardConversionSequence& SCS1,
2221 const StandardConversionSequence& SCS2) {
2222 ImplicitConversionSequence::CompareKind Result
2223 = ImplicitConversionSequence::Indistinguishable;
2224
Douglas Gregore87561a2010-05-23 22:10:15 +00002225 // the identity conversion sequence is considered to be a subsequence of
2226 // any non-identity conversion sequence
2227 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2228 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2229 return ImplicitConversionSequence::Better;
2230 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2231 return ImplicitConversionSequence::Worse;
2232 }
2233
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002234 if (SCS1.Second != SCS2.Second) {
2235 if (SCS1.Second == ICK_Identity)
2236 Result = ImplicitConversionSequence::Better;
2237 else if (SCS2.Second == ICK_Identity)
2238 Result = ImplicitConversionSequence::Worse;
2239 else
2240 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002241 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002242 return ImplicitConversionSequence::Indistinguishable;
2243
2244 if (SCS1.Third == SCS2.Third) {
2245 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2246 : ImplicitConversionSequence::Indistinguishable;
2247 }
2248
2249 if (SCS1.Third == ICK_Identity)
2250 return Result == ImplicitConversionSequence::Worse
2251 ? ImplicitConversionSequence::Indistinguishable
2252 : ImplicitConversionSequence::Better;
2253
2254 if (SCS2.Third == ICK_Identity)
2255 return Result == ImplicitConversionSequence::Better
2256 ? ImplicitConversionSequence::Indistinguishable
2257 : ImplicitConversionSequence::Worse;
2258
2259 return ImplicitConversionSequence::Indistinguishable;
2260}
2261
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002262/// CompareStandardConversionSequences - Compare two standard
2263/// conversion sequences to determine whether one is better than the
2264/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002265static ImplicitConversionSequence::CompareKind
2266CompareStandardConversionSequences(Sema &S,
2267 const StandardConversionSequence& SCS1,
2268 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002269{
2270 // Standard conversion sequence S1 is a better conversion sequence
2271 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2272
2273 // -- S1 is a proper subsequence of S2 (comparing the conversion
2274 // sequences in the canonical form defined by 13.3.3.1.1,
2275 // excluding any Lvalue Transformation; the identity conversion
2276 // sequence is considered to be a subsequence of any
2277 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002278 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002279 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002280 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002281
2282 // -- the rank of S1 is better than the rank of S2 (by the rules
2283 // defined below), or, if not that,
2284 ImplicitConversionRank Rank1 = SCS1.getRank();
2285 ImplicitConversionRank Rank2 = SCS2.getRank();
2286 if (Rank1 < Rank2)
2287 return ImplicitConversionSequence::Better;
2288 else if (Rank2 < Rank1)
2289 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002290
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002291 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2292 // are indistinguishable unless one of the following rules
2293 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002294
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002295 // A conversion that is not a conversion of a pointer, or
2296 // pointer to member, to bool is better than another conversion
2297 // that is such a conversion.
2298 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2299 return SCS2.isPointerConversionToBool()
2300 ? ImplicitConversionSequence::Better
2301 : ImplicitConversionSequence::Worse;
2302
Douglas Gregor5c407d92008-10-23 00:40:37 +00002303 // C++ [over.ics.rank]p4b2:
2304 //
2305 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002306 // conversion of B* to A* is better than conversion of B* to
2307 // void*, and conversion of A* to void* is better than conversion
2308 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002309 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002310 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002311 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002312 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002313 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2314 // Exactly one of the conversion sequences is a conversion to
2315 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002316 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2317 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002318 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2319 // Neither conversion sequence converts to a void pointer; compare
2320 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002321 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002322 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002323 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002324 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2325 // Both conversion sequences are conversions to void
2326 // pointers. Compare the source types to determine if there's an
2327 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002328 QualType FromType1 = SCS1.getFromType();
2329 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002330
2331 // Adjust the types we're converting from via the array-to-pointer
2332 // conversion, if we need to.
2333 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002334 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002335 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002336 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002337
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002338 QualType FromPointee1
2339 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2340 QualType FromPointee2
2341 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002342
John McCall5c32be02010-08-24 20:38:10 +00002343 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002344 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002345 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002346 return ImplicitConversionSequence::Worse;
2347
2348 // Objective-C++: If one interface is more specific than the
2349 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002350 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2351 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002352 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002353 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002354 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002355 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002356 return ImplicitConversionSequence::Worse;
2357 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002358 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002359
2360 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2361 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002362 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002363 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002364 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002365
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002366 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002367 // C++0x [over.ics.rank]p3b4:
2368 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2369 // implicit object parameter of a non-static member function declared
2370 // without a ref-qualifier, and S1 binds an rvalue reference to an
2371 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002372 // FIXME: We don't know if we're dealing with the implicit object parameter,
2373 // or if the member function in this case has a ref qualifier.
2374 // (Of course, we don't have ref qualifiers yet.)
2375 if (SCS1.RRefBinding != SCS2.RRefBinding)
2376 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2377 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002378
2379 // C++ [over.ics.rank]p3b4:
2380 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2381 // which the references refer are the same type except for
2382 // top-level cv-qualifiers, and the type to which the reference
2383 // initialized by S2 refers is more cv-qualified than the type
2384 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002385 QualType T1 = SCS1.getToType(2);
2386 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002387 T1 = S.Context.getCanonicalType(T1);
2388 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002389 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002390 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2391 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002392 if (UnqualT1 == UnqualT2) {
2393 // If the type is an array type, promote the element qualifiers to the type
2394 // for comparison.
2395 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002396 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002397 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002398 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002399 if (T2.isMoreQualifiedThan(T1))
2400 return ImplicitConversionSequence::Better;
2401 else if (T1.isMoreQualifiedThan(T2))
2402 return ImplicitConversionSequence::Worse;
2403 }
2404 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002405
2406 return ImplicitConversionSequence::Indistinguishable;
2407}
2408
2409/// CompareQualificationConversions - Compares two standard conversion
2410/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002411/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2412ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002413CompareQualificationConversions(Sema &S,
2414 const StandardConversionSequence& SCS1,
2415 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002416 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002417 // -- S1 and S2 differ only in their qualification conversion and
2418 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2419 // cv-qualification signature of type T1 is a proper subset of
2420 // the cv-qualification signature of type T2, and S1 is not the
2421 // deprecated string literal array-to-pointer conversion (4.2).
2422 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2423 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2424 return ImplicitConversionSequence::Indistinguishable;
2425
2426 // FIXME: the example in the standard doesn't use a qualification
2427 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002428 QualType T1 = SCS1.getToType(2);
2429 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002430 T1 = S.Context.getCanonicalType(T1);
2431 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002432 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002433 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2434 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002435
2436 // If the types are the same, we won't learn anything by unwrapped
2437 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002438 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002439 return ImplicitConversionSequence::Indistinguishable;
2440
Chandler Carruth607f38e2009-12-29 07:16:59 +00002441 // If the type is an array type, promote the element qualifiers to the type
2442 // for comparison.
2443 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002444 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002445 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002446 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002447
Mike Stump11289f42009-09-09 15:08:12 +00002448 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002449 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002450 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002451 // Within each iteration of the loop, we check the qualifiers to
2452 // determine if this still looks like a qualification
2453 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002454 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002455 // until there are no more pointers or pointers-to-members left
2456 // to unwrap. This essentially mimics what
2457 // IsQualificationConversion does, but here we're checking for a
2458 // strict subset of qualifiers.
2459 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2460 // The qualifiers are the same, so this doesn't tell us anything
2461 // about how the sequences rank.
2462 ;
2463 else if (T2.isMoreQualifiedThan(T1)) {
2464 // T1 has fewer qualifiers, so it could be the better sequence.
2465 if (Result == ImplicitConversionSequence::Worse)
2466 // Neither has qualifiers that are a subset of the other's
2467 // qualifiers.
2468 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002469
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002470 Result = ImplicitConversionSequence::Better;
2471 } else if (T1.isMoreQualifiedThan(T2)) {
2472 // T2 has fewer qualifiers, so it could be the better sequence.
2473 if (Result == ImplicitConversionSequence::Better)
2474 // Neither has qualifiers that are a subset of the other's
2475 // qualifiers.
2476 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002478 Result = ImplicitConversionSequence::Worse;
2479 } else {
2480 // Qualifiers are disjoint.
2481 return ImplicitConversionSequence::Indistinguishable;
2482 }
2483
2484 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002485 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002486 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002487 }
2488
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002489 // Check that the winning standard conversion sequence isn't using
2490 // the deprecated string literal array to pointer conversion.
2491 switch (Result) {
2492 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002493 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002494 Result = ImplicitConversionSequence::Indistinguishable;
2495 break;
2496
2497 case ImplicitConversionSequence::Indistinguishable:
2498 break;
2499
2500 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002501 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002502 Result = ImplicitConversionSequence::Indistinguishable;
2503 break;
2504 }
2505
2506 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002507}
2508
Douglas Gregor5c407d92008-10-23 00:40:37 +00002509/// CompareDerivedToBaseConversions - Compares two standard conversion
2510/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002511/// various kinds of derived-to-base conversions (C++
2512/// [over.ics.rank]p4b3). As part of these checks, we also look at
2513/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002514ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002515CompareDerivedToBaseConversions(Sema &S,
2516 const StandardConversionSequence& SCS1,
2517 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002518 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002519 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002520 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002521 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002522
2523 // Adjust the types we're converting from via the array-to-pointer
2524 // conversion, if we need to.
2525 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002526 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002527 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002528 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002529
2530 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002531 FromType1 = S.Context.getCanonicalType(FromType1);
2532 ToType1 = S.Context.getCanonicalType(ToType1);
2533 FromType2 = S.Context.getCanonicalType(FromType2);
2534 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002535
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002536 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002537 //
2538 // If class B is derived directly or indirectly from class A and
2539 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002540 //
2541 // For Objective-C, we let A, B, and C also be Objective-C
2542 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002543
2544 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002545 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002546 SCS2.Second == ICK_Pointer_Conversion &&
2547 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2548 FromType1->isPointerType() && FromType2->isPointerType() &&
2549 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002550 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002551 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002552 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002553 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002554 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002555 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002556 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002557 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002558
John McCall8b07ec22010-05-15 11:32:37 +00002559 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2560 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2561 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2562 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002563
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002564 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002565 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002566 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002567 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002568 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002569 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002570
2571 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002572 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002573 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002574 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002575 return ImplicitConversionSequence::Worse;
2576 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002577 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002578
2579 // -- conversion of B* to A* is better than conversion of C* to A*,
2580 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002581 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002582 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002583 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002584 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregor237f96c2008-11-26 23:31:11 +00002586 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002587 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002588 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002589 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002590 return ImplicitConversionSequence::Worse;
2591 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002592 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002593 }
2594
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002595 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002596 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2597 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2598 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2599 const MemberPointerType * FromMemPointer1 =
2600 FromType1->getAs<MemberPointerType>();
2601 const MemberPointerType * ToMemPointer1 =
2602 ToType1->getAs<MemberPointerType>();
2603 const MemberPointerType * FromMemPointer2 =
2604 FromType2->getAs<MemberPointerType>();
2605 const MemberPointerType * ToMemPointer2 =
2606 ToType2->getAs<MemberPointerType>();
2607 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2608 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2609 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2610 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2611 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2612 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2613 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2614 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002615 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002616 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002617 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002618 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002619 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002620 return ImplicitConversionSequence::Better;
2621 }
2622 // conversion of B::* to C::* is better than conversion of A::* to C::*
2623 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002624 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002625 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002626 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002627 return ImplicitConversionSequence::Worse;
2628 }
2629 }
2630
Douglas Gregor5ab11652010-04-17 22:01:05 +00002631 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002632 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002633 // -- binding of an expression of type C to a reference of type
2634 // B& is better than binding an expression of type C to a
2635 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002636 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2637 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2638 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002639 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002640 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002641 return ImplicitConversionSequence::Worse;
2642 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002643
Douglas Gregor2fe98832008-11-03 19:09:14 +00002644 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002645 // -- binding of an expression of type B to a reference of type
2646 // A& is better than binding an expression of type C to a
2647 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002648 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2649 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2650 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002651 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002652 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002653 return ImplicitConversionSequence::Worse;
2654 }
2655 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002656
Douglas Gregor5c407d92008-10-23 00:40:37 +00002657 return ImplicitConversionSequence::Indistinguishable;
2658}
2659
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002660/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2661/// determine whether they are reference-related,
2662/// reference-compatible, reference-compatible with added
2663/// qualification, or incompatible, for use in C++ initialization by
2664/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2665/// type, and the first type (T1) is the pointee type of the reference
2666/// type being initialized.
2667Sema::ReferenceCompareResult
2668Sema::CompareReferenceRelationship(SourceLocation Loc,
2669 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002670 bool &DerivedToBase,
2671 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002672 assert(!OrigT1->isReferenceType() &&
2673 "T1 must be the pointee type of the reference type");
2674 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2675
2676 QualType T1 = Context.getCanonicalType(OrigT1);
2677 QualType T2 = Context.getCanonicalType(OrigT2);
2678 Qualifiers T1Quals, T2Quals;
2679 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2680 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2681
2682 // C++ [dcl.init.ref]p4:
2683 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2684 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2685 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002686 DerivedToBase = false;
2687 ObjCConversion = false;
2688 if (UnqualT1 == UnqualT2) {
2689 // Nothing to do.
2690 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002691 IsDerivedFrom(UnqualT2, UnqualT1))
2692 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002693 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2694 UnqualT2->isObjCObjectOrInterfaceType() &&
2695 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2696 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002697 else
2698 return Ref_Incompatible;
2699
2700 // At this point, we know that T1 and T2 are reference-related (at
2701 // least).
2702
2703 // If the type is an array type, promote the element qualifiers to the type
2704 // for comparison.
2705 if (isa<ArrayType>(T1) && T1Quals)
2706 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2707 if (isa<ArrayType>(T2) && T2Quals)
2708 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2709
2710 // C++ [dcl.init.ref]p4:
2711 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2712 // reference-related to T2 and cv1 is the same cv-qualification
2713 // as, or greater cv-qualification than, cv2. For purposes of
2714 // overload resolution, cases for which cv1 is greater
2715 // cv-qualification than cv2 are identified as
2716 // reference-compatible with added qualification (see 13.3.3.2).
2717 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2718 return Ref_Compatible;
2719 else if (T1.isMoreQualifiedThan(T2))
2720 return Ref_Compatible_With_Added_Qualification;
2721 else
2722 return Ref_Related;
2723}
2724
Douglas Gregor836a7e82010-08-11 02:15:33 +00002725/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002726/// with DeclType. Return true if something definite is found.
2727static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002728FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2729 QualType DeclType, SourceLocation DeclLoc,
2730 Expr *Init, QualType T2, bool AllowRvalues,
2731 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002732 assert(T2->isRecordType() && "Can only find conversions of record types.");
2733 CXXRecordDecl *T2RecordDecl
2734 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2735
Douglas Gregor836a7e82010-08-11 02:15:33 +00002736 QualType ToType
2737 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2738 : DeclType;
2739
Sebastian Redld92badf2010-06-30 18:13:39 +00002740 OverloadCandidateSet CandidateSet(DeclLoc);
2741 const UnresolvedSetImpl *Conversions
2742 = T2RecordDecl->getVisibleConversionFunctions();
2743 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2744 E = Conversions->end(); I != E; ++I) {
2745 NamedDecl *D = *I;
2746 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2747 if (isa<UsingShadowDecl>(D))
2748 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2749
2750 FunctionTemplateDecl *ConvTemplate
2751 = dyn_cast<FunctionTemplateDecl>(D);
2752 CXXConversionDecl *Conv;
2753 if (ConvTemplate)
2754 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2755 else
2756 Conv = cast<CXXConversionDecl>(D);
2757
Douglas Gregor836a7e82010-08-11 02:15:33 +00002758 // If this is an explicit conversion, and we're not allowed to consider
2759 // explicit conversions, skip it.
2760 if (!AllowExplicit && Conv->isExplicit())
2761 continue;
2762
2763 if (AllowRvalues) {
2764 bool DerivedToBase = false;
2765 bool ObjCConversion = false;
2766 if (!ConvTemplate &&
2767 S.CompareReferenceRelationship(DeclLoc,
2768 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2769 DeclType.getNonReferenceType().getUnqualifiedType(),
2770 DerivedToBase, ObjCConversion)
2771 == Sema::Ref_Incompatible)
2772 continue;
2773 } else {
2774 // If the conversion function doesn't return a reference type,
2775 // it can't be considered for this conversion. An rvalue reference
2776 // is only acceptable if its referencee is a function type.
2777
2778 const ReferenceType *RefType =
2779 Conv->getConversionType()->getAs<ReferenceType>();
2780 if (!RefType ||
2781 (!RefType->isLValueReferenceType() &&
2782 !RefType->getPointeeType()->isFunctionType()))
2783 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002784 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002785
2786 if (ConvTemplate)
2787 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2788 Init, ToType, CandidateSet);
2789 else
2790 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2791 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002792 }
2793
2794 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002795 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002796 case OR_Success:
2797 // C++ [over.ics.ref]p1:
2798 //
2799 // [...] If the parameter binds directly to the result of
2800 // applying a conversion function to the argument
2801 // expression, the implicit conversion sequence is a
2802 // user-defined conversion sequence (13.3.3.1.2), with the
2803 // second standard conversion sequence either an identity
2804 // conversion or, if the conversion function returns an
2805 // entity of a type that is a derived class of the parameter
2806 // type, a derived-to-base Conversion.
2807 if (!Best->FinalConversion.DirectBinding)
2808 return false;
2809
2810 ICS.setUserDefined();
2811 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2812 ICS.UserDefined.After = Best->FinalConversion;
2813 ICS.UserDefined.ConversionFunction = Best->Function;
2814 ICS.UserDefined.EllipsisConversion = false;
2815 assert(ICS.UserDefined.After.ReferenceBinding &&
2816 ICS.UserDefined.After.DirectBinding &&
2817 "Expected a direct reference binding!");
2818 return true;
2819
2820 case OR_Ambiguous:
2821 ICS.setAmbiguous();
2822 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2823 Cand != CandidateSet.end(); ++Cand)
2824 if (Cand->Viable)
2825 ICS.Ambiguous.addConversion(Cand->Function);
2826 return true;
2827
2828 case OR_No_Viable_Function:
2829 case OR_Deleted:
2830 // There was no suitable conversion, or we found a deleted
2831 // conversion; continue with other checks.
2832 return false;
2833 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002834
2835 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002836}
2837
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002838/// \brief Compute an implicit conversion sequence for reference
2839/// initialization.
2840static ImplicitConversionSequence
2841TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2842 SourceLocation DeclLoc,
2843 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002844 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002845 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2846
2847 // Most paths end in a failed conversion.
2848 ImplicitConversionSequence ICS;
2849 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2850
2851 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2852 QualType T2 = Init->getType();
2853
2854 // If the initializer is the address of an overloaded function, try
2855 // to resolve the overloaded function. If all goes well, T2 is the
2856 // type of the resulting function.
2857 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2858 DeclAccessPair Found;
2859 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2860 false, Found))
2861 T2 = Fn->getType();
2862 }
2863
2864 // Compute some basic properties of the types and the initializer.
2865 bool isRValRef = DeclType->isRValueReferenceType();
2866 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002867 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002868 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002869 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002870 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2871 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002872
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002873
Sebastian Redld92badf2010-06-30 18:13:39 +00002874 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002875 // A reference to type "cv1 T1" is initialized by an expression
2876 // of type "cv2 T2" as follows:
2877
Sebastian Redld92badf2010-06-30 18:13:39 +00002878 // -- If reference is an lvalue reference and the initializer expression
2879 // The next bullet point (T1 is a function) is pretty much equivalent to this
2880 // one, so it's handled here.
2881 if (!isRValRef || T1->isFunctionType()) {
2882 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2883 // reference-compatible with "cv2 T2," or
2884 //
2885 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2886 if (InitCategory.isLValue() &&
2887 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002888 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002889 // When a parameter of reference type binds directly (8.5.3)
2890 // to an argument expression, the implicit conversion sequence
2891 // is the identity conversion, unless the argument expression
2892 // has a type that is a derived class of the parameter type,
2893 // in which case the implicit conversion sequence is a
2894 // derived-to-base Conversion (13.3.3.1).
2895 ICS.setStandard();
2896 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002897 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2898 : ObjCConversion? ICK_Compatible_Conversion
2899 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002900 ICS.Standard.Third = ICK_Identity;
2901 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2902 ICS.Standard.setToType(0, T2);
2903 ICS.Standard.setToType(1, T1);
2904 ICS.Standard.setToType(2, T1);
2905 ICS.Standard.ReferenceBinding = true;
2906 ICS.Standard.DirectBinding = true;
2907 ICS.Standard.RRefBinding = isRValRef;
2908 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002909
Sebastian Redld92badf2010-06-30 18:13:39 +00002910 // Nothing more to do: the inaccessibility/ambiguity check for
2911 // derived-to-base conversions is suppressed when we're
2912 // computing the implicit conversion sequence (C++
2913 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002914 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002915 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002916
Sebastian Redld92badf2010-06-30 18:13:39 +00002917 // -- has a class type (i.e., T2 is a class type), where T1 is
2918 // not reference-related to T2, and can be implicitly
2919 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2920 // is reference-compatible with "cv3 T3" 92) (this
2921 // conversion is selected by enumerating the applicable
2922 // conversion functions (13.3.1.6) and choosing the best
2923 // one through overload resolution (13.3)),
2924 if (!SuppressUserConversions && T2->isRecordType() &&
2925 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2926 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002927 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2928 Init, T2, /*AllowRvalues=*/false,
2929 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002930 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002931 }
2932 }
2933
Sebastian Redld92badf2010-06-30 18:13:39 +00002934 // -- Otherwise, the reference shall be an lvalue reference to a
2935 // non-volatile const type (i.e., cv1 shall be const), or the reference
2936 // shall be an rvalue reference and the initializer expression shall be
2937 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002938 //
2939 // We actually handle one oddity of C++ [over.ics.ref] at this
2940 // point, which is that, due to p2 (which short-circuits reference
2941 // binding by only attempting a simple conversion for non-direct
2942 // bindings) and p3's strange wording, we allow a const volatile
2943 // reference to bind to an rvalue. Hence the check for the presence
2944 // of "const" rather than checking for "const" being the only
2945 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002946 // This is also the point where rvalue references and lvalue inits no longer
2947 // go together.
2948 if ((!isRValRef && !T1.isConstQualified()) ||
2949 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002950 return ICS;
2951
Sebastian Redld92badf2010-06-30 18:13:39 +00002952 // -- If T1 is a function type, then
2953 // -- if T2 is the same type as T1, the reference is bound to the
2954 // initializer expression lvalue;
2955 // -- if T2 is a class type and the initializer expression can be
2956 // implicitly converted to an lvalue of type T1 [...], the
2957 // reference is bound to the function lvalue that is the result
2958 // of the conversion;
2959 // This is the same as for the lvalue case above, so it was handled there.
2960 // -- otherwise, the program is ill-formed.
2961 // This is the one difference to the lvalue case.
2962 if (T1->isFunctionType())
2963 return ICS;
2964
2965 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002966 // -- the initializer expression is an rvalue and "cv1 T1"
2967 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002968 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002969 // -- T1 is not reference-related to T2 and the initializer
2970 // expression can be implicitly converted to an rvalue
2971 // of type "cv3 T3" (this conversion is selected by
2972 // enumerating the applicable conversion functions
2973 // (13.3.1.6) and choosing the best one through overload
2974 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002975 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002976 // then the reference is bound to the initializer
2977 // expression rvalue in the first case and to the object
2978 // that is the result of the conversion in the second case
2979 // (or, in either case, to the appropriate base class
2980 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002981 if (T2->isRecordType()) {
2982 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2983 // direct binding in C++0x but not in C++03.
2984 if (InitCategory.isRValue() &&
2985 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2986 ICS.setStandard();
2987 ICS.Standard.First = ICK_Identity;
2988 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2989 : ObjCConversion? ICK_Compatible_Conversion
2990 : ICK_Identity;
2991 ICS.Standard.Third = ICK_Identity;
2992 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2993 ICS.Standard.setToType(0, T2);
2994 ICS.Standard.setToType(1, T1);
2995 ICS.Standard.setToType(2, T1);
2996 ICS.Standard.ReferenceBinding = true;
2997 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2998 ICS.Standard.RRefBinding = isRValRef;
2999 ICS.Standard.CopyConstructor = 0;
3000 return ICS;
3001 }
3002
3003 // Second case: not reference-related.
3004 if (RefRelationship == Sema::Ref_Incompatible &&
3005 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3006 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3007 Init, T2, /*AllowRvalues=*/true,
3008 AllowExplicit))
3009 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003010 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003011
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003012 // -- Otherwise, a temporary of type "cv1 T1" is created and
3013 // initialized from the initializer expression using the
3014 // rules for a non-reference copy initialization (8.5). The
3015 // reference is then bound to the temporary. If T1 is
3016 // reference-related to T2, cv1 must be the same
3017 // cv-qualification as, or greater cv-qualification than,
3018 // cv2; otherwise, the program is ill-formed.
3019 if (RefRelationship == Sema::Ref_Related) {
3020 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3021 // we would be reference-compatible or reference-compatible with
3022 // added qualification. But that wasn't the case, so the reference
3023 // initialization fails.
3024 return ICS;
3025 }
3026
3027 // If at least one of the types is a class type, the types are not
3028 // related, and we aren't allowed any user conversions, the
3029 // reference binding fails. This case is important for breaking
3030 // recursion, since TryImplicitConversion below will attempt to
3031 // create a temporary through the use of a copy constructor.
3032 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3033 (T1->isRecordType() || T2->isRecordType()))
3034 return ICS;
3035
3036 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003037 // When a parameter of reference type is not bound directly to
3038 // an argument expression, the conversion sequence is the one
3039 // required to convert the argument expression to the
3040 // underlying type of the reference according to
3041 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3042 // to copy-initializing a temporary of the underlying type with
3043 // the argument expression. Any difference in top-level
3044 // cv-qualification is subsumed by the initialization itself
3045 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003046 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3047 /*AllowExplicit=*/false,
3048 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003049
3050 // Of course, that's still a reference binding.
3051 if (ICS.isStandard()) {
3052 ICS.Standard.ReferenceBinding = true;
3053 ICS.Standard.RRefBinding = isRValRef;
3054 } else if (ICS.isUserDefined()) {
3055 ICS.UserDefined.After.ReferenceBinding = true;
3056 ICS.UserDefined.After.RRefBinding = isRValRef;
3057 }
3058 return ICS;
3059}
3060
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003061/// TryCopyInitialization - Try to copy-initialize a value of type
3062/// ToType from the expression From. Return the implicit conversion
3063/// sequence required to pass this argument, which may be a bad
3064/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003065/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003066/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003067static ImplicitConversionSequence
3068TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003069 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003070 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003071 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003072 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003073 /*FIXME:*/From->getLocStart(),
3074 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003075 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003076
John McCall5c32be02010-08-24 20:38:10 +00003077 return TryImplicitConversion(S, From, ToType,
3078 SuppressUserConversions,
3079 /*AllowExplicit=*/false,
3080 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003081}
3082
Douglas Gregor436424c2008-11-18 23:14:02 +00003083/// TryObjectArgumentInitialization - Try to initialize the object
3084/// parameter of the given member function (@c Method) from the
3085/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003086static ImplicitConversionSequence
3087TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3088 CXXMethodDecl *Method,
3089 CXXRecordDecl *ActingContext) {
3090 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003091 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3092 // const volatile object.
3093 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3094 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003095 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003096
3097 // Set up the conversion sequence as a "bad" conversion, to allow us
3098 // to exit early.
3099 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003100
3101 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003102 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003103 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003104 FromType = PT->getPointeeType();
3105
3106 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003107
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003108 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003109 // where X is the class of which the function is a member
3110 // (C++ [over.match.funcs]p4). However, when finding an implicit
3111 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003112 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003113 // (C++ [over.match.funcs]p5). We perform a simplified version of
3114 // reference binding here, that allows class rvalues to bind to
3115 // non-constant references.
3116
3117 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3118 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003119 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003120 if (ImplicitParamType.getCVRQualifiers()
3121 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003122 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003123 ICS.setBad(BadConversionSequence::bad_qualifiers,
3124 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003125 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003126 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003127
3128 // Check that we have either the same type or a derived type. It
3129 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003130 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003131 ImplicitConversionKind SecondKind;
3132 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3133 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003134 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003135 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003136 else {
John McCall65eb8792010-02-25 01:37:24 +00003137 ICS.setBad(BadConversionSequence::unrelated_class,
3138 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003139 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003140 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003141
3142 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003143 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003144 ICS.Standard.setAsIdentityConversion();
3145 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003146 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003147 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003148 ICS.Standard.ReferenceBinding = true;
3149 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003150 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003151 return ICS;
3152}
3153
3154/// PerformObjectArgumentInitialization - Perform initialization of
3155/// the implicit object parameter for the given Method with the given
3156/// expression.
3157bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003158Sema::PerformObjectArgumentInitialization(Expr *&From,
3159 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003160 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003161 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003162 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003163 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003164 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003165
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003166 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003167 FromRecordType = PT->getPointeeType();
3168 DestType = Method->getThisType(Context);
3169 } else {
3170 FromRecordType = From->getType();
3171 DestType = ImplicitParamRecordType;
3172 }
3173
John McCall6e9f8f62009-12-03 04:06:58 +00003174 // Note that we always use the true parent context when performing
3175 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003176 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003177 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003178 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003179 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003180 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003181 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003182 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003183
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003184 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003185 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003186
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003187 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003188 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003189 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003190 return false;
3191}
3192
Douglas Gregor5fb53972009-01-14 15:45:31 +00003193/// TryContextuallyConvertToBool - Attempt to contextually convert the
3194/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003195static ImplicitConversionSequence
3196TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003197 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003198 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003199 // FIXME: Are these flags correct?
3200 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003201 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003202 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003203}
3204
3205/// PerformContextuallyConvertToBool - Perform a contextual conversion
3206/// of the expression From to bool (C++0x [conv]p3).
3207bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003208 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003209 if (!ICS.isBad())
3210 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003211
Fariborz Jahanian76197412009-11-18 18:26:29 +00003212 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003213 return Diag(From->getSourceRange().getBegin(),
3214 diag::err_typecheck_bool_condition)
3215 << From->getType() << From->getSourceRange();
3216 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003217}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003218
3219/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3220/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003221static ImplicitConversionSequence
3222TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3223 QualType Ty = S.Context.getObjCIdType();
3224 return TryImplicitConversion(S, From, Ty,
3225 // FIXME: Are these flags correct?
3226 /*SuppressUserConversions=*/false,
3227 /*AllowExplicit=*/true,
3228 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003229}
John McCall5c32be02010-08-24 20:38:10 +00003230
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003231/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3232/// of the expression From to 'id'.
3233bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003234 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003235 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003236 if (!ICS.isBad())
3237 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3238 return true;
3239}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003240
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003241/// \brief Attempt to convert the given expression to an integral or
3242/// enumeration type.
3243///
3244/// This routine will attempt to convert an expression of class type to an
3245/// integral or enumeration type, if that class type only has a single
3246/// conversion to an integral or enumeration type.
3247///
Douglas Gregor4799d032010-06-30 00:20:43 +00003248/// \param Loc The source location of the construct that requires the
3249/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003250///
Douglas Gregor4799d032010-06-30 00:20:43 +00003251/// \param FromE The expression we're converting from.
3252///
3253/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3254/// have integral or enumeration type.
3255///
3256/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3257/// incomplete class type.
3258///
3259/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3260/// explicit conversion function (because no implicit conversion functions
3261/// were available). This is a recovery mode.
3262///
3263/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3264/// showing which conversion was picked.
3265///
3266/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3267/// conversion function that could convert to integral or enumeration type.
3268///
3269/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3270/// usable conversion function.
3271///
3272/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3273/// function, which may be an extension in this case.
3274///
3275/// \returns The expression, converted to an integral or enumeration type if
3276/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003277ExprResult
John McCallb268a282010-08-23 23:25:46 +00003278Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003279 const PartialDiagnostic &NotIntDiag,
3280 const PartialDiagnostic &IncompleteDiag,
3281 const PartialDiagnostic &ExplicitConvDiag,
3282 const PartialDiagnostic &ExplicitConvNote,
3283 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003284 const PartialDiagnostic &AmbigNote,
3285 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003286 // We can't perform any more checking for type-dependent expressions.
3287 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003288 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003289
3290 // If the expression already has integral or enumeration type, we're golden.
3291 QualType T = From->getType();
3292 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003293 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003294
3295 // FIXME: Check for missing '()' if T is a function type?
3296
3297 // If we don't have a class type in C++, there's no way we can get an
3298 // expression of integral or enumeration type.
3299 const RecordType *RecordTy = T->getAs<RecordType>();
3300 if (!RecordTy || !getLangOptions().CPlusPlus) {
3301 Diag(Loc, NotIntDiag)
3302 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003303 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003304 }
3305
3306 // We must have a complete class type.
3307 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003308 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003309
3310 // Look for a conversion to an integral or enumeration type.
3311 UnresolvedSet<4> ViableConversions;
3312 UnresolvedSet<4> ExplicitConversions;
3313 const UnresolvedSetImpl *Conversions
3314 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3315
3316 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3317 E = Conversions->end();
3318 I != E;
3319 ++I) {
3320 if (CXXConversionDecl *Conversion
3321 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3322 if (Conversion->getConversionType().getNonReferenceType()
3323 ->isIntegralOrEnumerationType()) {
3324 if (Conversion->isExplicit())
3325 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3326 else
3327 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3328 }
3329 }
3330
3331 switch (ViableConversions.size()) {
3332 case 0:
3333 if (ExplicitConversions.size() == 1) {
3334 DeclAccessPair Found = ExplicitConversions[0];
3335 CXXConversionDecl *Conversion
3336 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3337
3338 // The user probably meant to invoke the given explicit
3339 // conversion; use it.
3340 QualType ConvTy
3341 = Conversion->getConversionType().getNonReferenceType();
3342 std::string TypeStr;
3343 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3344
3345 Diag(Loc, ExplicitConvDiag)
3346 << T << ConvTy
3347 << FixItHint::CreateInsertion(From->getLocStart(),
3348 "static_cast<" + TypeStr + ">(")
3349 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3350 ")");
3351 Diag(Conversion->getLocation(), ExplicitConvNote)
3352 << ConvTy->isEnumeralType() << ConvTy;
3353
3354 // If we aren't in a SFINAE context, build a call to the
3355 // explicit conversion function.
3356 if (isSFINAEContext())
3357 return ExprError();
3358
3359 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003360 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003361 }
3362
3363 // We'll complain below about a non-integral condition type.
3364 break;
3365
3366 case 1: {
3367 // Apply this conversion.
3368 DeclAccessPair Found = ViableConversions[0];
3369 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003370
3371 CXXConversionDecl *Conversion
3372 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3373 QualType ConvTy
3374 = Conversion->getConversionType().getNonReferenceType();
3375 if (ConvDiag.getDiagID()) {
3376 if (isSFINAEContext())
3377 return ExprError();
3378
3379 Diag(Loc, ConvDiag)
3380 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3381 }
3382
John McCallb268a282010-08-23 23:25:46 +00003383 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003384 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003385 break;
3386 }
3387
3388 default:
3389 Diag(Loc, AmbigDiag)
3390 << T << From->getSourceRange();
3391 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3392 CXXConversionDecl *Conv
3393 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3394 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3395 Diag(Conv->getLocation(), AmbigNote)
3396 << ConvTy->isEnumeralType() << ConvTy;
3397 }
John McCallb268a282010-08-23 23:25:46 +00003398 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003399 }
3400
Douglas Gregor5823da32010-06-29 23:25:20 +00003401 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003402 Diag(Loc, NotIntDiag)
3403 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003404
John McCallb268a282010-08-23 23:25:46 +00003405 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003406}
3407
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003408/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003409/// candidate functions, using the given function call arguments. If
3410/// @p SuppressUserConversions, then don't allow user-defined
3411/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003412///
3413/// \para PartialOverloading true if we are performing "partial" overloading
3414/// based on an incomplete set of function arguments. This feature is used by
3415/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003416void
3417Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003418 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003419 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003420 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003421 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003422 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003423 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003424 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003425 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003426 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003427 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003428
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003430 if (!isa<CXXConstructorDecl>(Method)) {
3431 // If we get here, it's because we're calling a member function
3432 // that is named without a member access expression (e.g.,
3433 // "this->f") that was either written explicitly or created
3434 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003435 // function, e.g., X::f(). We use an empty type for the implied
3436 // object argument (C++ [over.call.func]p3), and the acting context
3437 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003438 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003439 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003440 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003441 return;
3442 }
3443 // We treat a constructor like a non-member function, since its object
3444 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003445 }
3446
Douglas Gregorff7028a2009-11-13 23:59:09 +00003447 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003448 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003449
Douglas Gregor27381f32009-11-23 12:27:39 +00003450 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003451 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003452
Douglas Gregorffe14e32009-11-14 01:20:54 +00003453 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3454 // C++ [class.copy]p3:
3455 // A member function template is never instantiated to perform the copy
3456 // of a class object to an object of its class type.
3457 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3458 if (NumArgs == 1 &&
3459 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003460 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3461 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003462 return;
3463 }
3464
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003465 // Add this candidate
3466 CandidateSet.push_back(OverloadCandidate());
3467 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003468 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003469 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003470 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003471 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003472 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003473
3474 unsigned NumArgsInProto = Proto->getNumArgs();
3475
3476 // (C++ 13.3.2p2): A candidate function having fewer than m
3477 // parameters is viable only if it has an ellipsis in its parameter
3478 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003479 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3480 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003481 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003482 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003483 return;
3484 }
3485
3486 // (C++ 13.3.2p2): A candidate function having more than m parameters
3487 // is viable only if the (m+1)st parameter has a default argument
3488 // (8.3.6). For the purposes of overload resolution, the
3489 // parameter list is truncated on the right, so that there are
3490 // exactly m parameters.
3491 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003492 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003493 // Not enough arguments.
3494 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003495 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003496 return;
3497 }
3498
3499 // Determine the implicit conversion sequences for each of the
3500 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003501 Candidate.Conversions.resize(NumArgs);
3502 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3503 if (ArgIdx < NumArgsInProto) {
3504 // (C++ 13.3.2p3): for F to be a viable function, there shall
3505 // exist for each argument an implicit conversion sequence
3506 // (13.3.3.1) that converts that argument to the corresponding
3507 // parameter of F.
3508 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003509 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003510 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003511 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003512 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003513 if (Candidate.Conversions[ArgIdx].isBad()) {
3514 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003515 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003516 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003517 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003518 } else {
3519 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3520 // argument for which there is no corresponding parameter is
3521 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003522 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003523 }
3524 }
3525}
3526
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003527/// \brief Add all of the function declarations in the given function set to
3528/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003529void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003530 Expr **Args, unsigned NumArgs,
3531 OverloadCandidateSet& CandidateSet,
3532 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003533 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003534 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3535 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003536 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003537 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003538 cast<CXXMethodDecl>(FD)->getParent(),
3539 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003540 CandidateSet, SuppressUserConversions);
3541 else
John McCalla0296f72010-03-19 07:35:19 +00003542 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003543 SuppressUserConversions);
3544 } else {
John McCalla0296f72010-03-19 07:35:19 +00003545 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003546 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3547 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003548 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003549 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003550 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003551 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003552 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003553 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003554 else
John McCalla0296f72010-03-19 07:35:19 +00003555 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003556 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003557 Args, NumArgs, CandidateSet,
3558 SuppressUserConversions);
3559 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003560 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003561}
3562
John McCallf0f1cf02009-11-17 07:50:12 +00003563/// AddMethodCandidate - Adds a named decl (which is some kind of
3564/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003565void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003566 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003567 Expr **Args, unsigned NumArgs,
3568 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003569 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003570 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003571 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003572
3573 if (isa<UsingShadowDecl>(Decl))
3574 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3575
3576 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3577 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3578 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003579 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3580 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003581 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003582 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003583 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003584 } else {
John McCalla0296f72010-03-19 07:35:19 +00003585 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003586 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003587 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003588 }
3589}
3590
Douglas Gregor436424c2008-11-18 23:14:02 +00003591/// AddMethodCandidate - Adds the given C++ member function to the set
3592/// of candidate functions, using the given function call arguments
3593/// and the object argument (@c Object). For example, in a call
3594/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3595/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3596/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003597/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003598void
John McCalla0296f72010-03-19 07:35:19 +00003599Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003600 CXXRecordDecl *ActingContext, QualType ObjectType,
3601 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003602 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003603 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003604 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003605 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003606 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003607 assert(!isa<CXXConstructorDecl>(Method) &&
3608 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003609
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003610 if (!CandidateSet.isNewCandidate(Method))
3611 return;
3612
Douglas Gregor27381f32009-11-23 12:27:39 +00003613 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003614 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003615
Douglas Gregor436424c2008-11-18 23:14:02 +00003616 // Add this candidate
3617 CandidateSet.push_back(OverloadCandidate());
3618 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003619 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003620 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003621 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003622 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003623
3624 unsigned NumArgsInProto = Proto->getNumArgs();
3625
3626 // (C++ 13.3.2p2): A candidate function having fewer than m
3627 // parameters is viable only if it has an ellipsis in its parameter
3628 // list (8.3.5).
3629 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3630 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003631 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003632 return;
3633 }
3634
3635 // (C++ 13.3.2p2): A candidate function having more than m parameters
3636 // is viable only if the (m+1)st parameter has a default argument
3637 // (8.3.6). For the purposes of overload resolution, the
3638 // parameter list is truncated on the right, so that there are
3639 // exactly m parameters.
3640 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3641 if (NumArgs < MinRequiredArgs) {
3642 // Not enough arguments.
3643 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003644 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003645 return;
3646 }
3647
3648 Candidate.Viable = true;
3649 Candidate.Conversions.resize(NumArgs + 1);
3650
John McCall6e9f8f62009-12-03 04:06:58 +00003651 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003652 // The implicit object argument is ignored.
3653 Candidate.IgnoreObjectArgument = true;
3654 else {
3655 // Determine the implicit conversion sequence for the object
3656 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003657 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003658 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3659 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003660 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003661 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003662 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003663 return;
3664 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003665 }
3666
3667 // Determine the implicit conversion sequences for each of the
3668 // arguments.
3669 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3670 if (ArgIdx < NumArgsInProto) {
3671 // (C++ 13.3.2p3): for F to be a viable function, there shall
3672 // exist for each argument an implicit conversion sequence
3673 // (13.3.3.1) that converts that argument to the corresponding
3674 // parameter of F.
3675 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003676 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003677 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003678 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003679 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003680 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003681 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003682 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003683 break;
3684 }
3685 } else {
3686 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3687 // argument for which there is no corresponding parameter is
3688 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003689 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003690 }
3691 }
3692}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003693
Douglas Gregor97628d62009-08-21 00:16:32 +00003694/// \brief Add a C++ member function template as a candidate to the candidate
3695/// set, using template argument deduction to produce an appropriate member
3696/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003697void
Douglas Gregor97628d62009-08-21 00:16:32 +00003698Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003699 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003700 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003701 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003702 QualType ObjectType,
3703 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003704 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003705 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003706 if (!CandidateSet.isNewCandidate(MethodTmpl))
3707 return;
3708
Douglas Gregor97628d62009-08-21 00:16:32 +00003709 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003710 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003711 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003712 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003713 // candidate functions in the usual way.113) A given name can refer to one
3714 // or more function templates and also to a set of overloaded non-template
3715 // functions. In such a case, the candidate functions generated from each
3716 // function template are combined with the set of non-template candidate
3717 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003718 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003719 FunctionDecl *Specialization = 0;
3720 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003721 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003722 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003723 CandidateSet.push_back(OverloadCandidate());
3724 OverloadCandidate &Candidate = CandidateSet.back();
3725 Candidate.FoundDecl = FoundDecl;
3726 Candidate.Function = MethodTmpl->getTemplatedDecl();
3727 Candidate.Viable = false;
3728 Candidate.FailureKind = ovl_fail_bad_deduction;
3729 Candidate.IsSurrogate = false;
3730 Candidate.IgnoreObjectArgument = false;
3731 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3732 Info);
3733 return;
3734 }
Mike Stump11289f42009-09-09 15:08:12 +00003735
Douglas Gregor97628d62009-08-21 00:16:32 +00003736 // Add the function template specialization produced by template argument
3737 // deduction as a candidate.
3738 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003739 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003740 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003741 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003742 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003743 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003744}
3745
Douglas Gregor05155d82009-08-21 23:19:43 +00003746/// \brief Add a C++ function template specialization as a candidate
3747/// in the candidate set, using template argument deduction to produce
3748/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003749void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003750Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003751 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003752 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003753 Expr **Args, unsigned NumArgs,
3754 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003755 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003756 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3757 return;
3758
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003759 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003760 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003761 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003762 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003763 // candidate functions in the usual way.113) A given name can refer to one
3764 // or more function templates and also to a set of overloaded non-template
3765 // functions. In such a case, the candidate functions generated from each
3766 // function template are combined with the set of non-template candidate
3767 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003768 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003769 FunctionDecl *Specialization = 0;
3770 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003771 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003772 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003773 CandidateSet.push_back(OverloadCandidate());
3774 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003775 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003776 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3777 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003778 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003779 Candidate.IsSurrogate = false;
3780 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003781 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3782 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003783 return;
3784 }
Mike Stump11289f42009-09-09 15:08:12 +00003785
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003786 // Add the function template specialization produced by template argument
3787 // deduction as a candidate.
3788 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003789 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003790 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003791}
Mike Stump11289f42009-09-09 15:08:12 +00003792
Douglas Gregora1f013e2008-11-07 22:36:19 +00003793/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003794/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003795/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003796/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003797/// (which may or may not be the same type as the type that the
3798/// conversion function produces).
3799void
3800Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003801 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003802 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003803 Expr *From, QualType ToType,
3804 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003805 assert(!Conversion->getDescribedFunctionTemplate() &&
3806 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003807 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003808 if (!CandidateSet.isNewCandidate(Conversion))
3809 return;
3810
Douglas Gregor27381f32009-11-23 12:27:39 +00003811 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003812 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003813
Douglas Gregora1f013e2008-11-07 22:36:19 +00003814 // Add this candidate
3815 CandidateSet.push_back(OverloadCandidate());
3816 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003817 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003818 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003819 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003820 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003821 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003822 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003823 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003824 Candidate.Viable = true;
3825 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003826
Douglas Gregor6affc782010-08-19 15:37:02 +00003827 // C++ [over.match.funcs]p4:
3828 // For conversion functions, the function is considered to be a member of
3829 // the class of the implicit implied object argument for the purpose of
3830 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003831 //
3832 // Determine the implicit conversion sequence for the implicit
3833 // object parameter.
3834 QualType ImplicitParamType = From->getType();
3835 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3836 ImplicitParamType = FromPtrType->getPointeeType();
3837 CXXRecordDecl *ConversionContext
3838 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3839
3840 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003841 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003842 ConversionContext);
3843
John McCall0d1da222010-01-12 00:44:57 +00003844 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003845 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003846 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003847 return;
3848 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003849
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003850 // We won't go through a user-define type conversion function to convert a
3851 // derived to base as such conversions are given Conversion Rank. They only
3852 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3853 QualType FromCanon
3854 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3855 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3856 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3857 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003858 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003859 return;
3860 }
3861
Douglas Gregora1f013e2008-11-07 22:36:19 +00003862 // To determine what the conversion from the result of calling the
3863 // conversion function to the type we're eventually trying to
3864 // convert to (ToType), we need to synthesize a call to the
3865 // conversion function and attempt copy initialization from it. This
3866 // makes sure that we get the right semantics with respect to
3867 // lvalues/rvalues and the type. Fortunately, we can allocate this
3868 // call on the stack and we don't need its arguments to be
3869 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003870 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003871 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003872 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3873 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003874 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003875 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003876
3877 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003878 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3879 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003880 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003881 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003882 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003883 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003884 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003885 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003886 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003887
John McCall0d1da222010-01-12 00:44:57 +00003888 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003889 case ImplicitConversionSequence::StandardConversion:
3890 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003891
3892 // C++ [over.ics.user]p3:
3893 // If the user-defined conversion is specified by a specialization of a
3894 // conversion function template, the second standard conversion sequence
3895 // shall have exact match rank.
3896 if (Conversion->getPrimaryTemplate() &&
3897 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3898 Candidate.Viable = false;
3899 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3900 }
3901
Douglas Gregora1f013e2008-11-07 22:36:19 +00003902 break;
3903
3904 case ImplicitConversionSequence::BadConversion:
3905 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003906 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003907 break;
3908
3909 default:
Mike Stump11289f42009-09-09 15:08:12 +00003910 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003911 "Can only end up with a standard conversion sequence or failure");
3912 }
3913}
3914
Douglas Gregor05155d82009-08-21 23:19:43 +00003915/// \brief Adds a conversion function template specialization
3916/// candidate to the overload set, using template argument deduction
3917/// to deduce the template arguments of the conversion function
3918/// template from the type that we are converting to (C++
3919/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003920void
Douglas Gregor05155d82009-08-21 23:19:43 +00003921Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003922 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003923 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003924 Expr *From, QualType ToType,
3925 OverloadCandidateSet &CandidateSet) {
3926 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3927 "Only conversion function templates permitted here");
3928
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003929 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3930 return;
3931
John McCallbc077cf2010-02-08 23:07:23 +00003932 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003933 CXXConversionDecl *Specialization = 0;
3934 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003935 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003936 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003937 CandidateSet.push_back(OverloadCandidate());
3938 OverloadCandidate &Candidate = CandidateSet.back();
3939 Candidate.FoundDecl = FoundDecl;
3940 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3941 Candidate.Viable = false;
3942 Candidate.FailureKind = ovl_fail_bad_deduction;
3943 Candidate.IsSurrogate = false;
3944 Candidate.IgnoreObjectArgument = false;
3945 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3946 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003947 return;
3948 }
Mike Stump11289f42009-09-09 15:08:12 +00003949
Douglas Gregor05155d82009-08-21 23:19:43 +00003950 // Add the conversion function template specialization produced by
3951 // template argument deduction as a candidate.
3952 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003953 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003954 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003955}
3956
Douglas Gregorab7897a2008-11-19 22:57:39 +00003957/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3958/// converts the given @c Object to a function pointer via the
3959/// conversion function @c Conversion, and then attempts to call it
3960/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3961/// the type of function that we'll eventually be calling.
3962void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003963 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003964 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003965 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003966 QualType ObjectType,
3967 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003968 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003969 if (!CandidateSet.isNewCandidate(Conversion))
3970 return;
3971
Douglas Gregor27381f32009-11-23 12:27:39 +00003972 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003973 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003974
Douglas Gregorab7897a2008-11-19 22:57:39 +00003975 CandidateSet.push_back(OverloadCandidate());
3976 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003977 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003978 Candidate.Function = 0;
3979 Candidate.Surrogate = Conversion;
3980 Candidate.Viable = true;
3981 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003982 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003983 Candidate.Conversions.resize(NumArgs + 1);
3984
3985 // Determine the implicit conversion sequence for the implicit
3986 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003987 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00003988 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3989 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003990 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003991 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003992 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003993 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003994 return;
3995 }
3996
3997 // The first conversion is actually a user-defined conversion whose
3998 // first conversion is ObjectInit's standard conversion (which is
3999 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004000 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004001 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004002 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004003 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00004004 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004005 = Candidate.Conversions[0].UserDefined.Before;
4006 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4007
Mike Stump11289f42009-09-09 15:08:12 +00004008 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004009 unsigned NumArgsInProto = Proto->getNumArgs();
4010
4011 // (C++ 13.3.2p2): A candidate function having fewer than m
4012 // parameters is viable only if it has an ellipsis in its parameter
4013 // list (8.3.5).
4014 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4015 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004016 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004017 return;
4018 }
4019
4020 // Function types don't have any default arguments, so just check if
4021 // we have enough arguments.
4022 if (NumArgs < NumArgsInProto) {
4023 // Not enough arguments.
4024 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004025 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004026 return;
4027 }
4028
4029 // Determine the implicit conversion sequences for each of the
4030 // arguments.
4031 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4032 if (ArgIdx < NumArgsInProto) {
4033 // (C++ 13.3.2p3): for F to be a viable function, there shall
4034 // exist for each argument an implicit conversion sequence
4035 // (13.3.3.1) that converts that argument to the corresponding
4036 // parameter of F.
4037 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004038 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004039 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004040 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004041 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004042 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004043 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004044 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004045 break;
4046 }
4047 } else {
4048 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4049 // argument for which there is no corresponding parameter is
4050 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004051 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004052 }
4053 }
4054}
4055
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004056/// \brief Add overload candidates for overloaded operators that are
4057/// member functions.
4058///
4059/// Add the overloaded operator candidates that are member functions
4060/// for the operator Op that was used in an operator expression such
4061/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4062/// CandidateSet will store the added overload candidates. (C++
4063/// [over.match.oper]).
4064void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4065 SourceLocation OpLoc,
4066 Expr **Args, unsigned NumArgs,
4067 OverloadCandidateSet& CandidateSet,
4068 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004069 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4070
4071 // C++ [over.match.oper]p3:
4072 // For a unary operator @ with an operand of a type whose
4073 // cv-unqualified version is T1, and for a binary operator @ with
4074 // a left operand of a type whose cv-unqualified version is T1 and
4075 // a right operand of a type whose cv-unqualified version is T2,
4076 // three sets of candidate functions, designated member
4077 // candidates, non-member candidates and built-in candidates, are
4078 // constructed as follows:
4079 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004080
4081 // -- If T1 is a class type, the set of member candidates is the
4082 // result of the qualified lookup of T1::operator@
4083 // (13.3.1.1.1); otherwise, the set of member candidates is
4084 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004085 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004086 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004087 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004088 return;
Mike Stump11289f42009-09-09 15:08:12 +00004089
John McCall27b18f82009-11-17 02:14:36 +00004090 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4091 LookupQualifiedName(Operators, T1Rec->getDecl());
4092 Operators.suppressDiagnostics();
4093
Mike Stump11289f42009-09-09 15:08:12 +00004094 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004095 OperEnd = Operators.end();
4096 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004097 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004098 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004099 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004100 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004101 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004102}
4103
Douglas Gregora11693b2008-11-12 17:17:38 +00004104/// AddBuiltinCandidate - Add a candidate for a built-in
4105/// operator. ResultTy and ParamTys are the result and parameter types
4106/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004107/// arguments being passed to the candidate. IsAssignmentOperator
4108/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004109/// operator. NumContextualBoolArguments is the number of arguments
4110/// (at the beginning of the argument list) that will be contextually
4111/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004112void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004113 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004114 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004115 bool IsAssignmentOperator,
4116 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004117 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004118 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004119
Douglas Gregora11693b2008-11-12 17:17:38 +00004120 // Add this candidate
4121 CandidateSet.push_back(OverloadCandidate());
4122 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004123 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004124 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004125 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004126 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004127 Candidate.BuiltinTypes.ResultTy = ResultTy;
4128 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4129 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4130
4131 // Determine the implicit conversion sequences for each of the
4132 // arguments.
4133 Candidate.Viable = true;
4134 Candidate.Conversions.resize(NumArgs);
4135 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004136 // C++ [over.match.oper]p4:
4137 // For the built-in assignment operators, conversions of the
4138 // left operand are restricted as follows:
4139 // -- no temporaries are introduced to hold the left operand, and
4140 // -- no user-defined conversions are applied to the left
4141 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004142 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004143 //
4144 // We block these conversions by turning off user-defined
4145 // conversions, since that is the only way that initialization of
4146 // a reference to a non-class type can occur from something that
4147 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004148 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004149 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004150 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004151 Candidate.Conversions[ArgIdx]
4152 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004153 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004154 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004155 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004156 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004157 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004158 }
John McCall0d1da222010-01-12 00:44:57 +00004159 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004160 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004161 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004162 break;
4163 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004164 }
4165}
4166
4167/// BuiltinCandidateTypeSet - A set of types that will be used for the
4168/// candidate operator functions for built-in operators (C++
4169/// [over.built]). The types are separated into pointer types and
4170/// enumeration types.
4171class BuiltinCandidateTypeSet {
4172 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004173 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004174
4175 /// PointerTypes - The set of pointer types that will be used in the
4176 /// built-in candidates.
4177 TypeSet PointerTypes;
4178
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004179 /// MemberPointerTypes - The set of member pointer types that will be
4180 /// used in the built-in candidates.
4181 TypeSet MemberPointerTypes;
4182
Douglas Gregora11693b2008-11-12 17:17:38 +00004183 /// EnumerationTypes - The set of enumeration types that will be
4184 /// used in the built-in candidates.
4185 TypeSet EnumerationTypes;
4186
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004187 /// \brief The set of vector types that will be used in the built-in
4188 /// candidates.
4189 TypeSet VectorTypes;
4190
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004191 /// Sema - The semantic analysis instance where we are building the
4192 /// candidate type set.
4193 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004194
Douglas Gregora11693b2008-11-12 17:17:38 +00004195 /// Context - The AST context in which we will build the type sets.
4196 ASTContext &Context;
4197
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004198 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4199 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004200 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004201
4202public:
4203 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004204 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004205
Mike Stump11289f42009-09-09 15:08:12 +00004206 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004207 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004208
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004209 void AddTypesConvertedFrom(QualType Ty,
4210 SourceLocation Loc,
4211 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004212 bool AllowExplicitConversions,
4213 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004214
4215 /// pointer_begin - First pointer type found;
4216 iterator pointer_begin() { return PointerTypes.begin(); }
4217
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004218 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004219 iterator pointer_end() { return PointerTypes.end(); }
4220
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004221 /// member_pointer_begin - First member pointer type found;
4222 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4223
4224 /// member_pointer_end - Past the last member pointer type found;
4225 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4226
Douglas Gregora11693b2008-11-12 17:17:38 +00004227 /// enumeration_begin - First enumeration type found;
4228 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4229
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004230 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004231 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004232
4233 iterator vector_begin() { return VectorTypes.begin(); }
4234 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004235};
4236
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004237/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004238/// the set of pointer types along with any more-qualified variants of
4239/// that type. For example, if @p Ty is "int const *", this routine
4240/// will add "int const *", "int const volatile *", "int const
4241/// restrict *", and "int const volatile restrict *" to the set of
4242/// pointer types. Returns true if the add of @p Ty itself succeeded,
4243/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004244///
4245/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004246bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004247BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4248 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004249
Douglas Gregora11693b2008-11-12 17:17:38 +00004250 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004251 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004252 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004253
4254 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004255 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004256 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004257 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004258 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004259 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004260 buildObjCPtr = true;
4261 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004262 else
4263 assert(false && "type was not a pointer type!");
4264 }
4265 else
4266 PointeeTy = PointerTy->getPointeeType();
4267
Sebastian Redl4990a632009-11-18 20:39:26 +00004268 // Don't add qualified variants of arrays. For one, they're not allowed
4269 // (the qualifier would sink to the element type), and for another, the
4270 // only overload situation where it matters is subscript or pointer +- int,
4271 // and those shouldn't have qualifier variants anyway.
4272 if (PointeeTy->isArrayType())
4273 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004274 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004275 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004276 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004277 bool hasVolatile = VisibleQuals.hasVolatile();
4278 bool hasRestrict = VisibleQuals.hasRestrict();
4279
John McCall8ccfcb52009-09-24 19:53:00 +00004280 // Iterate through all strict supersets of BaseCVR.
4281 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4282 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004283 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4284 // in the types.
4285 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4286 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004287 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004288 if (!buildObjCPtr)
4289 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4290 else
4291 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004292 }
4293
4294 return true;
4295}
4296
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004297/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4298/// to the set of pointer types along with any more-qualified variants of
4299/// that type. For example, if @p Ty is "int const *", this routine
4300/// will add "int const *", "int const volatile *", "int const
4301/// restrict *", and "int const volatile restrict *" to the set of
4302/// pointer types. Returns true if the add of @p Ty itself succeeded,
4303/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004304///
4305/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004306bool
4307BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4308 QualType Ty) {
4309 // Insert this type.
4310 if (!MemberPointerTypes.insert(Ty))
4311 return false;
4312
John McCall8ccfcb52009-09-24 19:53:00 +00004313 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4314 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004315
John McCall8ccfcb52009-09-24 19:53:00 +00004316 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004317 // Don't add qualified variants of arrays. For one, they're not allowed
4318 // (the qualifier would sink to the element type), and for another, the
4319 // only overload situation where it matters is subscript or pointer +- int,
4320 // and those shouldn't have qualifier variants anyway.
4321 if (PointeeTy->isArrayType())
4322 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004323 const Type *ClassTy = PointerTy->getClass();
4324
4325 // Iterate through all strict supersets of the pointee type's CVR
4326 // qualifiers.
4327 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4328 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4329 if ((CVR | BaseCVR) != CVR) continue;
4330
4331 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4332 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004333 }
4334
4335 return true;
4336}
4337
Douglas Gregora11693b2008-11-12 17:17:38 +00004338/// AddTypesConvertedFrom - Add each of the types to which the type @p
4339/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004340/// primarily interested in pointer types and enumeration types. We also
4341/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004342/// AllowUserConversions is true if we should look at the conversion
4343/// functions of a class type, and AllowExplicitConversions if we
4344/// should also include the explicit conversion functions of a class
4345/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004346void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004347BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004348 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004349 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004350 bool AllowExplicitConversions,
4351 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004352 // Only deal with canonical types.
4353 Ty = Context.getCanonicalType(Ty);
4354
4355 // Look through reference types; they aren't part of the type of an
4356 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004357 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004358 Ty = RefTy->getPointeeType();
4359
4360 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004361 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004362
Sebastian Redl65ae2002009-11-05 16:36:20 +00004363 // If we're dealing with an array type, decay to the pointer.
4364 if (Ty->isArrayType())
4365 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004366 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4367 PointerTypes.insert(Ty);
4368 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004369 // Insert our type, and its more-qualified variants, into the set
4370 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004371 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004372 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004373 } else if (Ty->isMemberPointerType()) {
4374 // Member pointers are far easier, since the pointee can't be converted.
4375 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4376 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004377 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004378 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004379 } else if (Ty->isVectorType()) {
4380 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004381 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004382 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004383 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004384 // No conversion functions in incomplete types.
4385 return;
4386 }
Mike Stump11289f42009-09-09 15:08:12 +00004387
Douglas Gregora11693b2008-11-12 17:17:38 +00004388 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004389 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004390 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004391 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004392 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004393 NamedDecl *D = I.getDecl();
4394 if (isa<UsingShadowDecl>(D))
4395 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004396
Mike Stump11289f42009-09-09 15:08:12 +00004397 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004398 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004399 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004400 continue;
4401
John McCallda4458e2010-03-31 01:36:47 +00004402 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004403 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004404 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004405 VisibleQuals);
4406 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004407 }
4408 }
4409 }
4410}
4411
Douglas Gregor84605ae2009-08-24 13:43:27 +00004412/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4413/// the volatile- and non-volatile-qualified assignment operators for the
4414/// given type to the candidate set.
4415static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4416 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004417 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004418 unsigned NumArgs,
4419 OverloadCandidateSet &CandidateSet) {
4420 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004421
Douglas Gregor84605ae2009-08-24 13:43:27 +00004422 // T& operator=(T&, T)
4423 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4424 ParamTypes[1] = T;
4425 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4426 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004427
Douglas Gregor84605ae2009-08-24 13:43:27 +00004428 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4429 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004430 ParamTypes[0]
4431 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004432 ParamTypes[1] = T;
4433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004434 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004435 }
4436}
Mike Stump11289f42009-09-09 15:08:12 +00004437
Sebastian Redl1054fae2009-10-25 17:03:50 +00004438/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4439/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004440static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4441 Qualifiers VRQuals;
4442 const RecordType *TyRec;
4443 if (const MemberPointerType *RHSMPType =
4444 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004445 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004446 else
4447 TyRec = ArgExpr->getType()->getAs<RecordType>();
4448 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004449 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004450 VRQuals.addVolatile();
4451 VRQuals.addRestrict();
4452 return VRQuals;
4453 }
4454
4455 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004456 if (!ClassDecl->hasDefinition())
4457 return VRQuals;
4458
John McCallad371252010-01-20 00:46:10 +00004459 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004460 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004461
John McCallad371252010-01-20 00:46:10 +00004462 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004463 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004464 NamedDecl *D = I.getDecl();
4465 if (isa<UsingShadowDecl>(D))
4466 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4467 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004468 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4469 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4470 CanTy = ResTypeRef->getPointeeType();
4471 // Need to go down the pointer/mempointer chain and add qualifiers
4472 // as see them.
4473 bool done = false;
4474 while (!done) {
4475 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4476 CanTy = ResTypePtr->getPointeeType();
4477 else if (const MemberPointerType *ResTypeMPtr =
4478 CanTy->getAs<MemberPointerType>())
4479 CanTy = ResTypeMPtr->getPointeeType();
4480 else
4481 done = true;
4482 if (CanTy.isVolatileQualified())
4483 VRQuals.addVolatile();
4484 if (CanTy.isRestrictQualified())
4485 VRQuals.addRestrict();
4486 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4487 return VRQuals;
4488 }
4489 }
4490 }
4491 return VRQuals;
4492}
4493
Douglas Gregord08452f2008-11-19 15:42:04 +00004494/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4495/// operator overloads to the candidate set (C++ [over.built]), based
4496/// on the operator @p Op and the arguments given. For example, if the
4497/// operator is a binary '+', this routine might add "int
4498/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004499void
Mike Stump11289f42009-09-09 15:08:12 +00004500Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004501 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004502 Expr **Args, unsigned NumArgs,
4503 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004504 // The set of "promoted arithmetic types", which are the arithmetic
4505 // types are that preserved by promotion (C++ [over.built]p2). Note
4506 // that the first few of these types are the promoted integral
4507 // types; these types need to be first.
4508 // FIXME: What about complex?
4509 const unsigned FirstIntegralType = 0;
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00004510 const unsigned LastIntegralType = 15;
4511 const unsigned FirstPromotedIntegralType = 9,
4512 LastPromotedIntegralType = 15;
4513 const unsigned FirstPromotedArithmeticType = 9,
4514 LastPromotedArithmeticType = 18;
4515 const unsigned NumArithmeticTypes = 18;
Douglas Gregora11693b2008-11-12 17:17:38 +00004516 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004517 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00004518 Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004519 Context.SignedCharTy, Context.ShortTy,
4520 Context.UnsignedCharTy, Context.UnsignedShortTy,
4521 Context.IntTy, Context.LongTy, Context.LongLongTy,
4522 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4523 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4524 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004525 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4526 "Invalid first promoted integral type");
4527 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4528 == Context.UnsignedLongLongTy &&
4529 "Invalid last promoted integral type");
4530 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4531 "Invalid first promoted arithmetic type");
4532 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4533 == Context.LongDoubleTy &&
4534 "Invalid last promoted arithmetic type");
4535
Douglas Gregora11693b2008-11-12 17:17:38 +00004536 // Find all of the types that the arguments can convert to, but only
4537 // if the operator we're looking at has built-in operator candidates
4538 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004539 Qualifiers VisibleTypeConversionsQuals;
4540 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004541 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4542 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4543
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004544 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4546 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4547 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4548 OpLoc,
4549 true,
4550 (Op == OO_Exclaim ||
4551 Op == OO_AmpAmp ||
4552 Op == OO_PipePipe),
4553 VisibleTypeConversionsQuals);
4554 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004555
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004556 // C++ [over.built]p1:
4557 // If there is a user-written candidate with the same name and parameter
4558 // types as a built-in candidate operator function, the built-in operator
4559 // function is hidden and is not included in the set of candidate functions.
4560 //
4561 // The text is actually in a note, but if we don't implement it then we end
4562 // up with ambiguities when the user provides an overloaded operator for
4563 // an enumeration type. Note that only enumeration types have this problem,
4564 // so we track which enumeration types we've seen operators for.
4565 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4566 UserDefinedBinaryOperators;
4567
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004568 /// Set of (canonical) types that we've already handled.
4569 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4570
4571 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4572 if (CandidateTypes[ArgIdx].enumeration_begin()
4573 != CandidateTypes[ArgIdx].enumeration_end()) {
4574 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4575 CEnd = CandidateSet.end();
4576 C != CEnd; ++C) {
4577 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4578 continue;
4579
4580 // Check if the first parameter is of enumeration type.
4581 QualType FirstParamType
4582 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4583 if (!FirstParamType->isEnumeralType())
4584 continue;
4585
4586 // Check if the second parameter is of enumeration type.
4587 QualType SecondParamType
4588 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4589 if (!SecondParamType->isEnumeralType())
4590 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004591
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004592 // Add this operator to the set of known user-defined operators.
4593 UserDefinedBinaryOperators.insert(
4594 std::make_pair(Context.getCanonicalType(FirstParamType),
4595 Context.getCanonicalType(SecondParamType)));
4596 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004597 }
4598 }
4599
Douglas Gregora11693b2008-11-12 17:17:38 +00004600 bool isComparison = false;
4601 switch (Op) {
4602 case OO_None:
4603 case NUM_OVERLOADED_OPERATORS:
4604 assert(false && "Expected an overloaded operator");
4605 break;
4606
Douglas Gregord08452f2008-11-19 15:42:04 +00004607 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004608 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004609 goto UnaryStar;
4610 else
4611 goto BinaryStar;
4612 break;
4613
4614 case OO_Plus: // '+' is either unary or binary
4615 if (NumArgs == 1)
4616 goto UnaryPlus;
4617 else
4618 goto BinaryPlus;
4619 break;
4620
4621 case OO_Minus: // '-' is either unary or binary
4622 if (NumArgs == 1)
4623 goto UnaryMinus;
4624 else
4625 goto BinaryMinus;
4626 break;
4627
4628 case OO_Amp: // '&' is either unary or binary
4629 if (NumArgs == 1)
4630 goto UnaryAmp;
4631 else
4632 goto BinaryAmp;
4633
4634 case OO_PlusPlus:
4635 case OO_MinusMinus:
4636 // C++ [over.built]p3:
4637 //
4638 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4639 // is either volatile or empty, there exist candidate operator
4640 // functions of the form
4641 //
4642 // VQ T& operator++(VQ T&);
4643 // T operator++(VQ T&, int);
4644 //
4645 // C++ [over.built]p4:
4646 //
4647 // For every pair (T, VQ), where T is an arithmetic type other
4648 // than bool, and VQ is either volatile or empty, there exist
4649 // candidate operator functions of the form
4650 //
4651 // VQ T& operator--(VQ T&);
4652 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004653 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004654 Arith < NumArithmeticTypes; ++Arith) {
4655 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004656 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004657 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004658
4659 // Non-volatile version.
4660 if (NumArgs == 1)
4661 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4662 else
4663 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004664 // heuristic to reduce number of builtin candidates in the set.
4665 // Add volatile version only if there are conversions to a volatile type.
4666 if (VisibleTypeConversionsQuals.hasVolatile()) {
4667 // Volatile version
4668 ParamTypes[0]
4669 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4670 if (NumArgs == 1)
4671 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4672 else
4673 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4674 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004675 }
4676
4677 // C++ [over.built]p5:
4678 //
4679 // For every pair (T, VQ), where T is a cv-qualified or
4680 // cv-unqualified object type, and VQ is either volatile or
4681 // empty, there exist candidate operator functions of the form
4682 //
4683 // T*VQ& operator++(T*VQ&);
4684 // T*VQ& operator--(T*VQ&);
4685 // T* operator++(T*VQ&, int);
4686 // T* operator--(T*VQ&, int);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004687 for (BuiltinCandidateTypeSet::iterator
4688 Ptr = CandidateTypes[0].pointer_begin(),
4689 PtrEnd = CandidateTypes[0].pointer_end();
4690 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004691 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004692 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004693 continue;
4694
Mike Stump11289f42009-09-09 15:08:12 +00004695 QualType ParamTypes[2] = {
4696 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004697 };
Mike Stump11289f42009-09-09 15:08:12 +00004698
Douglas Gregord08452f2008-11-19 15:42:04 +00004699 // Without volatile
4700 if (NumArgs == 1)
4701 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4702 else
4703 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4704
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004705 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4706 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004707 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004708 ParamTypes[0]
4709 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004710 if (NumArgs == 1)
4711 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4712 else
4713 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4714 }
4715 }
4716 break;
4717
4718 UnaryStar:
4719 // C++ [over.built]p6:
4720 // For every cv-qualified or cv-unqualified object type T, there
4721 // exist candidate operator functions of the form
4722 //
4723 // T& operator*(T*);
4724 //
4725 // C++ [over.built]p7:
4726 // For every function type T, there exist candidate operator
4727 // functions of the form
4728 // T& operator*(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004729 for (BuiltinCandidateTypeSet::iterator
4730 Ptr = CandidateTypes[0].pointer_begin(),
4731 PtrEnd = CandidateTypes[0].pointer_end();
4732 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004733 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004734 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004735 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004736 &ParamTy, Args, 1, CandidateSet);
4737 }
4738 break;
4739
4740 UnaryPlus:
4741 // C++ [over.built]p8:
4742 // For every type T, there exist candidate operator functions of
4743 // the form
4744 //
4745 // T* operator+(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004746 for (BuiltinCandidateTypeSet::iterator
4747 Ptr = CandidateTypes[0].pointer_begin(),
4748 PtrEnd = CandidateTypes[0].pointer_end();
4749 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004750 QualType ParamTy = *Ptr;
4751 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
Douglas Gregord08452f2008-11-19 15:42:04 +00004754 // Fall through
4755
4756 UnaryMinus:
4757 // C++ [over.built]p9:
4758 // For every promoted arithmetic type T, there exist candidate
4759 // operator functions of the form
4760 //
4761 // T operator+(T);
4762 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004763 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004764 Arith < LastPromotedArithmeticType; ++Arith) {
4765 QualType ArithTy = ArithmeticTypes[Arith];
4766 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4767 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004768
4769 // Extension: We also add these operators for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004770 for (BuiltinCandidateTypeSet::iterator
4771 Vec = CandidateTypes[0].vector_begin(),
4772 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004773 Vec != VecEnd; ++Vec) {
4774 QualType VecTy = *Vec;
4775 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4776 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004777 break;
4778
4779 case OO_Tilde:
4780 // C++ [over.built]p10:
4781 // For every promoted integral type T, there exist candidate
4782 // operator functions of the form
4783 //
4784 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004785 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004786 Int < LastPromotedIntegralType; ++Int) {
4787 QualType IntTy = ArithmeticTypes[Int];
4788 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4789 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004790
4791 // Extension: We also add this operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004792 for (BuiltinCandidateTypeSet::iterator
4793 Vec = CandidateTypes[0].vector_begin(),
4794 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004795 Vec != VecEnd; ++Vec) {
4796 QualType VecTy = *Vec;
4797 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4798 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004799 break;
4800
Douglas Gregora11693b2008-11-12 17:17:38 +00004801 case OO_New:
4802 case OO_Delete:
4803 case OO_Array_New:
4804 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004805 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004806 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004807 break;
4808
4809 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004810 UnaryAmp:
4811 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004812 // C++ [over.match.oper]p3:
4813 // -- For the operator ',', the unary operator '&', or the
4814 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004815 break;
4816
Douglas Gregor84605ae2009-08-24 13:43:27 +00004817 case OO_EqualEqual:
4818 case OO_ExclaimEqual:
4819 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004820 // For every pointer to member type T, there exist candidate operator
4821 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004822 //
4823 // bool operator==(T,T);
4824 // bool operator!=(T,T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004825 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4826 for (BuiltinCandidateTypeSet::iterator
4827 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4828 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4829 MemPtr != MemPtrEnd;
4830 ++MemPtr) {
4831 // Don't add the same builtin candidate twice.
4832 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4833 continue;
4834
4835 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4836 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4837 }
Douglas Gregor84605ae2009-08-24 13:43:27 +00004838 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004839 AddedTypes.clear();
4840
Douglas Gregor84605ae2009-08-24 13:43:27 +00004841 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004842
Douglas Gregora11693b2008-11-12 17:17:38 +00004843 case OO_Less:
4844 case OO_Greater:
4845 case OO_LessEqual:
4846 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004847 // C++ [over.built]p15:
4848 //
4849 // For every pointer or enumeration type T, there exist
4850 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004851 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004852 // bool operator<(T, T);
4853 // bool operator>(T, T);
4854 // bool operator<=(T, T);
4855 // bool operator>=(T, T);
4856 // bool operator==(T, T);
4857 // bool operator!=(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004858 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4859 for (BuiltinCandidateTypeSet::iterator
4860 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4861 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4862 Ptr != PtrEnd; ++Ptr) {
4863 // Don't add the same builtin candidate twice.
4864 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4865 continue;
4866
4867 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004868 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004869 }
4870 for (BuiltinCandidateTypeSet::iterator
4871 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4872 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4873 Enum != EnumEnd; ++Enum) {
4874 // Don't add the same builtin candidate twice.
4875 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4876 continue;
4877
4878 QualType ParamTypes[2] = { *Enum, *Enum };
4879 CanQualType CanonType = Context.getCanonicalType(*Enum);
4880 if (!UserDefinedBinaryOperators.count(
4881 std::make_pair(CanonType, CanonType)))
4882 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4883 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004884 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004885 AddedTypes.clear();
4886
Douglas Gregora11693b2008-11-12 17:17:38 +00004887 // Fall through.
4888 isComparison = true;
4889
Douglas Gregord08452f2008-11-19 15:42:04 +00004890 BinaryPlus:
4891 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004892 if (!isComparison) {
4893 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4894
4895 // C++ [over.built]p13:
4896 //
4897 // For every cv-qualified or cv-unqualified object type T
4898 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004899 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004900 // T* operator+(T*, ptrdiff_t);
4901 // T& operator[](T*, ptrdiff_t); [BELOW]
4902 // T* operator-(T*, ptrdiff_t);
4903 // T* operator+(ptrdiff_t, T*);
4904 // T& operator[](ptrdiff_t, T*); [BELOW]
4905 //
4906 // C++ [over.built]p14:
4907 //
4908 // For every T, where T is a pointer to object type, there
4909 // exist candidate operator functions of the form
4910 //
4911 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004912 for (BuiltinCandidateTypeSet::iterator
4913 Ptr = CandidateTypes[0].pointer_begin(),
4914 PtrEnd = CandidateTypes[0].pointer_end();
4915 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004916 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4917
4918 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4919 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4920
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004921 if (Op == OO_Minus) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004922 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004923 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4924 continue;
4925
Douglas Gregora11693b2008-11-12 17:17:38 +00004926 ParamTypes[1] = *Ptr;
4927 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4928 Args, 2, CandidateSet);
4929 }
4930 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004931
4932 for (BuiltinCandidateTypeSet::iterator
4933 Ptr = CandidateTypes[1].pointer_begin(),
4934 PtrEnd = CandidateTypes[1].pointer_end();
4935 Ptr != PtrEnd; ++Ptr) {
4936 if (Op == OO_Plus) {
4937 // T* operator+(ptrdiff_t, T*);
4938 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
4939 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4940 } else {
4941 // ptrdiff_t operator-(T, T);
4942 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4943 continue;
4944
4945 QualType ParamTypes[2] = { *Ptr, *Ptr };
4946 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4947 Args, 2, CandidateSet);
4948 }
4949 }
4950
4951 AddedTypes.clear();
Douglas Gregora11693b2008-11-12 17:17:38 +00004952 }
4953 // Fall through
4954
Douglas Gregora11693b2008-11-12 17:17:38 +00004955 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004956 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004957 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004958 // C++ [over.built]p12:
4959 //
4960 // For every pair of promoted arithmetic types L and R, there
4961 // exist candidate operator functions of the form
4962 //
4963 // LR operator*(L, R);
4964 // LR operator/(L, R);
4965 // LR operator+(L, R);
4966 // LR operator-(L, R);
4967 // bool operator<(L, R);
4968 // bool operator>(L, R);
4969 // bool operator<=(L, R);
4970 // bool operator>=(L, R);
4971 // bool operator==(L, R);
4972 // bool operator!=(L, R);
4973 //
4974 // where LR is the result of the usual arithmetic conversions
4975 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004976 //
4977 // C++ [over.built]p24:
4978 //
4979 // For every pair of promoted arithmetic types L and R, there exist
4980 // candidate operator functions of the form
4981 //
4982 // LR operator?(bool, L, R);
4983 //
4984 // where LR is the result of the usual arithmetic conversions
4985 // between types L and R.
4986 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004987 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004988 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004989 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004990 Right < LastPromotedArithmeticType; ++Right) {
4991 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004992 QualType Result
4993 = isComparison
4994 ? Context.BoolTy
4995 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004996 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4997 }
4998 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004999
5000 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5001 // conditional operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005002 for (BuiltinCandidateTypeSet::iterator
5003 Vec1 = CandidateTypes[0].vector_begin(),
5004 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005005 Vec1 != Vec1End; ++Vec1)
5006 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005007 Vec2 = CandidateTypes[1].vector_begin(),
5008 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005009 Vec2 != Vec2End; ++Vec2) {
5010 QualType LandR[2] = { *Vec1, *Vec2 };
5011 QualType Result;
5012 if (isComparison)
5013 Result = Context.BoolTy;
5014 else {
5015 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5016 Result = *Vec1;
5017 else
5018 Result = *Vec2;
5019 }
5020
5021 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5022 }
5023
Douglas Gregora11693b2008-11-12 17:17:38 +00005024 break;
5025
5026 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005027 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005028 case OO_Caret:
5029 case OO_Pipe:
5030 case OO_LessLess:
5031 case OO_GreaterGreater:
5032 // C++ [over.built]p17:
5033 //
5034 // For every pair of promoted integral types L and R, there
5035 // exist candidate operator functions of the form
5036 //
5037 // LR operator%(L, R);
5038 // LR operator&(L, R);
5039 // LR operator^(L, R);
5040 // LR operator|(L, R);
5041 // L operator<<(L, R);
5042 // L operator>>(L, R);
5043 //
5044 // where LR is the result of the usual arithmetic conversions
5045 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00005046 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005047 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005048 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005049 Right < LastPromotedIntegralType; ++Right) {
5050 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
5051 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5052 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005053 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005054 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5055 }
5056 }
5057 break;
5058
5059 case OO_Equal:
5060 // C++ [over.built]p20:
5061 //
5062 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00005063 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00005064 // empty, there exist candidate operator functions of the form
5065 //
5066 // VQ T& operator=(VQ T&, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005067 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5068 for (BuiltinCandidateTypeSet::iterator
5069 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5070 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5071 Enum != EnumEnd; ++Enum) {
5072 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5073 continue;
5074
5075 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5076 CandidateSet);
5077 }
5078
5079 for (BuiltinCandidateTypeSet::iterator
5080 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5081 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5082 MemPtr != MemPtrEnd; ++MemPtr) {
5083 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5084 continue;
5085
5086 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5087 CandidateSet);
5088 }
5089 }
5090 AddedTypes.clear();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005091
5092 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005093
5094 case OO_PlusEqual:
5095 case OO_MinusEqual:
5096 // C++ [over.built]p19:
5097 //
5098 // For every pair (T, VQ), where T is any type and VQ is either
5099 // volatile or empty, there exist candidate operator functions
5100 // of the form
5101 //
5102 // T*VQ& operator=(T*VQ&, T*);
5103 //
5104 // C++ [over.built]p21:
5105 //
5106 // For every pair (T, VQ), where T is a cv-qualified or
5107 // cv-unqualified object type and VQ is either volatile or
5108 // empty, there exist candidate operator functions of the form
5109 //
5110 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5111 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005112 for (BuiltinCandidateTypeSet::iterator
5113 Ptr = CandidateTypes[0].pointer_begin(),
5114 PtrEnd = CandidateTypes[0].pointer_end();
5115 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005116 QualType ParamTypes[2];
5117 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5118
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005119 // If this is operator=, keep track of the builtin candidates we added.
5120 if (Op == OO_Equal)
5121 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5122
Douglas Gregora11693b2008-11-12 17:17:38 +00005123 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005124 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005125 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5126 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005127
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005128 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5129 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005130 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005131 ParamTypes[0]
5132 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005133 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5134 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005135 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005136 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005137
5138 if (Op == OO_Equal) {
5139 for (BuiltinCandidateTypeSet::iterator
5140 Ptr = CandidateTypes[1].pointer_begin(),
5141 PtrEnd = CandidateTypes[1].pointer_end();
5142 Ptr != PtrEnd; ++Ptr) {
5143 // Make sure we don't add the same candidate twice.
5144 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5145 continue;
5146
5147 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5148
5149 // non-volatile version
5150 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5151 /*IsAssigmentOperator=*/true);
5152
5153 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5154 VisibleTypeConversionsQuals.hasVolatile()) {
5155 // volatile version
5156 ParamTypes[0]
5157 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5158 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5159 /*IsAssigmentOperator=*/true);
5160 }
5161 }
5162 AddedTypes.clear();
5163 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005164 // Fall through.
5165
5166 case OO_StarEqual:
5167 case OO_SlashEqual:
5168 // C++ [over.built]p18:
5169 //
5170 // For every triple (L, VQ, R), where L is an arithmetic type,
5171 // VQ is either volatile or empty, and R is a promoted
5172 // arithmetic type, there exist candidate operator functions of
5173 // the form
5174 //
5175 // VQ L& operator=(VQ L&, R);
5176 // VQ L& operator*=(VQ L&, R);
5177 // VQ L& operator/=(VQ L&, R);
5178 // VQ L& operator+=(VQ L&, R);
5179 // VQ L& operator-=(VQ L&, R);
5180 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005181 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005182 Right < LastPromotedArithmeticType; ++Right) {
5183 QualType ParamTypes[2];
5184 ParamTypes[1] = ArithmeticTypes[Right];
5185
5186 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005187 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005188 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5189 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005190
5191 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005192 if (VisibleTypeConversionsQuals.hasVolatile()) {
5193 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5194 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5195 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5196 /*IsAssigmentOperator=*/Op == OO_Equal);
5197 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005198 }
5199 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005200
5201 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005202 for (BuiltinCandidateTypeSet::iterator
5203 Vec1 = CandidateTypes[0].vector_begin(),
5204 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005205 Vec1 != Vec1End; ++Vec1)
5206 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005207 Vec2 = CandidateTypes[1].vector_begin(),
5208 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005209 Vec2 != Vec2End; ++Vec2) {
5210 QualType ParamTypes[2];
5211 ParamTypes[1] = *Vec2;
5212 // Add this built-in operator as a candidate (VQ is empty).
5213 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5214 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5215 /*IsAssigmentOperator=*/Op == OO_Equal);
5216
5217 // Add this built-in operator as a candidate (VQ is 'volatile').
5218 if (VisibleTypeConversionsQuals.hasVolatile()) {
5219 ParamTypes[0] = Context.getVolatileType(*Vec1);
5220 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5221 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5222 /*IsAssigmentOperator=*/Op == OO_Equal);
5223 }
5224 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005225 break;
5226
5227 case OO_PercentEqual:
5228 case OO_LessLessEqual:
5229 case OO_GreaterGreaterEqual:
5230 case OO_AmpEqual:
5231 case OO_CaretEqual:
5232 case OO_PipeEqual:
5233 // C++ [over.built]p22:
5234 //
5235 // For every triple (L, VQ, R), where L is an integral type, VQ
5236 // is either volatile or empty, and R is a promoted integral
5237 // type, there exist candidate operator functions of the form
5238 //
5239 // VQ L& operator%=(VQ L&, R);
5240 // VQ L& operator<<=(VQ L&, R);
5241 // VQ L& operator>>=(VQ L&, R);
5242 // VQ L& operator&=(VQ L&, R);
5243 // VQ L& operator^=(VQ L&, R);
5244 // VQ L& operator|=(VQ L&, R);
5245 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005246 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005247 Right < LastPromotedIntegralType; ++Right) {
5248 QualType ParamTypes[2];
5249 ParamTypes[1] = ArithmeticTypes[Right];
5250
5251 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005252 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005253 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005254 if (VisibleTypeConversionsQuals.hasVolatile()) {
5255 // Add this built-in operator as a candidate (VQ is 'volatile').
5256 ParamTypes[0] = ArithmeticTypes[Left];
5257 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5258 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5259 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5260 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005261 }
5262 }
5263 break;
5264
Douglas Gregord08452f2008-11-19 15:42:04 +00005265 case OO_Exclaim: {
5266 // C++ [over.operator]p23:
5267 //
5268 // There also exist candidate operator functions of the form
5269 //
Mike Stump11289f42009-09-09 15:08:12 +00005270 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005271 // bool operator&&(bool, bool); [BELOW]
5272 // bool operator||(bool, bool); [BELOW]
5273 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005274 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5275 /*IsAssignmentOperator=*/false,
5276 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005277 break;
5278 }
5279
Douglas Gregora11693b2008-11-12 17:17:38 +00005280 case OO_AmpAmp:
5281 case OO_PipePipe: {
5282 // C++ [over.operator]p23:
5283 //
5284 // There also exist candidate operator functions of the form
5285 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005286 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005287 // bool operator&&(bool, bool);
5288 // bool operator||(bool, bool);
5289 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005290 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5291 /*IsAssignmentOperator=*/false,
5292 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005293 break;
5294 }
5295
5296 case OO_Subscript:
5297 // C++ [over.built]p13:
5298 //
5299 // For every cv-qualified or cv-unqualified object type T there
5300 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005301 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005302 // T* operator+(T*, ptrdiff_t); [ABOVE]
5303 // T& operator[](T*, ptrdiff_t);
5304 // T* operator-(T*, ptrdiff_t); [ABOVE]
5305 // T* operator+(ptrdiff_t, T*); [ABOVE]
5306 // T& operator[](ptrdiff_t, T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005307 for (BuiltinCandidateTypeSet::iterator
5308 Ptr = CandidateTypes[0].pointer_begin(),
5309 PtrEnd = CandidateTypes[0].pointer_end();
5310 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005311 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005312 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005313 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005314
5315 // T& operator[](T*, ptrdiff_t)
5316 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005317 }
5318
5319 for (BuiltinCandidateTypeSet::iterator
5320 Ptr = CandidateTypes[1].pointer_begin(),
5321 PtrEnd = CandidateTypes[1].pointer_end();
5322 Ptr != PtrEnd; ++Ptr) {
5323 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5324 QualType PointeeType = (*Ptr)->getPointeeType();
5325 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5326
5327 // T& operator[](ptrdiff_t, T*)
Douglas Gregora11693b2008-11-12 17:17:38 +00005328 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005329 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005330 break;
5331
5332 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005333 // C++ [over.built]p11:
5334 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5335 // C1 is the same type as C2 or is a derived class of C2, T is an object
5336 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5337 // there exist candidate operator functions of the form
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005338 //
5339 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5340 //
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005341 // where CV12 is the union of CV1 and CV2.
5342 {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005343 for (BuiltinCandidateTypeSet::iterator
5344 Ptr = CandidateTypes[0].pointer_begin(),
5345 PtrEnd = CandidateTypes[0].pointer_end();
5346 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005347 QualType C1Ty = (*Ptr);
5348 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005349 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005350 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5351 if (!isa<RecordType>(C1))
5352 continue;
5353 // heuristic to reduce number of builtin candidates in the set.
5354 // Add volatile/restrict version only if there are conversions to a
5355 // volatile/restrict type.
5356 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5357 continue;
5358 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5359 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005360 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005361 MemPtr = CandidateTypes[1].member_pointer_begin(),
5362 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005363 MemPtr != MemPtrEnd; ++MemPtr) {
5364 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5365 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005366 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005367 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5368 break;
5369 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5370 // build CV12 T&
5371 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005372 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5373 T.isVolatileQualified())
5374 continue;
5375 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5376 T.isRestrictQualified())
5377 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005378 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005379 QualType ResultTy = Context.getLValueReferenceType(T);
5380 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5381 }
5382 }
5383 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005384 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005385
5386 case OO_Conditional:
5387 // Note that we don't consider the first argument, since it has been
5388 // contextually converted to bool long ago. The candidates below are
5389 // therefore added as binary.
5390 //
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005391 // C++ [over.built]p25:
5392 // For every type T, where T is a pointer, pointer-to-member, or scoped
5393 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl1a99f442009-04-16 17:51:27 +00005394 //
5395 // T operator?(bool, T, T);
5396 //
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005397 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5398 for (BuiltinCandidateTypeSet::iterator
5399 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5400 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5401 Ptr != PtrEnd; ++Ptr) {
5402 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5403 continue;
5404
5405 QualType ParamTypes[2] = { *Ptr, *Ptr };
5406 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5407 }
5408
5409 for (BuiltinCandidateTypeSet::iterator
5410 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5411 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5412 MemPtr != MemPtrEnd; ++MemPtr) {
5413 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5414 continue;
5415
5416 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5417 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5418 }
5419
5420 if (getLangOptions().CPlusPlus0x) {
5421 for (BuiltinCandidateTypeSet::iterator
5422 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5423 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5424 Enum != EnumEnd; ++Enum) {
5425 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5426 continue;
5427
5428 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5429 continue;
5430
5431 QualType ParamTypes[2] = { *Enum, *Enum };
5432 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5433 }
5434 }
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005435 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005436 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005437 }
5438}
5439
Douglas Gregore254f902009-02-04 00:32:51 +00005440/// \brief Add function candidates found via argument-dependent lookup
5441/// to the set of overloading candidates.
5442///
5443/// This routine performs argument-dependent name lookup based on the
5444/// given function name (which may also be an operator name) and adds
5445/// all of the overload candidates found by ADL to the overload
5446/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005447void
Douglas Gregore254f902009-02-04 00:32:51 +00005448Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005449 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005450 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005451 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005452 OverloadCandidateSet& CandidateSet,
5453 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005454 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005455
John McCall91f61fc2010-01-26 06:04:06 +00005456 // FIXME: This approach for uniquing ADL results (and removing
5457 // redundant candidates from the set) relies on pointer-equality,
5458 // which means we need to key off the canonical decl. However,
5459 // always going back to the canonical decl might not get us the
5460 // right set of default arguments. What default arguments are
5461 // we supposed to consider on ADL candidates, anyway?
5462
Douglas Gregorcabea402009-09-22 15:41:20 +00005463 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005464 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005465
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005466 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005467 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5468 CandEnd = CandidateSet.end();
5469 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005470 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005471 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005472 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005473 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005474 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005475
5476 // For each of the ADL candidates we found, add it to the overload
5477 // set.
John McCall8fe68082010-01-26 07:16:45 +00005478 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005479 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005480 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005481 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005482 continue;
5483
John McCalla0296f72010-03-19 07:35:19 +00005484 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005485 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005486 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005487 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005488 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005489 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005490 }
Douglas Gregore254f902009-02-04 00:32:51 +00005491}
5492
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005493/// isBetterOverloadCandidate - Determines whether the first overload
5494/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005495bool
John McCall5c32be02010-08-24 20:38:10 +00005496isBetterOverloadCandidate(Sema &S,
5497 const OverloadCandidate& Cand1,
5498 const OverloadCandidate& Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005499 SourceLocation Loc,
5500 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005501 // Define viable functions to be better candidates than non-viable
5502 // functions.
5503 if (!Cand2.Viable)
5504 return Cand1.Viable;
5505 else if (!Cand1.Viable)
5506 return false;
5507
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005508 // C++ [over.match.best]p1:
5509 //
5510 // -- if F is a static member function, ICS1(F) is defined such
5511 // that ICS1(F) is neither better nor worse than ICS1(G) for
5512 // any function G, and, symmetrically, ICS1(G) is neither
5513 // better nor worse than ICS1(F).
5514 unsigned StartArg = 0;
5515 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5516 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005517
Douglas Gregord3cb3562009-07-07 23:38:56 +00005518 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005519 // A viable function F1 is defined to be a better function than another
5520 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005521 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005522 unsigned NumArgs = Cand1.Conversions.size();
5523 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5524 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005525 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005526 switch (CompareImplicitConversionSequences(S,
5527 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005528 Cand2.Conversions[ArgIdx])) {
5529 case ImplicitConversionSequence::Better:
5530 // Cand1 has a better conversion sequence.
5531 HasBetterConversion = true;
5532 break;
5533
5534 case ImplicitConversionSequence::Worse:
5535 // Cand1 can't be better than Cand2.
5536 return false;
5537
5538 case ImplicitConversionSequence::Indistinguishable:
5539 // Do nothing.
5540 break;
5541 }
5542 }
5543
Mike Stump11289f42009-09-09 15:08:12 +00005544 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005545 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005546 if (HasBetterConversion)
5547 return true;
5548
Mike Stump11289f42009-09-09 15:08:12 +00005549 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005550 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005551 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005552 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5553 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005554
5555 // -- F1 and F2 are function template specializations, and the function
5556 // template for F1 is more specialized than the template for F2
5557 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005558 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005559 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5560 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005561 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005562 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5563 Cand2.Function->getPrimaryTemplate(),
5564 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005565 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5566 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005567 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005568
Douglas Gregora1f013e2008-11-07 22:36:19 +00005569 // -- the context is an initialization by user-defined conversion
5570 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5571 // from the return type of F1 to the destination type (i.e.,
5572 // the type of the entity being initialized) is a better
5573 // conversion sequence than the standard conversion sequence
5574 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005575 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005576 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005577 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005578 switch (CompareStandardConversionSequences(S,
5579 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005580 Cand2.FinalConversion)) {
5581 case ImplicitConversionSequence::Better:
5582 // Cand1 has a better conversion sequence.
5583 return true;
5584
5585 case ImplicitConversionSequence::Worse:
5586 // Cand1 can't be better than Cand2.
5587 return false;
5588
5589 case ImplicitConversionSequence::Indistinguishable:
5590 // Do nothing
5591 break;
5592 }
5593 }
5594
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005595 return false;
5596}
5597
Mike Stump11289f42009-09-09 15:08:12 +00005598/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005599/// within an overload candidate set.
5600///
5601/// \param CandidateSet the set of candidate functions.
5602///
5603/// \param Loc the location of the function name (or operator symbol) for
5604/// which overload resolution occurs.
5605///
Mike Stump11289f42009-09-09 15:08:12 +00005606/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005607/// function, Best points to the candidate function found.
5608///
5609/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005610OverloadingResult
5611OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005612 iterator& Best,
5613 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005614 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005615 Best = end();
5616 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5617 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005618 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5619 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005620 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005621 }
5622
5623 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005624 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005625 return OR_No_Viable_Function;
5626
5627 // Make sure that this function is better than every other viable
5628 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005629 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005630 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005631 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005632 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5633 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005634 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005635 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005636 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005637 }
Mike Stump11289f42009-09-09 15:08:12 +00005638
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005639 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005640 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005641 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005642 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005643 return OR_Deleted;
5644
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005645 // C++ [basic.def.odr]p2:
5646 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005647 // when referred to from a potentially-evaluated expression. [Note: this
5648 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005649 // (clause 13), user-defined conversions (12.3.2), allocation function for
5650 // placement new (5.3.4), as well as non-default initialization (8.5).
5651 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005652 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005653
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005654 return OR_Success;
5655}
5656
John McCall53262c92010-01-12 02:15:36 +00005657namespace {
5658
5659enum OverloadCandidateKind {
5660 oc_function,
5661 oc_method,
5662 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005663 oc_function_template,
5664 oc_method_template,
5665 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005666 oc_implicit_default_constructor,
5667 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005668 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005669};
5670
John McCalle1ac8d12010-01-13 00:25:19 +00005671OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5672 FunctionDecl *Fn,
5673 std::string &Description) {
5674 bool isTemplate = false;
5675
5676 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5677 isTemplate = true;
5678 Description = S.getTemplateArgumentBindingsText(
5679 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5680 }
John McCallfd0b2f82010-01-06 09:43:14 +00005681
5682 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005683 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005684 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005685
John McCall53262c92010-01-12 02:15:36 +00005686 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5687 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005688 }
5689
5690 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5691 // This actually gets spelled 'candidate function' for now, but
5692 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005693 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005694 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005695
Douglas Gregorec3bec02010-09-27 22:37:28 +00005696 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005697 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005698 return oc_implicit_copy_assignment;
5699 }
5700
John McCalle1ac8d12010-01-13 00:25:19 +00005701 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005702}
5703
5704} // end anonymous namespace
5705
5706// Notes the location of an overload candidate.
5707void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005708 std::string FnDesc;
5709 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5710 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5711 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005712}
5713
John McCall0d1da222010-01-12 00:44:57 +00005714/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5715/// "lead" diagnostic; it will be given two arguments, the source and
5716/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005717void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5718 Sema &S,
5719 SourceLocation CaretLoc,
5720 const PartialDiagnostic &PDiag) const {
5721 S.Diag(CaretLoc, PDiag)
5722 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005723 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005724 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5725 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005726 }
John McCall12f97bc2010-01-08 04:41:39 +00005727}
5728
John McCall0d1da222010-01-12 00:44:57 +00005729namespace {
5730
John McCall6a61b522010-01-13 09:16:55 +00005731void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5732 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5733 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005734 assert(Cand->Function && "for now, candidate must be a function");
5735 FunctionDecl *Fn = Cand->Function;
5736
5737 // There's a conversion slot for the object argument if this is a
5738 // non-constructor method. Note that 'I' corresponds the
5739 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005740 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005741 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005742 if (I == 0)
5743 isObjectArgument = true;
5744 else
5745 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005746 }
5747
John McCalle1ac8d12010-01-13 00:25:19 +00005748 std::string FnDesc;
5749 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5750
John McCall6a61b522010-01-13 09:16:55 +00005751 Expr *FromExpr = Conv.Bad.FromExpr;
5752 QualType FromTy = Conv.Bad.getFromType();
5753 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005754
John McCallfb7ad0f2010-02-02 02:42:52 +00005755 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005756 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005757 Expr *E = FromExpr->IgnoreParens();
5758 if (isa<UnaryOperator>(E))
5759 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005760 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005761
5762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5763 << (unsigned) FnKind << FnDesc
5764 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5765 << ToTy << Name << I+1;
5766 return;
5767 }
5768
John McCall6d174642010-01-23 08:10:49 +00005769 // Do some hand-waving analysis to see if the non-viability is due
5770 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005771 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5772 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5773 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5774 CToTy = RT->getPointeeType();
5775 else {
5776 // TODO: detect and diagnose the full richness of const mismatches.
5777 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5778 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5779 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5780 }
5781
5782 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5783 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5784 // It is dumb that we have to do this here.
5785 while (isa<ArrayType>(CFromTy))
5786 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5787 while (isa<ArrayType>(CToTy))
5788 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5789
5790 Qualifiers FromQs = CFromTy.getQualifiers();
5791 Qualifiers ToQs = CToTy.getQualifiers();
5792
5793 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5794 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5795 << (unsigned) FnKind << FnDesc
5796 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5797 << FromTy
5798 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5799 << (unsigned) isObjectArgument << I+1;
5800 return;
5801 }
5802
5803 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5804 assert(CVR && "unexpected qualifiers mismatch");
5805
5806 if (isObjectArgument) {
5807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5808 << (unsigned) FnKind << FnDesc
5809 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5810 << FromTy << (CVR - 1);
5811 } else {
5812 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5813 << (unsigned) FnKind << FnDesc
5814 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5815 << FromTy << (CVR - 1) << I+1;
5816 }
5817 return;
5818 }
5819
John McCall6d174642010-01-23 08:10:49 +00005820 // Diagnose references or pointers to incomplete types differently,
5821 // since it's far from impossible that the incompleteness triggered
5822 // the failure.
5823 QualType TempFromTy = FromTy.getNonReferenceType();
5824 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5825 TempFromTy = PTy->getPointeeType();
5826 if (TempFromTy->isIncompleteType()) {
5827 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5828 << (unsigned) FnKind << FnDesc
5829 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5830 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5831 return;
5832 }
5833
Douglas Gregor56f2e342010-06-30 23:01:39 +00005834 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005835 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005836 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5837 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5838 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5839 FromPtrTy->getPointeeType()) &&
5840 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5841 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5842 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5843 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005844 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005845 }
5846 } else if (const ObjCObjectPointerType *FromPtrTy
5847 = FromTy->getAs<ObjCObjectPointerType>()) {
5848 if (const ObjCObjectPointerType *ToPtrTy
5849 = ToTy->getAs<ObjCObjectPointerType>())
5850 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5851 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5852 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5853 FromPtrTy->getPointeeType()) &&
5854 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005855 BaseToDerivedConversion = 2;
5856 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5857 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5858 !FromTy->isIncompleteType() &&
5859 !ToRefTy->getPointeeType()->isIncompleteType() &&
5860 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5861 BaseToDerivedConversion = 3;
5862 }
5863
5864 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005865 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005866 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005867 << (unsigned) FnKind << FnDesc
5868 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005869 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005870 << FromTy << ToTy << I+1;
5871 return;
5872 }
5873
John McCall47000992010-01-14 03:28:57 +00005874 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5876 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005877 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005878 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005879}
5880
5881void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5882 unsigned NumFormalArgs) {
5883 // TODO: treat calls to a missing default constructor as a special case
5884
5885 FunctionDecl *Fn = Cand->Function;
5886 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5887
5888 unsigned MinParams = Fn->getMinRequiredArguments();
5889
5890 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005891 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005892 unsigned mode, modeCount;
5893 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005894 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5895 (Cand->FailureKind == ovl_fail_bad_deduction &&
5896 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005897 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5898 mode = 0; // "at least"
5899 else
5900 mode = 2; // "exactly"
5901 modeCount = MinParams;
5902 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005903 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5904 (Cand->FailureKind == ovl_fail_bad_deduction &&
5905 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005906 if (MinParams != FnTy->getNumArgs())
5907 mode = 1; // "at most"
5908 else
5909 mode = 2; // "exactly"
5910 modeCount = FnTy->getNumArgs();
5911 }
5912
5913 std::string Description;
5914 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5915
5916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005917 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5918 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005919}
5920
John McCall8b9ed552010-02-01 18:53:26 +00005921/// Diagnose a failed template-argument deduction.
5922void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5923 Expr **Args, unsigned NumArgs) {
5924 FunctionDecl *Fn = Cand->Function; // pattern
5925
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005926 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005927 NamedDecl *ParamD;
5928 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5929 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5930 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005931 switch (Cand->DeductionFailure.Result) {
5932 case Sema::TDK_Success:
5933 llvm_unreachable("TDK_success while diagnosing bad deduction");
5934
5935 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005936 assert(ParamD && "no parameter found for incomplete deduction result");
5937 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5938 << ParamD->getDeclName();
5939 return;
5940 }
5941
John McCall42d7d192010-08-05 09:05:08 +00005942 case Sema::TDK_Underqualified: {
5943 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5944 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5945
5946 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5947
5948 // Param will have been canonicalized, but it should just be a
5949 // qualified version of ParamD, so move the qualifiers to that.
5950 QualifierCollector Qs(S.Context);
5951 Qs.strip(Param);
5952 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5953 assert(S.Context.hasSameType(Param, NonCanonParam));
5954
5955 // Arg has also been canonicalized, but there's nothing we can do
5956 // about that. It also doesn't matter as much, because it won't
5957 // have any template parameters in it (because deduction isn't
5958 // done on dependent types).
5959 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5960
5961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5962 << ParamD->getDeclName() << Arg << NonCanonParam;
5963 return;
5964 }
5965
5966 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005967 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005968 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005969 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005970 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005971 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005972 which = 1;
5973 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005974 which = 2;
5975 }
5976
5977 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5978 << which << ParamD->getDeclName()
5979 << *Cand->DeductionFailure.getFirstArg()
5980 << *Cand->DeductionFailure.getSecondArg();
5981 return;
5982 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005983
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005984 case Sema::TDK_InvalidExplicitArguments:
5985 assert(ParamD && "no parameter found for invalid explicit arguments");
5986 if (ParamD->getDeclName())
5987 S.Diag(Fn->getLocation(),
5988 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5989 << ParamD->getDeclName();
5990 else {
5991 int index = 0;
5992 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5993 index = TTP->getIndex();
5994 else if (NonTypeTemplateParmDecl *NTTP
5995 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5996 index = NTTP->getIndex();
5997 else
5998 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5999 S.Diag(Fn->getLocation(),
6000 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6001 << (index + 1);
6002 }
6003 return;
6004
Douglas Gregor02eb4832010-05-08 18:13:28 +00006005 case Sema::TDK_TooManyArguments:
6006 case Sema::TDK_TooFewArguments:
6007 DiagnoseArityMismatch(S, Cand, NumArgs);
6008 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006009
6010 case Sema::TDK_InstantiationDepth:
6011 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6012 return;
6013
6014 case Sema::TDK_SubstitutionFailure: {
6015 std::string ArgString;
6016 if (TemplateArgumentList *Args
6017 = Cand->DeductionFailure.getTemplateArgumentList())
6018 ArgString = S.getTemplateArgumentBindingsText(
6019 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6020 *Args);
6021 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6022 << ArgString;
6023 return;
6024 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006025
John McCall8b9ed552010-02-01 18:53:26 +00006026 // TODO: diagnose these individually, then kill off
6027 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006028 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006029 case Sema::TDK_FailedOverloadResolution:
6030 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6031 return;
6032 }
6033}
6034
6035/// Generates a 'note' diagnostic for an overload candidate. We've
6036/// already generated a primary error at the call site.
6037///
6038/// It really does need to be a single diagnostic with its caret
6039/// pointed at the candidate declaration. Yes, this creates some
6040/// major challenges of technical writing. Yes, this makes pointing
6041/// out problems with specific arguments quite awkward. It's still
6042/// better than generating twenty screens of text for every failed
6043/// overload.
6044///
6045/// It would be great to be able to express per-candidate problems
6046/// more richly for those diagnostic clients that cared, but we'd
6047/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006048void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6049 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006050 FunctionDecl *Fn = Cand->Function;
6051
John McCall12f97bc2010-01-08 04:41:39 +00006052 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006053 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006054 std::string FnDesc;
6055 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006056
6057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006058 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006059 return;
John McCall12f97bc2010-01-08 04:41:39 +00006060 }
6061
John McCalle1ac8d12010-01-13 00:25:19 +00006062 // We don't really have anything else to say about viable candidates.
6063 if (Cand->Viable) {
6064 S.NoteOverloadCandidate(Fn);
6065 return;
6066 }
John McCall0d1da222010-01-12 00:44:57 +00006067
John McCall6a61b522010-01-13 09:16:55 +00006068 switch (Cand->FailureKind) {
6069 case ovl_fail_too_many_arguments:
6070 case ovl_fail_too_few_arguments:
6071 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006072
John McCall6a61b522010-01-13 09:16:55 +00006073 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006074 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6075
John McCallfe796dd2010-01-23 05:17:32 +00006076 case ovl_fail_trivial_conversion:
6077 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006078 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006079 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006080
John McCall65eb8792010-02-25 01:37:24 +00006081 case ovl_fail_bad_conversion: {
6082 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6083 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006084 if (Cand->Conversions[I].isBad())
6085 return DiagnoseBadConversion(S, Cand, I);
6086
6087 // FIXME: this currently happens when we're called from SemaInit
6088 // when user-conversion overload fails. Figure out how to handle
6089 // those conditions and diagnose them well.
6090 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006091 }
John McCall65eb8792010-02-25 01:37:24 +00006092 }
John McCalld3224162010-01-08 00:58:21 +00006093}
6094
6095void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6096 // Desugar the type of the surrogate down to a function type,
6097 // retaining as many typedefs as possible while still showing
6098 // the function type (and, therefore, its parameter types).
6099 QualType FnType = Cand->Surrogate->getConversionType();
6100 bool isLValueReference = false;
6101 bool isRValueReference = false;
6102 bool isPointer = false;
6103 if (const LValueReferenceType *FnTypeRef =
6104 FnType->getAs<LValueReferenceType>()) {
6105 FnType = FnTypeRef->getPointeeType();
6106 isLValueReference = true;
6107 } else if (const RValueReferenceType *FnTypeRef =
6108 FnType->getAs<RValueReferenceType>()) {
6109 FnType = FnTypeRef->getPointeeType();
6110 isRValueReference = true;
6111 }
6112 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6113 FnType = FnTypePtr->getPointeeType();
6114 isPointer = true;
6115 }
6116 // Desugar down to a function type.
6117 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6118 // Reconstruct the pointer/reference as appropriate.
6119 if (isPointer) FnType = S.Context.getPointerType(FnType);
6120 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6121 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6122
6123 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6124 << FnType;
6125}
6126
6127void NoteBuiltinOperatorCandidate(Sema &S,
6128 const char *Opc,
6129 SourceLocation OpLoc,
6130 OverloadCandidate *Cand) {
6131 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6132 std::string TypeStr("operator");
6133 TypeStr += Opc;
6134 TypeStr += "(";
6135 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6136 if (Cand->Conversions.size() == 1) {
6137 TypeStr += ")";
6138 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6139 } else {
6140 TypeStr += ", ";
6141 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6142 TypeStr += ")";
6143 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6144 }
6145}
6146
6147void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6148 OverloadCandidate *Cand) {
6149 unsigned NoOperands = Cand->Conversions.size();
6150 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6151 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006152 if (ICS.isBad()) break; // all meaningless after first invalid
6153 if (!ICS.isAmbiguous()) continue;
6154
John McCall5c32be02010-08-24 20:38:10 +00006155 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006156 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006157 }
6158}
6159
John McCall3712d9e2010-01-15 23:32:50 +00006160SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6161 if (Cand->Function)
6162 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006163 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006164 return Cand->Surrogate->getLocation();
6165 return SourceLocation();
6166}
6167
John McCallad2587a2010-01-12 00:48:53 +00006168struct CompareOverloadCandidatesForDisplay {
6169 Sema &S;
6170 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006171
6172 bool operator()(const OverloadCandidate *L,
6173 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006174 // Fast-path this check.
6175 if (L == R) return false;
6176
John McCall12f97bc2010-01-08 04:41:39 +00006177 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006178 if (L->Viable) {
6179 if (!R->Viable) return true;
6180
6181 // TODO: introduce a tri-valued comparison for overload
6182 // candidates. Would be more worthwhile if we had a sort
6183 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006184 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6185 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006186 } else if (R->Viable)
6187 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006188
John McCall3712d9e2010-01-15 23:32:50 +00006189 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006190
John McCall3712d9e2010-01-15 23:32:50 +00006191 // Criteria by which we can sort non-viable candidates:
6192 if (!L->Viable) {
6193 // 1. Arity mismatches come after other candidates.
6194 if (L->FailureKind == ovl_fail_too_many_arguments ||
6195 L->FailureKind == ovl_fail_too_few_arguments)
6196 return false;
6197 if (R->FailureKind == ovl_fail_too_many_arguments ||
6198 R->FailureKind == ovl_fail_too_few_arguments)
6199 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006200
John McCallfe796dd2010-01-23 05:17:32 +00006201 // 2. Bad conversions come first and are ordered by the number
6202 // of bad conversions and quality of good conversions.
6203 if (L->FailureKind == ovl_fail_bad_conversion) {
6204 if (R->FailureKind != ovl_fail_bad_conversion)
6205 return true;
6206
6207 // If there's any ordering between the defined conversions...
6208 // FIXME: this might not be transitive.
6209 assert(L->Conversions.size() == R->Conversions.size());
6210
6211 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006212 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6213 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006214 switch (CompareImplicitConversionSequences(S,
6215 L->Conversions[I],
6216 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006217 case ImplicitConversionSequence::Better:
6218 leftBetter++;
6219 break;
6220
6221 case ImplicitConversionSequence::Worse:
6222 leftBetter--;
6223 break;
6224
6225 case ImplicitConversionSequence::Indistinguishable:
6226 break;
6227 }
6228 }
6229 if (leftBetter > 0) return true;
6230 if (leftBetter < 0) return false;
6231
6232 } else if (R->FailureKind == ovl_fail_bad_conversion)
6233 return false;
6234
John McCall3712d9e2010-01-15 23:32:50 +00006235 // TODO: others?
6236 }
6237
6238 // Sort everything else by location.
6239 SourceLocation LLoc = GetLocationForCandidate(L);
6240 SourceLocation RLoc = GetLocationForCandidate(R);
6241
6242 // Put candidates without locations (e.g. builtins) at the end.
6243 if (LLoc.isInvalid()) return false;
6244 if (RLoc.isInvalid()) return true;
6245
6246 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006247 }
6248};
6249
John McCallfe796dd2010-01-23 05:17:32 +00006250/// CompleteNonViableCandidate - Normally, overload resolution only
6251/// computes up to the first
6252void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6253 Expr **Args, unsigned NumArgs) {
6254 assert(!Cand->Viable);
6255
6256 // Don't do anything on failures other than bad conversion.
6257 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6258
6259 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006260 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006261 unsigned ConvCount = Cand->Conversions.size();
6262 while (true) {
6263 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6264 ConvIdx++;
6265 if (Cand->Conversions[ConvIdx - 1].isBad())
6266 break;
6267 }
6268
6269 if (ConvIdx == ConvCount)
6270 return;
6271
John McCall65eb8792010-02-25 01:37:24 +00006272 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6273 "remaining conversion is initialized?");
6274
Douglas Gregoradc7a702010-04-16 17:45:54 +00006275 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006276 // operation somehow.
6277 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006278
6279 const FunctionProtoType* Proto;
6280 unsigned ArgIdx = ConvIdx;
6281
6282 if (Cand->IsSurrogate) {
6283 QualType ConvType
6284 = Cand->Surrogate->getConversionType().getNonReferenceType();
6285 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6286 ConvType = ConvPtrType->getPointeeType();
6287 Proto = ConvType->getAs<FunctionProtoType>();
6288 ArgIdx--;
6289 } else if (Cand->Function) {
6290 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6291 if (isa<CXXMethodDecl>(Cand->Function) &&
6292 !isa<CXXConstructorDecl>(Cand->Function))
6293 ArgIdx--;
6294 } else {
6295 // Builtin binary operator with a bad first conversion.
6296 assert(ConvCount <= 3);
6297 for (; ConvIdx != ConvCount; ++ConvIdx)
6298 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006299 = TryCopyInitialization(S, Args[ConvIdx],
6300 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6301 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006302 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006303 return;
6304 }
6305
6306 // Fill in the rest of the conversions.
6307 unsigned NumArgsInProto = Proto->getNumArgs();
6308 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6309 if (ArgIdx < NumArgsInProto)
6310 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006311 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6312 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006313 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006314 else
6315 Cand->Conversions[ConvIdx].setEllipsis();
6316 }
6317}
6318
John McCalld3224162010-01-08 00:58:21 +00006319} // end anonymous namespace
6320
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006321/// PrintOverloadCandidates - When overload resolution fails, prints
6322/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006323/// set.
John McCall5c32be02010-08-24 20:38:10 +00006324void OverloadCandidateSet::NoteCandidates(Sema &S,
6325 OverloadCandidateDisplayKind OCD,
6326 Expr **Args, unsigned NumArgs,
6327 const char *Opc,
6328 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006329 // Sort the candidates by viability and position. Sorting directly would
6330 // be prohibitive, so we make a set of pointers and sort those.
6331 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006332 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6333 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006334 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006335 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006336 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006337 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006338 if (Cand->Function || Cand->IsSurrogate)
6339 Cands.push_back(Cand);
6340 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6341 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006342 }
6343 }
6344
John McCallad2587a2010-01-12 00:48:53 +00006345 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006346 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006347
John McCall0d1da222010-01-12 00:44:57 +00006348 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006349
John McCall12f97bc2010-01-08 04:41:39 +00006350 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006351 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006352 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006353 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6354 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006355
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006356 // Set an arbitrary limit on the number of candidate functions we'll spam
6357 // the user with. FIXME: This limit should depend on details of the
6358 // candidate list.
6359 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6360 break;
6361 }
6362 ++CandsShown;
6363
John McCalld3224162010-01-08 00:58:21 +00006364 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006365 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006366 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006367 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006368 else {
6369 assert(Cand->Viable &&
6370 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006371 // Generally we only see ambiguities including viable builtin
6372 // operators if overload resolution got screwed up by an
6373 // ambiguous user-defined conversion.
6374 //
6375 // FIXME: It's quite possible for different conversions to see
6376 // different ambiguities, though.
6377 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006378 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006379 ReportedAmbiguousConversions = true;
6380 }
John McCalld3224162010-01-08 00:58:21 +00006381
John McCall0d1da222010-01-12 00:44:57 +00006382 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006383 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006384 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006385 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006386
6387 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006388 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006389}
6390
John McCalla0296f72010-03-19 07:35:19 +00006391static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006392 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006393 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006394
John McCalla0296f72010-03-19 07:35:19 +00006395 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006396}
6397
Douglas Gregorcd695e52008-11-10 20:40:00 +00006398/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6399/// an overloaded function (C++ [over.over]), where @p From is an
6400/// expression with overloaded function type and @p ToType is the type
6401/// we're trying to resolve to. For example:
6402///
6403/// @code
6404/// int f(double);
6405/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006406///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006407/// int (*pfd)(double) = f; // selects f(double)
6408/// @endcode
6409///
6410/// This routine returns the resulting FunctionDecl if it could be
6411/// resolved, and NULL otherwise. When @p Complain is true, this
6412/// routine will emit diagnostics if there is an error.
6413FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006414Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006415 bool Complain,
6416 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006417 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006418 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006419 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006420 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006421 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006422 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006423 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006424 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006425 FunctionType = MemTypePtr->getPointeeType();
6426 IsMember = true;
6427 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006428
Douglas Gregorcd695e52008-11-10 20:40:00 +00006429 // C++ [over.over]p1:
6430 // [...] [Note: any redundant set of parentheses surrounding the
6431 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006432 // C++ [over.over]p1:
6433 // [...] The overloaded function name can be preceded by the &
6434 // operator.
John McCall7d460512010-08-24 23:26:21 +00006435 // However, remember whether the expression has member-pointer form:
6436 // C++ [expr.unary.op]p4:
6437 // A pointer to member is only formed when an explicit & is used
6438 // and its operand is a qualified-id not enclosed in
6439 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006440 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6441 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006442
Douglas Gregor064fdb22010-04-14 23:11:21 +00006443 // We expect a pointer or reference to function, or a function pointer.
6444 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6445 if (!FunctionType->isFunctionType()) {
6446 if (Complain)
6447 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6448 << OvlExpr->getName() << ToType;
6449
6450 return 0;
6451 }
6452
John McCall24d18942010-08-24 22:52:39 +00006453 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006454 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006455 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006456 if (!Complain) return 0;
6457
6458 // TODO: Should we condition this on whether any functions might
6459 // have matched, or is it more appropriate to do that in callers?
6460 // TODO: a fixit wouldn't hurt.
6461 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6462 << ToType << OvlExpr->getSourceRange();
6463 return 0;
6464 }
6465
6466 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6467 if (OvlExpr->hasExplicitTemplateArgs()) {
6468 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6469 ExplicitTemplateArgs = &ETABuffer;
6470 }
6471
Douglas Gregor064fdb22010-04-14 23:11:21 +00006472 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006473
Douglas Gregorcd695e52008-11-10 20:40:00 +00006474 // Look through all of the overloaded functions, searching for one
6475 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006476 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006477 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006478
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006479 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006480 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6481 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006482 // Look through any using declarations to find the underlying function.
6483 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6484
Douglas Gregorcd695e52008-11-10 20:40:00 +00006485 // C++ [over.over]p3:
6486 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006487 // targets of type "pointer-to-function" or "reference-to-function."
6488 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006489 // type "pointer-to-member-function."
6490 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006491
Mike Stump11289f42009-09-09 15:08:12 +00006492 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006493 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006494 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006495 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006496 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006497 // static when converting to member pointer.
6498 if (Method->isStatic() == IsMember)
6499 continue;
6500 } else if (IsMember)
6501 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006502
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006503 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006504 // If the name is a function template, template argument deduction is
6505 // done (14.8.2.2), and if the argument deduction succeeds, the
6506 // resulting template argument list is used to generate a single
6507 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006508 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006509 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006510 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006511 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006512 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006513 FunctionType, Specialization, Info)) {
6514 // FIXME: make a note of the failed deduction for diagnostics.
6515 (void)Result;
6516 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006517 // Template argument deduction ensures that we have an exact match.
6518 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006519 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006520 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006521 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006522 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006523 }
John McCalld14a8642009-11-21 08:51:07 +00006524
6525 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006526 }
Mike Stump11289f42009-09-09 15:08:12 +00006527
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006528 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006529 // Skip non-static functions when converting to pointer, and static
6530 // when converting to member pointer.
6531 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006532 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006533
6534 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006535 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006536 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006537 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006538 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006539
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006540 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006541 QualType ResultTy;
6542 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6543 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6544 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006545 Matches.push_back(std::make_pair(I.getPair(),
6546 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006547 FoundNonTemplateFunction = true;
6548 }
Mike Stump11289f42009-09-09 15:08:12 +00006549 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006550 }
6551
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006552 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006553 if (Matches.empty()) {
6554 if (Complain) {
6555 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6556 << OvlExpr->getName() << FunctionType;
6557 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6558 E = OvlExpr->decls_end();
6559 I != E; ++I)
6560 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6561 NoteOverloadCandidate(F);
6562 }
6563
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006564 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006565 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006566 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006567 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006568 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006569 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006570 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006571 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006572 return Result;
6573 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006574
6575 // C++ [over.over]p4:
6576 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006577 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006578 // [...] and any given function template specialization F1 is
6579 // eliminated if the set contains a second function template
6580 // specialization whose function template is more specialized
6581 // than the function template of F1 according to the partial
6582 // ordering rules of 14.5.5.2.
6583
6584 // The algorithm specified above is quadratic. We instead use a
6585 // two-pass algorithm (similar to the one used to identify the
6586 // best viable function in an overload set) that identifies the
6587 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006588
6589 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6590 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6591 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006592
6593 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006594 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006595 TPOC_Other, From->getLocStart(),
6596 PDiag(),
6597 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006598 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006599 PDiag(diag::note_ovl_candidate)
6600 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006601 if (Result == MatchesCopy.end())
6602 return 0;
6603
John McCall58cc69d2010-01-27 01:50:18 +00006604 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006605 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006606 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006607 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006608 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Douglas Gregorfae1d712009-09-26 03:56:17 +00006611 // [...] any function template specializations in the set are
6612 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006613 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006614 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006615 ++I;
6616 else {
John McCalla0296f72010-03-19 07:35:19 +00006617 Matches[I] = Matches[--N];
6618 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006619 }
6620 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006621
Mike Stump11289f42009-09-09 15:08:12 +00006622 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006623 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006624 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006625 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006626 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006627 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006628 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6629 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006630 }
Mike Stump11289f42009-09-09 15:08:12 +00006631
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006632 // FIXME: We should probably return the same thing that BestViableFunction
6633 // returns (even if we issue the diagnostics here).
6634 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006635 << Matches[0].second->getDeclName();
6636 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6637 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006638 return 0;
6639}
6640
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006641/// \brief Given an expression that refers to an overloaded function, try to
6642/// resolve that overloaded function expression down to a single function.
6643///
6644/// This routine can only resolve template-ids that refer to a single function
6645/// template, where that template-id refers to a single template whose template
6646/// arguments are either provided by the template-id or have defaults,
6647/// as described in C++0x [temp.arg.explicit]p3.
6648FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6649 // C++ [over.over]p1:
6650 // [...] [Note: any redundant set of parentheses surrounding the
6651 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006652 // C++ [over.over]p1:
6653 // [...] The overloaded function name can be preceded by the &
6654 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006655
6656 if (From->getType() != Context.OverloadTy)
6657 return 0;
6658
John McCall8d08b9b2010-08-27 09:08:28 +00006659 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006660
6661 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006662 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006663 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006664
6665 TemplateArgumentListInfo ExplicitTemplateArgs;
6666 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006667
6668 // Look through all of the overloaded functions, searching for one
6669 // whose type matches exactly.
6670 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006671 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6672 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006673 // C++0x [temp.arg.explicit]p3:
6674 // [...] In contexts where deduction is done and fails, or in contexts
6675 // where deduction is not done, if a template argument list is
6676 // specified and it, along with any default template arguments,
6677 // identifies a single function template specialization, then the
6678 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006679 FunctionTemplateDecl *FunctionTemplate
6680 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006681
6682 // C++ [over.over]p2:
6683 // If the name is a function template, template argument deduction is
6684 // done (14.8.2.2), and if the argument deduction succeeds, the
6685 // resulting template argument list is used to generate a single
6686 // function template specialization, which is added to the set of
6687 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006688 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006689 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006690 if (TemplateDeductionResult Result
6691 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6692 Specialization, Info)) {
6693 // FIXME: make a note of the failed deduction for diagnostics.
6694 (void)Result;
6695 continue;
6696 }
6697
6698 // Multiple matches; we can't resolve to a single declaration.
6699 if (Matched)
6700 return 0;
6701
6702 Matched = Specialization;
6703 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006704
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006705 return Matched;
6706}
6707
Douglas Gregorcabea402009-09-22 15:41:20 +00006708/// \brief Add a single candidate to the overload set.
6709static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006710 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006711 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006712 Expr **Args, unsigned NumArgs,
6713 OverloadCandidateSet &CandidateSet,
6714 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006715 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006716 if (isa<UsingShadowDecl>(Callee))
6717 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6718
Douglas Gregorcabea402009-09-22 15:41:20 +00006719 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006720 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006721 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006722 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006723 return;
John McCalld14a8642009-11-21 08:51:07 +00006724 }
6725
6726 if (FunctionTemplateDecl *FuncTemplate
6727 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006728 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6729 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006730 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006731 return;
6732 }
6733
6734 assert(false && "unhandled case in overloaded call candidate");
6735
6736 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006737}
6738
6739/// \brief Add the overload candidates named by callee and/or found by argument
6740/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006741void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006742 Expr **Args, unsigned NumArgs,
6743 OverloadCandidateSet &CandidateSet,
6744 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006745
6746#ifndef NDEBUG
6747 // Verify that ArgumentDependentLookup is consistent with the rules
6748 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006749 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006750 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6751 // and let Y be the lookup set produced by argument dependent
6752 // lookup (defined as follows). If X contains
6753 //
6754 // -- a declaration of a class member, or
6755 //
6756 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006757 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006758 //
6759 // -- a declaration that is neither a function or a function
6760 // template
6761 //
6762 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006763
John McCall57500772009-12-16 12:17:52 +00006764 if (ULE->requiresADL()) {
6765 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6766 E = ULE->decls_end(); I != E; ++I) {
6767 assert(!(*I)->getDeclContext()->isRecord());
6768 assert(isa<UsingShadowDecl>(*I) ||
6769 !(*I)->getDeclContext()->isFunctionOrMethod());
6770 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006771 }
6772 }
6773#endif
6774
John McCall57500772009-12-16 12:17:52 +00006775 // It would be nice to avoid this copy.
6776 TemplateArgumentListInfo TABuffer;
6777 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6778 if (ULE->hasExplicitTemplateArgs()) {
6779 ULE->copyTemplateArgumentsInto(TABuffer);
6780 ExplicitTemplateArgs = &TABuffer;
6781 }
6782
6783 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6784 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006785 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006786 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006787 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006788
John McCall57500772009-12-16 12:17:52 +00006789 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006790 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6791 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006792 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006793 CandidateSet,
6794 PartialOverloading);
6795}
John McCalld681c392009-12-16 08:11:27 +00006796
6797/// Attempts to recover from a call where no functions were found.
6798///
6799/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006800static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006801BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006802 UnresolvedLookupExpr *ULE,
6803 SourceLocation LParenLoc,
6804 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006805 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006806
6807 CXXScopeSpec SS;
6808 if (ULE->getQualifier()) {
6809 SS.setScopeRep(ULE->getQualifier());
6810 SS.setRange(ULE->getQualifierRange());
6811 }
6812
John McCall57500772009-12-16 12:17:52 +00006813 TemplateArgumentListInfo TABuffer;
6814 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6815 if (ULE->hasExplicitTemplateArgs()) {
6816 ULE->copyTemplateArgumentsInto(TABuffer);
6817 ExplicitTemplateArgs = &TABuffer;
6818 }
6819
John McCalld681c392009-12-16 08:11:27 +00006820 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6821 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006822 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006823 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006824
John McCall57500772009-12-16 12:17:52 +00006825 assert(!R.empty() && "lookup results empty despite recovery");
6826
6827 // Build an implicit member call if appropriate. Just drop the
6828 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006829 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006830 if ((*R.begin())->isCXXClassMember())
6831 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6832 else if (ExplicitTemplateArgs)
6833 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6834 else
6835 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6836
6837 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006838 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006839
6840 // This shouldn't cause an infinite loop because we're giving it
6841 // an expression with non-empty lookup results, which should never
6842 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006843 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006844 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006845}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006846
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006847/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006848/// (which eventually refers to the declaration Func) and the call
6849/// arguments Args/NumArgs, attempt to resolve the function call down
6850/// to a specific function. If overload resolution succeeds, returns
6851/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006852/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006853/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006854ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006855Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006856 SourceLocation LParenLoc,
6857 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006858 SourceLocation RParenLoc) {
6859#ifndef NDEBUG
6860 if (ULE->requiresADL()) {
6861 // To do ADL, we must have found an unqualified name.
6862 assert(!ULE->getQualifier() && "qualified name with ADL");
6863
6864 // We don't perform ADL for implicit declarations of builtins.
6865 // Verify that this was correctly set up.
6866 FunctionDecl *F;
6867 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6868 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6869 F->getBuiltinID() && F->isImplicit())
6870 assert(0 && "performing ADL for builtin");
6871
6872 // We don't perform ADL in C.
6873 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6874 }
6875#endif
6876
John McCallbc077cf2010-02-08 23:07:23 +00006877 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006878
John McCall57500772009-12-16 12:17:52 +00006879 // Add the functions denoted by the callee to the set of candidate
6880 // functions, including those from argument-dependent lookup.
6881 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006882
6883 // If we found nothing, try to recover.
6884 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6885 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006886 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006887 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006888 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006889
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006890 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006891 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006892 case OR_Success: {
6893 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006894 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00006895 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006896 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006897 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6898 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006899
6900 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006901 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006902 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006903 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006904 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006905 break;
6906
6907 case OR_Ambiguous:
6908 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006909 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006910 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006911 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006912
6913 case OR_Deleted:
6914 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6915 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006916 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006917 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006918 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006919 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006920 }
6921
Douglas Gregorb412e172010-07-25 18:17:45 +00006922 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006923 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006924}
6925
John McCall4c4c1df2010-01-26 03:27:55 +00006926static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006927 return Functions.size() > 1 ||
6928 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6929}
6930
Douglas Gregor084d8552009-03-13 23:49:33 +00006931/// \brief Create a unary operation that may resolve to an overloaded
6932/// operator.
6933///
6934/// \param OpLoc The location of the operator itself (e.g., '*').
6935///
6936/// \param OpcIn The UnaryOperator::Opcode that describes this
6937/// operator.
6938///
6939/// \param Functions The set of non-member functions that will be
6940/// considered by overload resolution. The caller needs to build this
6941/// set based on the context using, e.g.,
6942/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6943/// set should not contain any member functions; those will be added
6944/// by CreateOverloadedUnaryOp().
6945///
6946/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00006947ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00006948Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6949 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00006950 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006951 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00006952
6953 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6954 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6955 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006956 // TODO: provide better source location info.
6957 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006958
6959 Expr *Args[2] = { Input, 0 };
6960 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006961
Douglas Gregor084d8552009-03-13 23:49:33 +00006962 // For post-increment and post-decrement, add the implicit '0' as
6963 // the second argument, so that we know this is a post-increment or
6964 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00006965 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006966 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006967 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6968 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00006969 NumArgs = 2;
6970 }
6971
6972 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006973 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00006974 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00006975 Opc,
6976 Context.DependentTy,
6977 OpLoc));
6978
John McCall58cc69d2010-01-27 01:50:18 +00006979 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006980 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006981 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006982 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006983 /*ADL*/ true, IsOverloaded(Fns),
6984 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006985 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6986 &Args[0], NumArgs,
6987 Context.DependentTy,
6988 OpLoc));
6989 }
6990
6991 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006992 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006993
6994 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006995 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006996
6997 // Add operator candidates that are member functions.
6998 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6999
John McCall4c4c1df2010-01-26 03:27:55 +00007000 // Add candidates from ADL.
7001 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007002 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007003 /*ExplicitTemplateArgs*/ 0,
7004 CandidateSet);
7005
Douglas Gregor084d8552009-03-13 23:49:33 +00007006 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007007 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007008
7009 // Perform overload resolution.
7010 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007011 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007012 case OR_Success: {
7013 // We found a built-in operator or an overloaded operator.
7014 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007015
Douglas Gregor084d8552009-03-13 23:49:33 +00007016 if (FnDecl) {
7017 // We matched an overloaded operator. Build a call to that
7018 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007019
Douglas Gregor084d8552009-03-13 23:49:33 +00007020 // Convert the arguments.
7021 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007022 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007023
John McCall16df1e52010-03-30 21:47:33 +00007024 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7025 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007026 return ExprError();
7027 } else {
7028 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007029 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007030 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007031 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007032 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007033 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007034 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007035 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007036 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007037 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007038 }
7039
John McCall4fa0d5f2010-05-06 18:15:07 +00007040 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7041
Douglas Gregor084d8552009-03-13 23:49:33 +00007042 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00007043 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007044
Douglas Gregor084d8552009-03-13 23:49:33 +00007045 // Build the actual expression node.
7046 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7047 SourceLocation());
7048 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00007049
Eli Friedman030eee42009-11-18 03:58:17 +00007050 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007051 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007052 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00007053 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007054
John McCallb268a282010-08-23 23:25:46 +00007055 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007056 FnDecl))
7057 return ExprError();
7058
John McCallb268a282010-08-23 23:25:46 +00007059 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007060 } else {
7061 // We matched a built-in operator. Convert the arguments, then
7062 // break out so that we will build the appropriate built-in
7063 // operator node.
7064 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007065 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007066 return ExprError();
7067
7068 break;
7069 }
7070 }
7071
7072 case OR_No_Viable_Function:
7073 // No viable function; fall through to handling this as a
7074 // built-in operator, which will produce an error message for us.
7075 break;
7076
7077 case OR_Ambiguous:
7078 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7079 << UnaryOperator::getOpcodeStr(Opc)
7080 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007081 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7082 Args, NumArgs,
7083 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007084 return ExprError();
7085
7086 case OR_Deleted:
7087 Diag(OpLoc, diag::err_ovl_deleted_oper)
7088 << Best->Function->isDeleted()
7089 << UnaryOperator::getOpcodeStr(Opc)
7090 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007091 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007092 return ExprError();
7093 }
7094
7095 // Either we found no viable overloaded operator or we matched a
7096 // built-in operator. In either case, fall through to trying to
7097 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007098 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007099}
7100
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007101/// \brief Create a binary operation that may resolve to an overloaded
7102/// operator.
7103///
7104/// \param OpLoc The location of the operator itself (e.g., '+').
7105///
7106/// \param OpcIn The BinaryOperator::Opcode that describes this
7107/// operator.
7108///
7109/// \param Functions The set of non-member functions that will be
7110/// considered by overload resolution. The caller needs to build this
7111/// set based on the context using, e.g.,
7112/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7113/// set should not contain any member functions; those will be added
7114/// by CreateOverloadedBinOp().
7115///
7116/// \param LHS Left-hand argument.
7117/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007118ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007119Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007120 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007121 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007122 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007123 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007124 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007125
7126 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7127 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7128 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7129
7130 // If either side is type-dependent, create an appropriate dependent
7131 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007132 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007133 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007134 // If there are no functions to store, just build a dependent
7135 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007136 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007137 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7138 Context.DependentTy, OpLoc));
7139
7140 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7141 Context.DependentTy,
7142 Context.DependentTy,
7143 Context.DependentTy,
7144 OpLoc));
7145 }
John McCall4c4c1df2010-01-26 03:27:55 +00007146
7147 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007148 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007149 // TODO: provide better source location info in DNLoc component.
7150 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007151 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007152 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007153 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007154 /*ADL*/ true, IsOverloaded(Fns),
7155 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007156 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007157 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007158 Context.DependentTy,
7159 OpLoc));
7160 }
7161
7162 // If this is the .* operator, which is not overloadable, just
7163 // create a built-in binary operator.
John McCalle3027922010-08-25 11:45:40 +00007164 if (Opc == BO_PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00007165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007166
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007167 // If this is the assignment operator, we only perform overload resolution
7168 // if the left-hand side is a class or enumeration type. This is actually
7169 // a hack. The standard requires that we do overload resolution between the
7170 // various built-in candidates, but as DR507 points out, this can lead to
7171 // problems. So we do it this way, which pretty much follows what GCC does.
7172 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007173 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007174 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007175
Douglas Gregor084d8552009-03-13 23:49:33 +00007176 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007177 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007178
7179 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007180 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007181
7182 // Add operator candidates that are member functions.
7183 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7184
John McCall4c4c1df2010-01-26 03:27:55 +00007185 // Add candidates from ADL.
7186 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7187 Args, 2,
7188 /*ExplicitTemplateArgs*/ 0,
7189 CandidateSet);
7190
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007191 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007192 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007193
7194 // Perform overload resolution.
7195 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007196 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007197 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007198 // We found a built-in operator or an overloaded operator.
7199 FunctionDecl *FnDecl = Best->Function;
7200
7201 if (FnDecl) {
7202 // We matched an overloaded operator. Build a call to that
7203 // operator.
7204
7205 // Convert the arguments.
7206 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007207 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007208 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007209
John McCalldadc5752010-08-24 06:29:42 +00007210 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007211 = PerformCopyInitialization(
7212 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007213 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007214 FnDecl->getParamDecl(0)),
7215 SourceLocation(),
7216 Owned(Args[1]));
7217 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007218 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007219
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007220 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007221 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007222 return ExprError();
7223
7224 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007225 } else {
7226 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007227 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007228 = PerformCopyInitialization(
7229 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007230 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007231 FnDecl->getParamDecl(0)),
7232 SourceLocation(),
7233 Owned(Args[0]));
7234 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007235 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007236
John McCalldadc5752010-08-24 06:29:42 +00007237 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007238 = PerformCopyInitialization(
7239 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007240 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007241 FnDecl->getParamDecl(1)),
7242 SourceLocation(),
7243 Owned(Args[1]));
7244 if (Arg1.isInvalid())
7245 return ExprError();
7246 Args[0] = LHS = Arg0.takeAs<Expr>();
7247 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007248 }
7249
John McCall4fa0d5f2010-05-06 18:15:07 +00007250 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7251
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007252 // Determine the result type
7253 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007254 = FnDecl->getType()->getAs<FunctionType>()
7255 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007256
7257 // Build the actual expression node.
7258 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00007259 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007260 UsualUnaryConversions(FnExpr);
7261
John McCallb268a282010-08-23 23:25:46 +00007262 CXXOperatorCallExpr *TheCall =
7263 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7264 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007265
John McCallb268a282010-08-23 23:25:46 +00007266 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007267 FnDecl))
7268 return ExprError();
7269
John McCallb268a282010-08-23 23:25:46 +00007270 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007271 } else {
7272 // We matched a built-in operator. Convert the arguments, then
7273 // break out so that we will build the appropriate built-in
7274 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007275 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007276 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007277 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007278 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007279 return ExprError();
7280
7281 break;
7282 }
7283 }
7284
Douglas Gregor66950a32009-09-30 21:46:01 +00007285 case OR_No_Viable_Function: {
7286 // C++ [over.match.oper]p9:
7287 // If the operator is the operator , [...] and there are no
7288 // viable functions, then the operator is assumed to be the
7289 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007290 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007291 break;
7292
Sebastian Redl027de2a2009-05-21 11:50:50 +00007293 // For class as left operand for assignment or compound assigment operator
7294 // do not fall through to handling in built-in, but report that no overloaded
7295 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007296 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007297 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007298 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007299 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7300 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007301 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007302 } else {
7303 // No viable function; try to create a built-in operation, which will
7304 // produce an error. Then, show the non-viable candidates.
7305 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007306 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007307 assert(Result.isInvalid() &&
7308 "C++ binary operator overloading is missing candidates!");
7309 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007310 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7311 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007312 return move(Result);
7313 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007314
7315 case OR_Ambiguous:
7316 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7317 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007318 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007319 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7320 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007321 return ExprError();
7322
7323 case OR_Deleted:
7324 Diag(OpLoc, diag::err_ovl_deleted_oper)
7325 << Best->Function->isDeleted()
7326 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007327 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007328 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007329 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007330 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007331
Douglas Gregor66950a32009-09-30 21:46:01 +00007332 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007333 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007334}
7335
John McCalldadc5752010-08-24 06:29:42 +00007336ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007337Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7338 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007339 Expr *Base, Expr *Idx) {
7340 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007341 DeclarationName OpName =
7342 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7343
7344 // If either side is type-dependent, create an appropriate dependent
7345 // expression.
7346 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7347
John McCall58cc69d2010-01-27 01:50:18 +00007348 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007349 // CHECKME: no 'operator' keyword?
7350 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7351 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007352 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007353 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007354 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007355 /*ADL*/ true, /*Overloaded*/ false,
7356 UnresolvedSetIterator(),
7357 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007358 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007359
Sebastian Redladba46e2009-10-29 20:17:01 +00007360 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7361 Args, 2,
7362 Context.DependentTy,
7363 RLoc));
7364 }
7365
7366 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007367 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007368
7369 // Subscript can only be overloaded as a member function.
7370
7371 // Add operator candidates that are member functions.
7372 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7373
7374 // Add builtin operator candidates.
7375 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7376
7377 // Perform overload resolution.
7378 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007379 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007380 case OR_Success: {
7381 // We found a built-in operator or an overloaded operator.
7382 FunctionDecl *FnDecl = Best->Function;
7383
7384 if (FnDecl) {
7385 // We matched an overloaded operator. Build a call to that
7386 // operator.
7387
John McCalla0296f72010-03-19 07:35:19 +00007388 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007389 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007390
Sebastian Redladba46e2009-10-29 20:17:01 +00007391 // Convert the arguments.
7392 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007393 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007394 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007395 return ExprError();
7396
Anders Carlssona68e51e2010-01-29 18:37:50 +00007397 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007398 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007399 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007400 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007401 FnDecl->getParamDecl(0)),
7402 SourceLocation(),
7403 Owned(Args[1]));
7404 if (InputInit.isInvalid())
7405 return ExprError();
7406
7407 Args[1] = InputInit.takeAs<Expr>();
7408
Sebastian Redladba46e2009-10-29 20:17:01 +00007409 // Determine the result type
7410 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007411 = FnDecl->getType()->getAs<FunctionType>()
7412 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007413
7414 // Build the actual expression node.
7415 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7416 LLoc);
7417 UsualUnaryConversions(FnExpr);
7418
John McCallb268a282010-08-23 23:25:46 +00007419 CXXOperatorCallExpr *TheCall =
7420 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7421 FnExpr, Args, 2,
7422 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007423
John McCallb268a282010-08-23 23:25:46 +00007424 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007425 FnDecl))
7426 return ExprError();
7427
John McCallb268a282010-08-23 23:25:46 +00007428 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007429 } else {
7430 // We matched a built-in operator. Convert the arguments, then
7431 // break out so that we will build the appropriate built-in
7432 // operator node.
7433 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007434 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007435 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007436 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007437 return ExprError();
7438
7439 break;
7440 }
7441 }
7442
7443 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007444 if (CandidateSet.empty())
7445 Diag(LLoc, diag::err_ovl_no_oper)
7446 << Args[0]->getType() << /*subscript*/ 0
7447 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7448 else
7449 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7450 << Args[0]->getType()
7451 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007452 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7453 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007454 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007455 }
7456
7457 case OR_Ambiguous:
7458 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7459 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007460 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7461 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007462 return ExprError();
7463
7464 case OR_Deleted:
7465 Diag(LLoc, diag::err_ovl_deleted_oper)
7466 << Best->Function->isDeleted() << "[]"
7467 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007468 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7469 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007470 return ExprError();
7471 }
7472
7473 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007474 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007475}
7476
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007477/// BuildCallToMemberFunction - Build a call to a member
7478/// function. MemExpr is the expression that refers to the member
7479/// function (and includes the object parameter), Args/NumArgs are the
7480/// arguments to the function call (not including the object
7481/// parameter). The caller needs to validate that the member
7482/// expression refers to a member function or an overloaded member
7483/// function.
John McCalldadc5752010-08-24 06:29:42 +00007484ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007485Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7486 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007487 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007488 // Dig out the member expression. This holds both the object
7489 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007490 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7491
John McCall10eae182009-11-30 22:42:35 +00007492 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007493 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007494 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007495 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007496 if (isa<MemberExpr>(NakedMemExpr)) {
7497 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007498 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007499 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007500 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007501 } else {
7502 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007503 Qualifier = UnresExpr->getQualifier();
7504
John McCall6e9f8f62009-12-03 04:06:58 +00007505 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007506
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007507 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007508 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007509
John McCall2d74de92009-12-01 22:10:20 +00007510 // FIXME: avoid copy.
7511 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7512 if (UnresExpr->hasExplicitTemplateArgs()) {
7513 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7514 TemplateArgs = &TemplateArgsBuffer;
7515 }
7516
John McCall10eae182009-11-30 22:42:35 +00007517 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7518 E = UnresExpr->decls_end(); I != E; ++I) {
7519
John McCall6e9f8f62009-12-03 04:06:58 +00007520 NamedDecl *Func = *I;
7521 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7522 if (isa<UsingShadowDecl>(Func))
7523 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7524
John McCall10eae182009-11-30 22:42:35 +00007525 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007526 // If explicit template arguments were provided, we can't call a
7527 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007528 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007529 continue;
7530
John McCalla0296f72010-03-19 07:35:19 +00007531 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007532 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007533 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007534 } else {
John McCall10eae182009-11-30 22:42:35 +00007535 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007536 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007537 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007538 CandidateSet,
7539 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007540 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007541 }
Mike Stump11289f42009-09-09 15:08:12 +00007542
John McCall10eae182009-11-30 22:42:35 +00007543 DeclarationName DeclName = UnresExpr->getMemberName();
7544
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007545 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007546 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7547 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007548 case OR_Success:
7549 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007550 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007551 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007552 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007553 break;
7554
7555 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007556 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007557 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007558 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007559 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007560 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007561 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007562
7563 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007564 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007565 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007566 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007567 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007568 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007569
7570 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007571 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007572 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007573 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007574 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007575 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007576 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007577 }
7578
John McCall16df1e52010-03-30 21:47:33 +00007579 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007580
John McCall2d74de92009-12-01 22:10:20 +00007581 // If overload resolution picked a static member, build a
7582 // non-member call based on that function.
7583 if (Method->isStatic()) {
7584 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7585 Args, NumArgs, RParenLoc);
7586 }
7587
John McCall10eae182009-11-30 22:42:35 +00007588 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007589 }
7590
7591 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007592 CXXMemberCallExpr *TheCall =
7593 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7594 Method->getCallResultType(),
7595 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007596
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007597 // Check for a valid return type.
7598 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007599 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007600 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007601
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007602 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007603 // We only need to do this if there was actually an overload; otherwise
7604 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007605 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007606 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007607 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7608 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007609 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007610 MemExpr->setBase(ObjectArg);
7611
7612 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007613 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007614 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007615 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007616 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007617
John McCallb268a282010-08-23 23:25:46 +00007618 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007619 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007620
John McCallb268a282010-08-23 23:25:46 +00007621 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007622}
7623
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007624/// BuildCallToObjectOfClassType - Build a call to an object of class
7625/// type (C++ [over.call.object]), which can end up invoking an
7626/// overloaded function call operator (@c operator()) or performing a
7627/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007628ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007629Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007630 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007631 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007632 SourceLocation RParenLoc) {
7633 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007634 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007635
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007636 // C++ [over.call.object]p1:
7637 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007638 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007639 // candidate functions includes at least the function call
7640 // operators of T. The function call operators of T are obtained by
7641 // ordinary lookup of the name operator() in the context of
7642 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007643 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007644 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007645
7646 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007647 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007648 << Object->getSourceRange()))
7649 return true;
7650
John McCall27b18f82009-11-17 02:14:36 +00007651 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7652 LookupQualifiedName(R, Record->getDecl());
7653 R.suppressDiagnostics();
7654
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007655 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007656 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007657 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007658 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007659 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007660 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007661
Douglas Gregorab7897a2008-11-19 22:57:39 +00007662 // C++ [over.call.object]p2:
7663 // In addition, for each conversion function declared in T of the
7664 // form
7665 //
7666 // operator conversion-type-id () cv-qualifier;
7667 //
7668 // where cv-qualifier is the same cv-qualification as, or a
7669 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007670 // denotes the type "pointer to function of (P1,...,Pn) returning
7671 // R", or the type "reference to pointer to function of
7672 // (P1,...,Pn) returning R", or the type "reference to function
7673 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007674 // is also considered as a candidate function. Similarly,
7675 // surrogate call functions are added to the set of candidate
7676 // functions for each conversion function declared in an
7677 // accessible base class provided the function is not hidden
7678 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007679 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007680 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007681 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007682 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007683 NamedDecl *D = *I;
7684 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7685 if (isa<UsingShadowDecl>(D))
7686 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7687
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007688 // Skip over templated conversion functions; they aren't
7689 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007690 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007691 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007692
John McCall6e9f8f62009-12-03 04:06:58 +00007693 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007694
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007695 // Strip the reference type (if any) and then the pointer type (if
7696 // any) to get down to what might be a function type.
7697 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7698 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7699 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007700
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007701 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007702 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007703 Object->getType(), Args, NumArgs,
7704 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007705 }
Mike Stump11289f42009-09-09 15:08:12 +00007706
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007707 // Perform overload resolution.
7708 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007709 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7710 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007711 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007712 // Overload resolution succeeded; we'll build the appropriate call
7713 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007714 break;
7715
7716 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007717 if (CandidateSet.empty())
7718 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7719 << Object->getType() << /*call*/ 1
7720 << Object->getSourceRange();
7721 else
7722 Diag(Object->getSourceRange().getBegin(),
7723 diag::err_ovl_no_viable_object_call)
7724 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007725 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007726 break;
7727
7728 case OR_Ambiguous:
7729 Diag(Object->getSourceRange().getBegin(),
7730 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007731 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007732 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007733 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007734
7735 case OR_Deleted:
7736 Diag(Object->getSourceRange().getBegin(),
7737 diag::err_ovl_deleted_object_call)
7738 << Best->Function->isDeleted()
7739 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007740 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007741 break;
Mike Stump11289f42009-09-09 15:08:12 +00007742 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007743
Douglas Gregorb412e172010-07-25 18:17:45 +00007744 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007745 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007746
Douglas Gregorab7897a2008-11-19 22:57:39 +00007747 if (Best->Function == 0) {
7748 // Since there is no function declaration, this is one of the
7749 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007750 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007751 = cast<CXXConversionDecl>(
7752 Best->Conversions[0].UserDefined.ConversionFunction);
7753
John McCalla0296f72010-03-19 07:35:19 +00007754 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007755 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007756
Douglas Gregorab7897a2008-11-19 22:57:39 +00007757 // We selected one of the surrogate functions that converts the
7758 // object parameter to a function pointer. Perform the conversion
7759 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007760
7761 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007762 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007763 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7764 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007765
John McCallfaf5fb42010-08-26 23:41:50 +00007766 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007767 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007768 }
7769
John McCalla0296f72010-03-19 07:35:19 +00007770 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007771 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007772
Douglas Gregorab7897a2008-11-19 22:57:39 +00007773 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7774 // that calls this method, using Object for the implicit object
7775 // parameter and passing along the remaining arguments.
7776 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007777 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007778
7779 unsigned NumArgsInProto = Proto->getNumArgs();
7780 unsigned NumArgsToCheck = NumArgs;
7781
7782 // Build the full argument list for the method call (the
7783 // implicit object parameter is placed at the beginning of the
7784 // list).
7785 Expr **MethodArgs;
7786 if (NumArgs < NumArgsInProto) {
7787 NumArgsToCheck = NumArgsInProto;
7788 MethodArgs = new Expr*[NumArgsInProto + 1];
7789 } else {
7790 MethodArgs = new Expr*[NumArgs + 1];
7791 }
7792 MethodArgs[0] = Object;
7793 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7794 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007795
7796 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007797 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007798 UsualUnaryConversions(NewFn);
7799
7800 // Once we've built TheCall, all of the expressions are properly
7801 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007802 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007803 CXXOperatorCallExpr *TheCall =
7804 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7805 MethodArgs, NumArgs + 1,
7806 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007807 delete [] MethodArgs;
7808
John McCallb268a282010-08-23 23:25:46 +00007809 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007810 Method))
7811 return true;
7812
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007813 // We may have default arguments. If so, we need to allocate more
7814 // slots in the call for them.
7815 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007816 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007817 else if (NumArgs > NumArgsInProto)
7818 NumArgsToCheck = NumArgsInProto;
7819
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007820 bool IsError = false;
7821
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007822 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007823 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007824 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007825 TheCall->setArg(0, Object);
7826
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007827
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007828 // Check the argument types.
7829 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007830 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007831 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007832 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007833
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007834 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007835
John McCalldadc5752010-08-24 06:29:42 +00007836 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007837 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007838 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007839 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007840 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007841
7842 IsError |= InputInit.isInvalid();
7843 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007844 } else {
John McCalldadc5752010-08-24 06:29:42 +00007845 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007846 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7847 if (DefArg.isInvalid()) {
7848 IsError = true;
7849 break;
7850 }
7851
7852 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007853 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007854
7855 TheCall->setArg(i + 1, Arg);
7856 }
7857
7858 // If this is a variadic call, handle args passed through "...".
7859 if (Proto->isVariadic()) {
7860 // Promote the arguments (C99 6.5.2.2p7).
7861 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7862 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007863 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007864 TheCall->setArg(i + 1, Arg);
7865 }
7866 }
7867
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007868 if (IsError) return true;
7869
John McCallb268a282010-08-23 23:25:46 +00007870 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007871 return true;
7872
John McCalle172be52010-08-24 06:09:16 +00007873 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007874}
7875
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007876/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007877/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007878/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007879ExprResult
John McCallb268a282010-08-23 23:25:46 +00007880Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007881 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007882
John McCallbc077cf2010-02-08 23:07:23 +00007883 SourceLocation Loc = Base->getExprLoc();
7884
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007885 // C++ [over.ref]p1:
7886 //
7887 // [...] An expression x->m is interpreted as (x.operator->())->m
7888 // for a class object x of type T if T::operator->() exists and if
7889 // the operator is selected as the best match function by the
7890 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007891 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007892 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007893 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007894
John McCallbc077cf2010-02-08 23:07:23 +00007895 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007896 PDiag(diag::err_typecheck_incomplete_tag)
7897 << Base->getSourceRange()))
7898 return ExprError();
7899
John McCall27b18f82009-11-17 02:14:36 +00007900 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7901 LookupQualifiedName(R, BaseRecord->getDecl());
7902 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007903
7904 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007905 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007906 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007907 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007908 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007909
7910 // Perform overload resolution.
7911 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007912 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007913 case OR_Success:
7914 // Overload resolution succeeded; we'll build the call below.
7915 break;
7916
7917 case OR_No_Viable_Function:
7918 if (CandidateSet.empty())
7919 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007920 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007921 else
7922 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007923 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007924 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007925 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007926
7927 case OR_Ambiguous:
7928 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007929 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007930 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007931 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007932
7933 case OR_Deleted:
7934 Diag(OpLoc, diag::err_ovl_deleted_oper)
7935 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007936 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007937 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007938 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007939 }
7940
John McCalla0296f72010-03-19 07:35:19 +00007941 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007942 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007943
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007944 // Convert the object parameter.
7945 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007946 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7947 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007948 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007949
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007950 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007951 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7952 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007953 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007954
Douglas Gregor603d81b2010-07-13 08:18:22 +00007955 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007956 CXXOperatorCallExpr *TheCall =
7957 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7958 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007959
John McCallb268a282010-08-23 23:25:46 +00007960 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007961 Method))
7962 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007963 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007964}
7965
Douglas Gregorcd695e52008-11-10 20:40:00 +00007966/// FixOverloadedFunctionReference - E is an expression that refers to
7967/// a C++ overloaded function (possibly with some parentheses and
7968/// perhaps a '&' around it). We have resolved the overloaded function
7969/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007970/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007971Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007972 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007973 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007974 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7975 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007976 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00007977 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00007978
7979 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7980 }
7981
7982 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007983 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7984 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007985 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007986 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007987 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007988 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007989 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00007990 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00007991
John McCallcf142162010-08-07 06:22:56 +00007992 return ImplicitCastExpr::Create(Context, ICE->getType(),
7993 ICE->getCastKind(),
7994 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00007995 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007996 }
7997
7998 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00007999 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008000 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008001 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8002 if (Method->isStatic()) {
8003 // Do nothing: static member functions aren't any different
8004 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008005 } else {
John McCalle66edc12009-11-24 19:00:30 +00008006 // Fix the sub expression, which really has to be an
8007 // UnresolvedLookupExpr holding an overloaded member function
8008 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008009 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8010 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008011 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008012 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008013
John McCalld14a8642009-11-21 08:51:07 +00008014 assert(isa<DeclRefExpr>(SubExpr)
8015 && "fixed to something other than a decl ref");
8016 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8017 && "fixed to a member ref with no nested name qualifier");
8018
8019 // We have taken the address of a pointer to member
8020 // function. Perform the computation here so that we get the
8021 // appropriate pointer to member type.
8022 QualType ClassType
8023 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8024 QualType MemPtrType
8025 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8026
John McCalle3027922010-08-25 11:45:40 +00008027 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCalld14a8642009-11-21 08:51:07 +00008028 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008029 }
8030 }
John McCall16df1e52010-03-30 21:47:33 +00008031 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8032 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008033 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008034 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008035
John McCalle3027922010-08-25 11:45:40 +00008036 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008037 Context.getPointerType(SubExpr->getType()),
8038 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008039 }
John McCalld14a8642009-11-21 08:51:07 +00008040
8041 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008042 // FIXME: avoid copy.
8043 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008044 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008045 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8046 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008047 }
8048
John McCalld14a8642009-11-21 08:51:07 +00008049 return DeclRefExpr::Create(Context,
8050 ULE->getQualifier(),
8051 ULE->getQualifierRange(),
8052 Fn,
8053 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008054 Fn->getType(),
8055 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008056 }
8057
John McCall10eae182009-11-30 22:42:35 +00008058 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008059 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008060 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8061 if (MemExpr->hasExplicitTemplateArgs()) {
8062 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8063 TemplateArgs = &TemplateArgsBuffer;
8064 }
John McCall6b51f282009-11-23 01:53:49 +00008065
John McCall2d74de92009-12-01 22:10:20 +00008066 Expr *Base;
8067
8068 // If we're filling in
8069 if (MemExpr->isImplicitAccess()) {
8070 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8071 return DeclRefExpr::Create(Context,
8072 MemExpr->getQualifier(),
8073 MemExpr->getQualifierRange(),
8074 Fn,
8075 MemExpr->getMemberLoc(),
8076 Fn->getType(),
8077 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008078 } else {
8079 SourceLocation Loc = MemExpr->getMemberLoc();
8080 if (MemExpr->getQualifier())
8081 Loc = MemExpr->getQualifierRange().getBegin();
8082 Base = new (Context) CXXThisExpr(Loc,
8083 MemExpr->getBaseType(),
8084 /*isImplicit=*/true);
8085 }
John McCall2d74de92009-12-01 22:10:20 +00008086 } else
John McCallc3007a22010-10-26 07:05:15 +00008087 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008088
8089 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008090 MemExpr->isArrow(),
8091 MemExpr->getQualifier(),
8092 MemExpr->getQualifierRange(),
8093 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008094 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008095 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008096 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008097 Fn->getType());
8098 }
8099
John McCallc3007a22010-10-26 07:05:15 +00008100 llvm_unreachable("Invalid reference to overloaded function");
8101 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008102}
8103
John McCalldadc5752010-08-24 06:29:42 +00008104ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8105 DeclAccessPair Found,
8106 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008107 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008108}
8109
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008110} // end namespace clang