blob: 078669a556a743ad95c710153a202eaa7934df3d [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
Douglas Gregor1aa450a2009-12-13 21:37:05 +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
1190 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1191 // can be converted to an rvalue of the first of the following types
1192 // that can represent all the values of its underlying type: int,
1193 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001194
1195 // We pre-calculate the promotion type for enum types.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001196 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1197 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1198 // provided for a scoped enumeration.
1199 if (FromEnumType->getDecl()->isScoped())
1200 return false;
1201
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001202 if (ToType->isIntegerType() &&
1203 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001204 return Context.hasSameUnqualifiedType(ToType,
1205 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001206 }
John McCall56774992009-12-09 09:09:27 +00001207
1208 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209 // Determine whether the type we're converting from is signed or
1210 // unsigned.
1211 bool FromIsSigned;
1212 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001213
1214 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1215 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001216
1217 // The types we'll try to promote to, in the appropriate
1218 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001219 QualType PromoteTypes[6] = {
1220 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001221 Context.LongTy, Context.UnsignedLongTy ,
1222 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001223 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001224 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001225 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1226 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001227 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1229 // We found the type that we can promote to. If this is the
1230 // type we wanted, we have a promotion. Otherwise, no
1231 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001232 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233 }
1234 }
1235 }
1236
1237 // An rvalue for an integral bit-field (9.6) can be converted to an
1238 // rvalue of type int if int can represent all the values of the
1239 // bit-field; otherwise, it can be converted to unsigned int if
1240 // unsigned int can represent all the values of the bit-field. If
1241 // the bit-field is larger yet, no integral promotion applies to
1242 // it. If the bit-field has an enumerated type, it is treated as any
1243 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001244 // FIXME: We should delay checking of bit-fields until we actually perform the
1245 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001246 using llvm::APSInt;
1247 if (From)
1248 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001249 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001250 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001251 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1252 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1253 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001255 // Are we promoting to an int from a bitfield that fits in an int?
1256 if (BitWidth < ToSize ||
1257 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1258 return To->getKind() == BuiltinType::Int;
1259 }
Mike Stump11289f42009-09-09 15:08:12 +00001260
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001261 // Are we promoting to an unsigned int from an unsigned bitfield
1262 // that fits into an unsigned int?
1263 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1264 return To->getKind() == BuiltinType::UInt;
1265 }
Mike Stump11289f42009-09-09 15:08:12 +00001266
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001267 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001268 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269 }
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001271 // An rvalue of type bool can be converted to an rvalue of type int,
1272 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001273 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001275 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001276
1277 return false;
1278}
1279
1280/// IsFloatingPointPromotion - Determines whether the conversion from
1281/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1282/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001283bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001284 /// An rvalue of type float can be converted to an rvalue of type
1285 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001286 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1287 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 if (FromBuiltin->getKind() == BuiltinType::Float &&
1289 ToBuiltin->getKind() == BuiltinType::Double)
1290 return true;
1291
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001292 // C99 6.3.1.5p1:
1293 // When a float is promoted to double or long double, or a
1294 // double is promoted to long double [...].
1295 if (!getLangOptions().CPlusPlus &&
1296 (FromBuiltin->getKind() == BuiltinType::Float ||
1297 FromBuiltin->getKind() == BuiltinType::Double) &&
1298 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1299 return true;
1300 }
1301
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 return false;
1303}
1304
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001305/// \brief Determine if a conversion is a complex promotion.
1306///
1307/// A complex promotion is defined as a complex -> complex conversion
1308/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001309/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001310bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001311 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001312 if (!FromComplex)
1313 return false;
1314
John McCall9dd450b2009-09-21 23:43:11 +00001315 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001316 if (!ToComplex)
1317 return false;
1318
1319 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001320 ToComplex->getElementType()) ||
1321 IsIntegralPromotion(0, FromComplex->getElementType(),
1322 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001323}
1324
Douglas Gregor237f96c2008-11-26 23:31:11 +00001325/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1326/// the pointer type FromPtr to a pointer to type ToPointee, with the
1327/// same type qualifiers as FromPtr has on its pointee type. ToType,
1328/// if non-empty, will be a pointer to ToType that may or may not have
1329/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001330static QualType
1331BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001332 QualType ToPointee, QualType ToType,
1333 ASTContext &Context) {
1334 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1335 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001336 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001337
1338 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001339 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001340 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001341 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001342 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001343
1344 // Build a pointer to ToPointee. It has the right qualifiers
1345 // already.
1346 return Context.getPointerType(ToPointee);
1347 }
1348
1349 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001350 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001351 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1352 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001353}
1354
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001355/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1356/// the FromType, which is an objective-c pointer, to ToType, which may or may
1357/// not have the right set of qualifiers.
1358static QualType
1359BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1360 QualType ToType,
1361 ASTContext &Context) {
1362 QualType CanonFromType = Context.getCanonicalType(FromType);
1363 QualType CanonToType = Context.getCanonicalType(ToType);
1364 Qualifiers Quals = CanonFromType.getQualifiers();
1365
1366 // Exact qualifier match -> return the pointer type we're converting to.
1367 if (CanonToType.getLocalQualifiers() == Quals)
1368 return ToType;
1369
1370 // Just build a canonical type that has the right qualifiers.
1371 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1372}
1373
Mike Stump11289f42009-09-09 15:08:12 +00001374static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001375 bool InOverloadResolution,
1376 ASTContext &Context) {
1377 // Handle value-dependent integral null pointer constants correctly.
1378 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1379 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001380 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001381 return !InOverloadResolution;
1382
Douglas Gregor56751b52009-09-25 04:25:58 +00001383 return Expr->isNullPointerConstant(Context,
1384 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1385 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001386}
Mike Stump11289f42009-09-09 15:08:12 +00001387
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001388/// IsPointerConversion - Determines whether the conversion of the
1389/// expression From, which has the (possibly adjusted) type FromType,
1390/// can be converted to the type ToType via a pointer conversion (C++
1391/// 4.10). If so, returns true and places the converted type (that
1392/// might differ from ToType in its cv-qualifiers at some level) into
1393/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001394///
Douglas Gregora29dc052008-11-27 01:19:21 +00001395/// This routine also supports conversions to and from block pointers
1396/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1397/// pointers to interfaces. FIXME: Once we've determined the
1398/// appropriate overloading rules for Objective-C, we may want to
1399/// split the Objective-C checks into a different routine; however,
1400/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001401/// conversions, so for now they live here. IncompatibleObjC will be
1402/// set if the conversion is an allowed Objective-C conversion that
1403/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001405 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001406 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001407 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001408 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001409 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1410 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001411
Mike Stump11289f42009-09-09 15:08:12 +00001412 // Conversion from a null pointer constant to any Objective-C pointer type.
1413 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001414 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001415 ConvertedType = ToType;
1416 return true;
1417 }
1418
Douglas Gregor231d1c62008-11-27 00:15:41 +00001419 // Blocks: Block pointers can be converted to void*.
1420 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001421 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001422 ConvertedType = ToType;
1423 return true;
1424 }
1425 // Blocks: A null pointer constant can be converted to a block
1426 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001427 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001428 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001429 ConvertedType = ToType;
1430 return true;
1431 }
1432
Sebastian Redl576fd422009-05-10 18:38:11 +00001433 // If the left-hand-side is nullptr_t, the right side can be a null
1434 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001435 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001436 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001437 ConvertedType = ToType;
1438 return true;
1439 }
1440
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001441 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 if (!ToTypePtr)
1443 return false;
1444
1445 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001446 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001447 ConvertedType = ToType;
1448 return true;
1449 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001450
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001451 // Beyond this point, both types need to be pointers
1452 // , including objective-c pointers.
1453 QualType ToPointeeType = ToTypePtr->getPointeeType();
1454 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1455 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1456 ToType, Context);
1457 return true;
1458
1459 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001460 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001461 if (!FromTypePtr)
1462 return false;
1463
1464 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001465
Douglas Gregorfb640862010-08-18 21:25:30 +00001466 // If the unqualified pointee types are the same, this can't be a
1467 // pointer conversion, so don't do all of the work below.
1468 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1469 return false;
1470
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471 // An rvalue of type "pointer to cv T," where T is an object type,
1472 // can be converted to an rvalue of type "pointer to cv void" (C++
1473 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001474 if (FromPointeeType->isIncompleteOrObjectType() &&
1475 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001477 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001478 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001479 return true;
1480 }
1481
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001482 // When we're overloading in C, we allow a special kind of pointer
1483 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001484 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001485 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001486 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001487 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001488 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001489 return true;
1490 }
1491
Douglas Gregor5c407d92008-10-23 00:40:37 +00001492 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001493 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001494 // An rvalue of type "pointer to cv D," where D is a class type,
1495 // can be converted to an rvalue of type "pointer to cv B," where
1496 // B is a base class (clause 10) of D. If B is an inaccessible
1497 // (clause 11) or ambiguous (10.2) base class of D, a program that
1498 // necessitates this conversion is ill-formed. The result of the
1499 // conversion is a pointer to the base class sub-object of the
1500 // derived class object. The null pointer value is converted to
1501 // the null pointer value of the destination type.
1502 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001503 // Note that we do not check for ambiguity or inaccessibility
1504 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001505 if (getLangOptions().CPlusPlus &&
1506 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001507 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001508 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001509 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001510 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001511 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001512 ToType, Context);
1513 return true;
1514 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001515
Douglas Gregora119f102008-12-19 19:13:09 +00001516 return false;
1517}
1518
1519/// isObjCPointerConversion - Determines whether this is an
1520/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1521/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001522bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001523 QualType& ConvertedType,
1524 bool &IncompatibleObjC) {
1525 if (!getLangOptions().ObjC1)
1526 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001527
Steve Naroff7cae42b2009-07-10 23:34:53 +00001528 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001529 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001530 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001531 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001532
Steve Naroff7cae42b2009-07-10 23:34:53 +00001533 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001534 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001535 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001536 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001537 ConvertedType = ToType;
1538 return true;
1539 }
1540 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001541 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001542 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001543 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001544 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001545 ConvertedType = ToType;
1546 return true;
1547 }
1548 // Objective C++: We're able to convert from a pointer to an
1549 // interface to a pointer to a different interface.
1550 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001551 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1552 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1553 if (getLangOptions().CPlusPlus && LHS && RHS &&
1554 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1555 FromObjCPtr->getPointeeType()))
1556 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001557 ConvertedType = ToType;
1558 return true;
1559 }
1560
1561 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1562 // Okay: this is some kind of implicit downcast of Objective-C
1563 // interfaces, which is permitted. However, we're going to
1564 // complain about it.
1565 IncompatibleObjC = true;
1566 ConvertedType = FromType;
1567 return true;
1568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001570 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001571 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001572 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001573 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001574 else if (const BlockPointerType *ToBlockPtr =
1575 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001576 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001577 // to a block pointer type.
1578 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1579 ConvertedType = ToType;
1580 return true;
1581 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001582 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001583 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001584 else if (FromType->getAs<BlockPointerType>() &&
1585 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1586 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001587 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001588 ConvertedType = ToType;
1589 return true;
1590 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001591 else
Douglas Gregora119f102008-12-19 19:13:09 +00001592 return false;
1593
Douglas Gregor033f56d2008-12-23 00:53:59 +00001594 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001595 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001596 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001597 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001598 FromPointeeType = FromBlockPtr->getPointeeType();
1599 else
Douglas Gregora119f102008-12-19 19:13:09 +00001600 return false;
1601
Douglas Gregora119f102008-12-19 19:13:09 +00001602 // If we have pointers to pointers, recursively check whether this
1603 // is an Objective-C conversion.
1604 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1605 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1606 IncompatibleObjC)) {
1607 // We always complain about this conversion.
1608 IncompatibleObjC = true;
1609 ConvertedType = ToType;
1610 return true;
1611 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001612 // Allow conversion of pointee being objective-c pointer to another one;
1613 // as in I* to id.
1614 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1615 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1616 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1617 IncompatibleObjC)) {
1618 ConvertedType = ToType;
1619 return true;
1620 }
1621
Douglas Gregor033f56d2008-12-23 00:53:59 +00001622 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001623 // differences in the argument and result types are in Objective-C
1624 // pointer conversions. If so, we permit the conversion (but
1625 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001626 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001627 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001628 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001629 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001630 if (FromFunctionType && ToFunctionType) {
1631 // If the function types are exactly the same, this isn't an
1632 // Objective-C pointer conversion.
1633 if (Context.getCanonicalType(FromPointeeType)
1634 == Context.getCanonicalType(ToPointeeType))
1635 return false;
1636
1637 // Perform the quick checks that will tell us whether these
1638 // function types are obviously different.
1639 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1640 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1641 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1642 return false;
1643
1644 bool HasObjCConversion = false;
1645 if (Context.getCanonicalType(FromFunctionType->getResultType())
1646 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1647 // Okay, the types match exactly. Nothing to do.
1648 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1649 ToFunctionType->getResultType(),
1650 ConvertedType, IncompatibleObjC)) {
1651 // Okay, we have an Objective-C pointer conversion.
1652 HasObjCConversion = true;
1653 } else {
1654 // Function types are too different. Abort.
1655 return false;
1656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregora119f102008-12-19 19:13:09 +00001658 // Check argument types.
1659 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1660 ArgIdx != NumArgs; ++ArgIdx) {
1661 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1662 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1663 if (Context.getCanonicalType(FromArgType)
1664 == Context.getCanonicalType(ToArgType)) {
1665 // Okay, the types match exactly. Nothing to do.
1666 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1667 ConvertedType, IncompatibleObjC)) {
1668 // Okay, we have an Objective-C pointer conversion.
1669 HasObjCConversion = true;
1670 } else {
1671 // Argument types are too different. Abort.
1672 return false;
1673 }
1674 }
1675
1676 if (HasObjCConversion) {
1677 // We had an Objective-C conversion. Allow this pointer
1678 // conversion, but complain about it.
1679 ConvertedType = ToType;
1680 IncompatibleObjC = true;
1681 return true;
1682 }
1683 }
1684
Sebastian Redl72b597d2009-01-25 19:43:20 +00001685 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001686}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001687
1688/// FunctionArgTypesAreEqual - This routine checks two function proto types
1689/// for equlity of their argument types. Caller has already checked that
1690/// they have same number of arguments. This routine assumes that Objective-C
1691/// pointer types which only differ in their protocol qualifiers are equal.
1692bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1693 FunctionProtoType* NewType){
1694 if (!getLangOptions().ObjC1)
1695 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1696 NewType->arg_type_begin());
1697
1698 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1699 N = NewType->arg_type_begin(),
1700 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1701 QualType ToType = (*O);
1702 QualType FromType = (*N);
1703 if (ToType != FromType) {
1704 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1705 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001706 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1707 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1708 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1709 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001710 continue;
1711 }
John McCall8b07ec22010-05-15 11:32:37 +00001712 else if (const ObjCObjectPointerType *PTTo =
1713 ToType->getAs<ObjCObjectPointerType>()) {
1714 if (const ObjCObjectPointerType *PTFr =
1715 FromType->getAs<ObjCObjectPointerType>())
1716 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1717 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001718 }
1719 return false;
1720 }
1721 }
1722 return true;
1723}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724
Douglas Gregor39c16d42008-10-24 04:54:22 +00001725/// CheckPointerConversion - Check the pointer conversion from the
1726/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001727/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001728/// conversions for which IsPointerConversion has already returned
1729/// true. It returns true and produces a diagnostic if there was an
1730/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001731bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001732 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001733 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001734 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001735 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001736 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001737
Douglas Gregor4038cf42010-06-08 17:35:15 +00001738 if (CXXBoolLiteralExpr* LitBool
1739 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001740 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001741 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1742 << ToType;
1743
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001744 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1745 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001746 QualType FromPointeeType = FromPtrType->getPointeeType(),
1747 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001748
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001749 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1750 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001751 // We must have a derived-to-base conversion. Check an
1752 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001753 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1754 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001755 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001756 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001757 return true;
1758
1759 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001760 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001761 }
1762 }
Mike Stump11289f42009-09-09 15:08:12 +00001763 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001764 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001765 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001766 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001767 // Objective-C++ conversions are always okay.
1768 // FIXME: We should have a different class of conversions for the
1769 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001770 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001771 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001772
Steve Naroff7cae42b2009-07-10 23:34:53 +00001773 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001774 return false;
1775}
1776
Sebastian Redl72b597d2009-01-25 19:43:20 +00001777/// IsMemberPointerConversion - Determines whether the conversion of the
1778/// expression From, which has the (possibly adjusted) type FromType, can be
1779/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1780/// If so, returns true and places the converted type (that might differ from
1781/// ToType in its cv-qualifiers at some level) into ConvertedType.
1782bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001783 QualType ToType,
1784 bool InOverloadResolution,
1785 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001786 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001787 if (!ToTypePtr)
1788 return false;
1789
1790 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001791 if (From->isNullPointerConstant(Context,
1792 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1793 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001794 ConvertedType = ToType;
1795 return true;
1796 }
1797
1798 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001799 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001800 if (!FromTypePtr)
1801 return false;
1802
1803 // A pointer to member of B can be converted to a pointer to member of D,
1804 // where D is derived from B (C++ 4.11p2).
1805 QualType FromClass(FromTypePtr->getClass(), 0);
1806 QualType ToClass(ToTypePtr->getClass(), 0);
1807 // FIXME: What happens when these are dependent? Is this function even called?
1808
1809 if (IsDerivedFrom(ToClass, FromClass)) {
1810 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1811 ToClass.getTypePtr());
1812 return true;
1813 }
1814
1815 return false;
1816}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001817
Sebastian Redl72b597d2009-01-25 19:43:20 +00001818/// CheckMemberPointerConversion - Check the member pointer conversion from the
1819/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001820/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001821/// for which IsMemberPointerConversion has already returned true. It returns
1822/// true and produces a diagnostic if there was an error, or returns false
1823/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001824bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001825 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001826 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001827 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001828 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001829 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001830 if (!FromPtrType) {
1831 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001832 assert(From->isNullPointerConstant(Context,
1833 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001834 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001835 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001836 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001837 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001838
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001839 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001840 assert(ToPtrType && "No member pointer cast has a target type "
1841 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001842
Sebastian Redled8f2002009-01-28 18:33:18 +00001843 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1844 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001845
Sebastian Redled8f2002009-01-28 18:33:18 +00001846 // FIXME: What about dependent types?
1847 assert(FromClass->isRecordType() && "Pointer into non-class.");
1848 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001849
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001850 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001851 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001852 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1853 assert(DerivationOkay &&
1854 "Should not have been called if derivation isn't OK.");
1855 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001856
Sebastian Redled8f2002009-01-28 18:33:18 +00001857 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1858 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001859 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1860 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1861 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1862 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001863 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001864
Douglas Gregor89ee6822009-02-28 01:32:25 +00001865 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001866 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1867 << FromClass << ToClass << QualType(VBase, 0)
1868 << From->getSourceRange();
1869 return true;
1870 }
1871
John McCall5b0829a2010-02-10 09:31:12 +00001872 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001873 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1874 Paths.front(),
1875 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001876
Anders Carlssond7923c62009-08-22 23:33:40 +00001877 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001878 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001879 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001880 return false;
1881}
1882
Douglas Gregor9a657932008-10-21 23:43:52 +00001883/// IsQualificationConversion - Determines whether the conversion from
1884/// an rvalue of type FromType to ToType is a qualification conversion
1885/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001886bool
1887Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001888 FromType = Context.getCanonicalType(FromType);
1889 ToType = Context.getCanonicalType(ToType);
1890
1891 // If FromType and ToType are the same type, this is not a
1892 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001893 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001894 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001895
Douglas Gregor9a657932008-10-21 23:43:52 +00001896 // (C++ 4.4p4):
1897 // A conversion can add cv-qualifiers at levels other than the first
1898 // in multi-level pointers, subject to the following rules: [...]
1899 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001900 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001901 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001902 // Within each iteration of the loop, we check the qualifiers to
1903 // determine if this still looks like a qualification
1904 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001905 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001906 // until there are no more pointers or pointers-to-members left to
1907 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001908 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001909
1910 // -- for every j > 0, if const is in cv 1,j then const is in cv
1911 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001912 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001913 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001914
Douglas Gregor9a657932008-10-21 23:43:52 +00001915 // -- if the cv 1,j and cv 2,j are different, then const is in
1916 // every cv for 0 < k < j.
1917 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001918 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001919 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001920
Douglas Gregor9a657932008-10-21 23:43:52 +00001921 // Keep track of whether all prior cv-qualifiers in the "to" type
1922 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001923 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001924 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001925 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001926
1927 // We are left with FromType and ToType being the pointee types
1928 // after unwrapping the original FromType and ToType the same number
1929 // of types. If we unwrapped any pointers, and if FromType and
1930 // ToType have the same unqualified type (since we checked
1931 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001932 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001933}
1934
Douglas Gregor576e98c2009-01-30 23:27:23 +00001935/// Determines whether there is a user-defined conversion sequence
1936/// (C++ [over.ics.user]) that converts expression From to the type
1937/// ToType. If such a conversion exists, User will contain the
1938/// user-defined conversion sequence that performs such a conversion
1939/// and this routine will return true. Otherwise, this routine returns
1940/// false and User is unspecified.
1941///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001942/// \param AllowExplicit true if the conversion should consider C++0x
1943/// "explicit" conversion functions as well as non-explicit conversion
1944/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001945static OverloadingResult
1946IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1947 UserDefinedConversionSequence& User,
1948 OverloadCandidateSet& CandidateSet,
1949 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001950 // Whether we will only visit constructors.
1951 bool ConstructorsOnly = false;
1952
1953 // If the type we are conversion to is a class type, enumerate its
1954 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001955 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001956 // C++ [over.match.ctor]p1:
1957 // When objects of class type are direct-initialized (8.5), or
1958 // copy-initialized from an expression of the same or a
1959 // derived class type (8.5), overload resolution selects the
1960 // constructor. [...] For copy-initialization, the candidate
1961 // functions are all the converting constructors (12.3.1) of
1962 // that class. The argument list is the expression-list within
1963 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00001964 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00001965 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001966 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001967 ConstructorsOnly = true;
1968
John McCall5c32be02010-08-24 20:38:10 +00001969 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001970 // We're not going to find any constructors.
1971 } else if (CXXRecordDecl *ToRecordDecl
1972 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001973 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00001974 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001975 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001976 NamedDecl *D = *Con;
1977 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1978
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001979 // Find the constructor (which may be a template).
1980 CXXConstructorDecl *Constructor = 0;
1981 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001982 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001983 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001984 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001985 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1986 else
John McCalla0296f72010-03-19 07:35:19 +00001987 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001988
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001989 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001990 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001991 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00001992 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1993 /*ExplicitArgs*/ 0,
1994 &From, 1, CandidateSet,
1995 /*SuppressUserConversions=*/
1996 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001997 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001998 // Allow one user-defined conversion when user specifies a
1999 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002000 S.AddOverloadCandidate(Constructor, FoundDecl,
2001 &From, 1, CandidateSet,
2002 /*SuppressUserConversions=*/
2003 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002004 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002005 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002006 }
2007 }
2008
Douglas Gregor5ab11652010-04-17 22:01:05 +00002009 // Enumerate conversion functions, if we're allowed to.
2010 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002011 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2012 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002013 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002014 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002015 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002016 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002017 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2018 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002019 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002020 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002021 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002022 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002023 DeclAccessPair FoundDecl = I.getPair();
2024 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002025 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2026 if (isa<UsingShadowDecl>(D))
2027 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2028
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002029 CXXConversionDecl *Conv;
2030 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002031 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2032 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002033 else
John McCallda4458e2010-03-31 01:36:47 +00002034 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002035
2036 if (AllowExplicit || !Conv->isExplicit()) {
2037 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002038 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2039 ActingContext, From, ToType,
2040 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002041 else
John McCall5c32be02010-08-24 20:38:10 +00002042 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2043 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002044 }
2045 }
2046 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002047 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002048
2049 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002050 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002051 case OR_Success:
2052 // Record the standard conversion we used and the conversion function.
2053 if (CXXConstructorDecl *Constructor
2054 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2055 // C++ [over.ics.user]p1:
2056 // If the user-defined conversion is specified by a
2057 // constructor (12.3.1), the initial standard conversion
2058 // sequence converts the source type to the type required by
2059 // the argument of the constructor.
2060 //
2061 QualType ThisType = Constructor->getThisType(S.Context);
2062 if (Best->Conversions[0].isEllipsis())
2063 User.EllipsisConversion = true;
2064 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002065 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002066 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002067 }
John McCall5c32be02010-08-24 20:38:10 +00002068 User.ConversionFunction = Constructor;
2069 User.After.setAsIdentityConversion();
2070 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2071 User.After.setAllToTypes(ToType);
2072 return OR_Success;
2073 } else if (CXXConversionDecl *Conversion
2074 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2075 // C++ [over.ics.user]p1:
2076 //
2077 // [...] If the user-defined conversion is specified by a
2078 // conversion function (12.3.2), the initial standard
2079 // conversion sequence converts the source type to the
2080 // implicit object parameter of the conversion function.
2081 User.Before = Best->Conversions[0].Standard;
2082 User.ConversionFunction = Conversion;
2083 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002084
John McCall5c32be02010-08-24 20:38:10 +00002085 // C++ [over.ics.user]p2:
2086 // The second standard conversion sequence converts the
2087 // result of the user-defined conversion to the target type
2088 // for the sequence. Since an implicit conversion sequence
2089 // is an initialization, the special rules for
2090 // initialization by user-defined conversion apply when
2091 // selecting the best user-defined conversion for a
2092 // user-defined conversion sequence (see 13.3.3 and
2093 // 13.3.3.1).
2094 User.After = Best->FinalConversion;
2095 return OR_Success;
2096 } else {
2097 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002098 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002099 }
2100
John McCall5c32be02010-08-24 20:38:10 +00002101 case OR_No_Viable_Function:
2102 return OR_No_Viable_Function;
2103 case OR_Deleted:
2104 // No conversion here! We're done.
2105 return OR_Deleted;
2106
2107 case OR_Ambiguous:
2108 return OR_Ambiguous;
2109 }
2110
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002111 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002112}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002113
2114bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002115Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002116 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002117 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002118 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002119 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002120 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002121 if (OvResult == OR_Ambiguous)
2122 Diag(From->getSourceRange().getBegin(),
2123 diag::err_typecheck_ambiguous_condition)
2124 << From->getType() << ToType << From->getSourceRange();
2125 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2126 Diag(From->getSourceRange().getBegin(),
2127 diag::err_typecheck_nonviable_condition)
2128 << From->getType() << ToType << From->getSourceRange();
2129 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002130 return false;
John McCall5c32be02010-08-24 20:38:10 +00002131 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002132 return true;
2133}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002134
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002135/// CompareImplicitConversionSequences - Compare two implicit
2136/// conversion sequences to determine whether one is better than the
2137/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002138static ImplicitConversionSequence::CompareKind
2139CompareImplicitConversionSequences(Sema &S,
2140 const ImplicitConversionSequence& ICS1,
2141 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002142{
2143 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2144 // conversion sequences (as defined in 13.3.3.1)
2145 // -- a standard conversion sequence (13.3.3.1.1) is a better
2146 // conversion sequence than a user-defined conversion sequence or
2147 // an ellipsis conversion sequence, and
2148 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2149 // conversion sequence than an ellipsis conversion sequence
2150 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002151 //
John McCall0d1da222010-01-12 00:44:57 +00002152 // C++0x [over.best.ics]p10:
2153 // For the purpose of ranking implicit conversion sequences as
2154 // described in 13.3.3.2, the ambiguous conversion sequence is
2155 // treated as a user-defined sequence that is indistinguishable
2156 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002157 if (ICS1.getKindRank() < ICS2.getKindRank())
2158 return ImplicitConversionSequence::Better;
2159 else if (ICS2.getKindRank() < ICS1.getKindRank())
2160 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002161
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002162 // The following checks require both conversion sequences to be of
2163 // the same kind.
2164 if (ICS1.getKind() != ICS2.getKind())
2165 return ImplicitConversionSequence::Indistinguishable;
2166
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002167 // Two implicit conversion sequences of the same form are
2168 // indistinguishable conversion sequences unless one of the
2169 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002170 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002171 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002172 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002173 // User-defined conversion sequence U1 is a better conversion
2174 // sequence than another user-defined conversion sequence U2 if
2175 // they contain the same user-defined conversion function or
2176 // constructor and if the second standard conversion sequence of
2177 // U1 is better than the second standard conversion sequence of
2178 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002179 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002180 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002181 return CompareStandardConversionSequences(S,
2182 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002183 ICS2.UserDefined.After);
2184 }
2185
2186 return ImplicitConversionSequence::Indistinguishable;
2187}
2188
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002189static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2190 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2191 Qualifiers Quals;
2192 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2193 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2194 }
2195
2196 return Context.hasSameUnqualifiedType(T1, T2);
2197}
2198
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002199// Per 13.3.3.2p3, compare the given standard conversion sequences to
2200// determine if one is a proper subset of the other.
2201static ImplicitConversionSequence::CompareKind
2202compareStandardConversionSubsets(ASTContext &Context,
2203 const StandardConversionSequence& SCS1,
2204 const StandardConversionSequence& SCS2) {
2205 ImplicitConversionSequence::CompareKind Result
2206 = ImplicitConversionSequence::Indistinguishable;
2207
Douglas Gregore87561a2010-05-23 22:10:15 +00002208 // the identity conversion sequence is considered to be a subsequence of
2209 // any non-identity conversion sequence
2210 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2211 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2212 return ImplicitConversionSequence::Better;
2213 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2214 return ImplicitConversionSequence::Worse;
2215 }
2216
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002217 if (SCS1.Second != SCS2.Second) {
2218 if (SCS1.Second == ICK_Identity)
2219 Result = ImplicitConversionSequence::Better;
2220 else if (SCS2.Second == ICK_Identity)
2221 Result = ImplicitConversionSequence::Worse;
2222 else
2223 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002224 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002225 return ImplicitConversionSequence::Indistinguishable;
2226
2227 if (SCS1.Third == SCS2.Third) {
2228 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2229 : ImplicitConversionSequence::Indistinguishable;
2230 }
2231
2232 if (SCS1.Third == ICK_Identity)
2233 return Result == ImplicitConversionSequence::Worse
2234 ? ImplicitConversionSequence::Indistinguishable
2235 : ImplicitConversionSequence::Better;
2236
2237 if (SCS2.Third == ICK_Identity)
2238 return Result == ImplicitConversionSequence::Better
2239 ? ImplicitConversionSequence::Indistinguishable
2240 : ImplicitConversionSequence::Worse;
2241
2242 return ImplicitConversionSequence::Indistinguishable;
2243}
2244
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002245/// CompareStandardConversionSequences - Compare two standard
2246/// conversion sequences to determine whether one is better than the
2247/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002248static ImplicitConversionSequence::CompareKind
2249CompareStandardConversionSequences(Sema &S,
2250 const StandardConversionSequence& SCS1,
2251 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002252{
2253 // Standard conversion sequence S1 is a better conversion sequence
2254 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2255
2256 // -- S1 is a proper subsequence of S2 (comparing the conversion
2257 // sequences in the canonical form defined by 13.3.3.1.1,
2258 // excluding any Lvalue Transformation; the identity conversion
2259 // sequence is considered to be a subsequence of any
2260 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002261 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002262 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002263 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002264
2265 // -- the rank of S1 is better than the rank of S2 (by the rules
2266 // defined below), or, if not that,
2267 ImplicitConversionRank Rank1 = SCS1.getRank();
2268 ImplicitConversionRank Rank2 = SCS2.getRank();
2269 if (Rank1 < Rank2)
2270 return ImplicitConversionSequence::Better;
2271 else if (Rank2 < Rank1)
2272 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002273
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002274 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2275 // are indistinguishable unless one of the following rules
2276 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002277
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002278 // A conversion that is not a conversion of a pointer, or
2279 // pointer to member, to bool is better than another conversion
2280 // that is such a conversion.
2281 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2282 return SCS2.isPointerConversionToBool()
2283 ? ImplicitConversionSequence::Better
2284 : ImplicitConversionSequence::Worse;
2285
Douglas Gregor5c407d92008-10-23 00:40:37 +00002286 // C++ [over.ics.rank]p4b2:
2287 //
2288 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002289 // conversion of B* to A* is better than conversion of B* to
2290 // void*, and conversion of A* to void* is better than conversion
2291 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002292 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002293 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002294 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002295 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002296 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2297 // Exactly one of the conversion sequences is a conversion to
2298 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002299 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2300 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002301 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2302 // Neither conversion sequence converts to a void pointer; compare
2303 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002304 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002305 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002306 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002307 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2308 // Both conversion sequences are conversions to void
2309 // pointers. Compare the source types to determine if there's an
2310 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002311 QualType FromType1 = SCS1.getFromType();
2312 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002313
2314 // Adjust the types we're converting from via the array-to-pointer
2315 // conversion, if we need to.
2316 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002317 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002318 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002319 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002320
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002321 QualType FromPointee1
2322 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2323 QualType FromPointee2
2324 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002325
John McCall5c32be02010-08-24 20:38:10 +00002326 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002327 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002328 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002329 return ImplicitConversionSequence::Worse;
2330
2331 // Objective-C++: If one interface is more specific than the
2332 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002333 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2334 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002335 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002336 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002337 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002338 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002339 return ImplicitConversionSequence::Worse;
2340 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002342
2343 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2344 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002345 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002346 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002347 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002348
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002349 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002350 // C++0x [over.ics.rank]p3b4:
2351 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2352 // implicit object parameter of a non-static member function declared
2353 // without a ref-qualifier, and S1 binds an rvalue reference to an
2354 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002355 // FIXME: We don't know if we're dealing with the implicit object parameter,
2356 // or if the member function in this case has a ref qualifier.
2357 // (Of course, we don't have ref qualifiers yet.)
2358 if (SCS1.RRefBinding != SCS2.RRefBinding)
2359 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2360 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002361
2362 // C++ [over.ics.rank]p3b4:
2363 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2364 // which the references refer are the same type except for
2365 // top-level cv-qualifiers, and the type to which the reference
2366 // initialized by S2 refers is more cv-qualified than the type
2367 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002368 QualType T1 = SCS1.getToType(2);
2369 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002370 T1 = S.Context.getCanonicalType(T1);
2371 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002372 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002373 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2374 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002375 if (UnqualT1 == UnqualT2) {
2376 // If the type is an array type, promote the element qualifiers to the type
2377 // for comparison.
2378 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002379 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002380 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002381 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002382 if (T2.isMoreQualifiedThan(T1))
2383 return ImplicitConversionSequence::Better;
2384 else if (T1.isMoreQualifiedThan(T2))
2385 return ImplicitConversionSequence::Worse;
2386 }
2387 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002388
2389 return ImplicitConversionSequence::Indistinguishable;
2390}
2391
2392/// CompareQualificationConversions - Compares two standard conversion
2393/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002394/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2395ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002396CompareQualificationConversions(Sema &S,
2397 const StandardConversionSequence& SCS1,
2398 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002399 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002400 // -- S1 and S2 differ only in their qualification conversion and
2401 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2402 // cv-qualification signature of type T1 is a proper subset of
2403 // the cv-qualification signature of type T2, and S1 is not the
2404 // deprecated string literal array-to-pointer conversion (4.2).
2405 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2406 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2407 return ImplicitConversionSequence::Indistinguishable;
2408
2409 // FIXME: the example in the standard doesn't use a qualification
2410 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002411 QualType T1 = SCS1.getToType(2);
2412 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002413 T1 = S.Context.getCanonicalType(T1);
2414 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002415 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002416 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2417 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002418
2419 // If the types are the same, we won't learn anything by unwrapped
2420 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002421 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002422 return ImplicitConversionSequence::Indistinguishable;
2423
Chandler Carruth607f38e2009-12-29 07:16:59 +00002424 // If the type is an array type, promote the element qualifiers to the type
2425 // for comparison.
2426 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002427 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002428 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002429 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002430
Mike Stump11289f42009-09-09 15:08:12 +00002431 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002432 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002433 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002434 // Within each iteration of the loop, we check the qualifiers to
2435 // determine if this still looks like a qualification
2436 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002437 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002438 // until there are no more pointers or pointers-to-members left
2439 // to unwrap. This essentially mimics what
2440 // IsQualificationConversion does, but here we're checking for a
2441 // strict subset of qualifiers.
2442 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2443 // The qualifiers are the same, so this doesn't tell us anything
2444 // about how the sequences rank.
2445 ;
2446 else if (T2.isMoreQualifiedThan(T1)) {
2447 // T1 has fewer qualifiers, so it could be the better sequence.
2448 if (Result == ImplicitConversionSequence::Worse)
2449 // Neither has qualifiers that are a subset of the other's
2450 // qualifiers.
2451 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002452
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002453 Result = ImplicitConversionSequence::Better;
2454 } else if (T1.isMoreQualifiedThan(T2)) {
2455 // T2 has fewer qualifiers, so it could be the better sequence.
2456 if (Result == ImplicitConversionSequence::Better)
2457 // Neither has qualifiers that are a subset of the other's
2458 // qualifiers.
2459 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002460
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002461 Result = ImplicitConversionSequence::Worse;
2462 } else {
2463 // Qualifiers are disjoint.
2464 return ImplicitConversionSequence::Indistinguishable;
2465 }
2466
2467 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002468 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002469 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002470 }
2471
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002472 // Check that the winning standard conversion sequence isn't using
2473 // the deprecated string literal array to pointer conversion.
2474 switch (Result) {
2475 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002476 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002477 Result = ImplicitConversionSequence::Indistinguishable;
2478 break;
2479
2480 case ImplicitConversionSequence::Indistinguishable:
2481 break;
2482
2483 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002484 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002485 Result = ImplicitConversionSequence::Indistinguishable;
2486 break;
2487 }
2488
2489 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002490}
2491
Douglas Gregor5c407d92008-10-23 00:40:37 +00002492/// CompareDerivedToBaseConversions - Compares two standard conversion
2493/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002494/// various kinds of derived-to-base conversions (C++
2495/// [over.ics.rank]p4b3). As part of these checks, we also look at
2496/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002497ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002498CompareDerivedToBaseConversions(Sema &S,
2499 const StandardConversionSequence& SCS1,
2500 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002501 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002502 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002503 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002504 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002505
2506 // Adjust the types we're converting from via the array-to-pointer
2507 // conversion, if we need to.
2508 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002509 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002510 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002511 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002512
2513 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002514 FromType1 = S.Context.getCanonicalType(FromType1);
2515 ToType1 = S.Context.getCanonicalType(ToType1);
2516 FromType2 = S.Context.getCanonicalType(FromType2);
2517 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002518
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002519 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002520 //
2521 // If class B is derived directly or indirectly from class A and
2522 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002523 //
2524 // For Objective-C, we let A, B, and C also be Objective-C
2525 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002526
2527 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002528 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002529 SCS2.Second == ICK_Pointer_Conversion &&
2530 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2531 FromType1->isPointerType() && FromType2->isPointerType() &&
2532 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002533 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002534 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002535 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002536 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002537 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002538 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002539 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002540 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002541
John McCall8b07ec22010-05-15 11:32:37 +00002542 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2543 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2544 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2545 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002546
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002547 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002548 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002549 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002550 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002551 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002552 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002553
2554 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002555 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002556 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002557 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002558 return ImplicitConversionSequence::Worse;
2559 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002560 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002561
2562 // -- conversion of B* to A* is better than conversion of C* to A*,
2563 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002564 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002565 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002566 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002567 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002568
Douglas Gregor237f96c2008-11-26 23:31:11 +00002569 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002570 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002571 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002572 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002573 return ImplicitConversionSequence::Worse;
2574 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002575 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002576 }
2577
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002578 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002579 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2580 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2581 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2582 const MemberPointerType * FromMemPointer1 =
2583 FromType1->getAs<MemberPointerType>();
2584 const MemberPointerType * ToMemPointer1 =
2585 ToType1->getAs<MemberPointerType>();
2586 const MemberPointerType * FromMemPointer2 =
2587 FromType2->getAs<MemberPointerType>();
2588 const MemberPointerType * ToMemPointer2 =
2589 ToType2->getAs<MemberPointerType>();
2590 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2591 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2592 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2593 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2594 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2595 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2596 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2597 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002598 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002599 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002600 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002601 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002602 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002603 return ImplicitConversionSequence::Better;
2604 }
2605 // conversion of B::* to C::* is better than conversion of A::* to C::*
2606 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002607 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002608 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002609 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002610 return ImplicitConversionSequence::Worse;
2611 }
2612 }
2613
Douglas Gregor5ab11652010-04-17 22:01:05 +00002614 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002615 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002616 // -- binding of an expression of type C to a reference of type
2617 // B& is better than binding an expression of type C to a
2618 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002619 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2620 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2621 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002622 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002623 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002624 return ImplicitConversionSequence::Worse;
2625 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002626
Douglas Gregor2fe98832008-11-03 19:09:14 +00002627 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002628 // -- binding of an expression of type B to a reference of type
2629 // A& is better than binding an expression of type C to a
2630 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002631 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2632 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2633 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002634 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002635 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002636 return ImplicitConversionSequence::Worse;
2637 }
2638 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002639
Douglas Gregor5c407d92008-10-23 00:40:37 +00002640 return ImplicitConversionSequence::Indistinguishable;
2641}
2642
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002643/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2644/// determine whether they are reference-related,
2645/// reference-compatible, reference-compatible with added
2646/// qualification, or incompatible, for use in C++ initialization by
2647/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2648/// type, and the first type (T1) is the pointee type of the reference
2649/// type being initialized.
2650Sema::ReferenceCompareResult
2651Sema::CompareReferenceRelationship(SourceLocation Loc,
2652 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002653 bool &DerivedToBase,
2654 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002655 assert(!OrigT1->isReferenceType() &&
2656 "T1 must be the pointee type of the reference type");
2657 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2658
2659 QualType T1 = Context.getCanonicalType(OrigT1);
2660 QualType T2 = Context.getCanonicalType(OrigT2);
2661 Qualifiers T1Quals, T2Quals;
2662 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2663 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2664
2665 // C++ [dcl.init.ref]p4:
2666 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2667 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2668 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002669 DerivedToBase = false;
2670 ObjCConversion = false;
2671 if (UnqualT1 == UnqualT2) {
2672 // Nothing to do.
2673 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002674 IsDerivedFrom(UnqualT2, UnqualT1))
2675 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002676 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2677 UnqualT2->isObjCObjectOrInterfaceType() &&
2678 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2679 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002680 else
2681 return Ref_Incompatible;
2682
2683 // At this point, we know that T1 and T2 are reference-related (at
2684 // least).
2685
2686 // If the type is an array type, promote the element qualifiers to the type
2687 // for comparison.
2688 if (isa<ArrayType>(T1) && T1Quals)
2689 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2690 if (isa<ArrayType>(T2) && T2Quals)
2691 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2692
2693 // C++ [dcl.init.ref]p4:
2694 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2695 // reference-related to T2 and cv1 is the same cv-qualification
2696 // as, or greater cv-qualification than, cv2. For purposes of
2697 // overload resolution, cases for which cv1 is greater
2698 // cv-qualification than cv2 are identified as
2699 // reference-compatible with added qualification (see 13.3.3.2).
2700 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2701 return Ref_Compatible;
2702 else if (T1.isMoreQualifiedThan(T2))
2703 return Ref_Compatible_With_Added_Qualification;
2704 else
2705 return Ref_Related;
2706}
2707
Douglas Gregor836a7e82010-08-11 02:15:33 +00002708/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002709/// with DeclType. Return true if something definite is found.
2710static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002711FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2712 QualType DeclType, SourceLocation DeclLoc,
2713 Expr *Init, QualType T2, bool AllowRvalues,
2714 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002715 assert(T2->isRecordType() && "Can only find conversions of record types.");
2716 CXXRecordDecl *T2RecordDecl
2717 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2718
Douglas Gregor836a7e82010-08-11 02:15:33 +00002719 QualType ToType
2720 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2721 : DeclType;
2722
Sebastian Redld92badf2010-06-30 18:13:39 +00002723 OverloadCandidateSet CandidateSet(DeclLoc);
2724 const UnresolvedSetImpl *Conversions
2725 = T2RecordDecl->getVisibleConversionFunctions();
2726 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2727 E = Conversions->end(); I != E; ++I) {
2728 NamedDecl *D = *I;
2729 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2730 if (isa<UsingShadowDecl>(D))
2731 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2732
2733 FunctionTemplateDecl *ConvTemplate
2734 = dyn_cast<FunctionTemplateDecl>(D);
2735 CXXConversionDecl *Conv;
2736 if (ConvTemplate)
2737 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2738 else
2739 Conv = cast<CXXConversionDecl>(D);
2740
Douglas Gregor836a7e82010-08-11 02:15:33 +00002741 // If this is an explicit conversion, and we're not allowed to consider
2742 // explicit conversions, skip it.
2743 if (!AllowExplicit && Conv->isExplicit())
2744 continue;
2745
2746 if (AllowRvalues) {
2747 bool DerivedToBase = false;
2748 bool ObjCConversion = false;
2749 if (!ConvTemplate &&
2750 S.CompareReferenceRelationship(DeclLoc,
2751 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2752 DeclType.getNonReferenceType().getUnqualifiedType(),
2753 DerivedToBase, ObjCConversion)
2754 == Sema::Ref_Incompatible)
2755 continue;
2756 } else {
2757 // If the conversion function doesn't return a reference type,
2758 // it can't be considered for this conversion. An rvalue reference
2759 // is only acceptable if its referencee is a function type.
2760
2761 const ReferenceType *RefType =
2762 Conv->getConversionType()->getAs<ReferenceType>();
2763 if (!RefType ||
2764 (!RefType->isLValueReferenceType() &&
2765 !RefType->getPointeeType()->isFunctionType()))
2766 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002767 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002768
2769 if (ConvTemplate)
2770 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2771 Init, ToType, CandidateSet);
2772 else
2773 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2774 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002775 }
2776
2777 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002778 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002779 case OR_Success:
2780 // C++ [over.ics.ref]p1:
2781 //
2782 // [...] If the parameter binds directly to the result of
2783 // applying a conversion function to the argument
2784 // expression, the implicit conversion sequence is a
2785 // user-defined conversion sequence (13.3.3.1.2), with the
2786 // second standard conversion sequence either an identity
2787 // conversion or, if the conversion function returns an
2788 // entity of a type that is a derived class of the parameter
2789 // type, a derived-to-base Conversion.
2790 if (!Best->FinalConversion.DirectBinding)
2791 return false;
2792
2793 ICS.setUserDefined();
2794 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2795 ICS.UserDefined.After = Best->FinalConversion;
2796 ICS.UserDefined.ConversionFunction = Best->Function;
2797 ICS.UserDefined.EllipsisConversion = false;
2798 assert(ICS.UserDefined.After.ReferenceBinding &&
2799 ICS.UserDefined.After.DirectBinding &&
2800 "Expected a direct reference binding!");
2801 return true;
2802
2803 case OR_Ambiguous:
2804 ICS.setAmbiguous();
2805 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2806 Cand != CandidateSet.end(); ++Cand)
2807 if (Cand->Viable)
2808 ICS.Ambiguous.addConversion(Cand->Function);
2809 return true;
2810
2811 case OR_No_Viable_Function:
2812 case OR_Deleted:
2813 // There was no suitable conversion, or we found a deleted
2814 // conversion; continue with other checks.
2815 return false;
2816 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002817
2818 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002819}
2820
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002821/// \brief Compute an implicit conversion sequence for reference
2822/// initialization.
2823static ImplicitConversionSequence
2824TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2825 SourceLocation DeclLoc,
2826 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002827 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002828 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2829
2830 // Most paths end in a failed conversion.
2831 ImplicitConversionSequence ICS;
2832 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2833
2834 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2835 QualType T2 = Init->getType();
2836
2837 // If the initializer is the address of an overloaded function, try
2838 // to resolve the overloaded function. If all goes well, T2 is the
2839 // type of the resulting function.
2840 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2841 DeclAccessPair Found;
2842 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2843 false, Found))
2844 T2 = Fn->getType();
2845 }
2846
2847 // Compute some basic properties of the types and the initializer.
2848 bool isRValRef = DeclType->isRValueReferenceType();
2849 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002850 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002851 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002852 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002853 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2854 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002855
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002856
Sebastian Redld92badf2010-06-30 18:13:39 +00002857 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002858 // A reference to type "cv1 T1" is initialized by an expression
2859 // of type "cv2 T2" as follows:
2860
Sebastian Redld92badf2010-06-30 18:13:39 +00002861 // -- If reference is an lvalue reference and the initializer expression
2862 // The next bullet point (T1 is a function) is pretty much equivalent to this
2863 // one, so it's handled here.
2864 if (!isRValRef || T1->isFunctionType()) {
2865 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2866 // reference-compatible with "cv2 T2," or
2867 //
2868 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2869 if (InitCategory.isLValue() &&
2870 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002871 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002872 // When a parameter of reference type binds directly (8.5.3)
2873 // to an argument expression, the implicit conversion sequence
2874 // is the identity conversion, unless the argument expression
2875 // has a type that is a derived class of the parameter type,
2876 // in which case the implicit conversion sequence is a
2877 // derived-to-base Conversion (13.3.3.1).
2878 ICS.setStandard();
2879 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002880 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2881 : ObjCConversion? ICK_Compatible_Conversion
2882 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002883 ICS.Standard.Third = ICK_Identity;
2884 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2885 ICS.Standard.setToType(0, T2);
2886 ICS.Standard.setToType(1, T1);
2887 ICS.Standard.setToType(2, T1);
2888 ICS.Standard.ReferenceBinding = true;
2889 ICS.Standard.DirectBinding = true;
2890 ICS.Standard.RRefBinding = isRValRef;
2891 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002892
Sebastian Redld92badf2010-06-30 18:13:39 +00002893 // Nothing more to do: the inaccessibility/ambiguity check for
2894 // derived-to-base conversions is suppressed when we're
2895 // computing the implicit conversion sequence (C++
2896 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002897 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002898 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002899
Sebastian Redld92badf2010-06-30 18:13:39 +00002900 // -- has a class type (i.e., T2 is a class type), where T1 is
2901 // not reference-related to T2, and can be implicitly
2902 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2903 // is reference-compatible with "cv3 T3" 92) (this
2904 // conversion is selected by enumerating the applicable
2905 // conversion functions (13.3.1.6) and choosing the best
2906 // one through overload resolution (13.3)),
2907 if (!SuppressUserConversions && T2->isRecordType() &&
2908 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2909 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002910 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2911 Init, T2, /*AllowRvalues=*/false,
2912 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002913 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002914 }
2915 }
2916
Sebastian Redld92badf2010-06-30 18:13:39 +00002917 // -- Otherwise, the reference shall be an lvalue reference to a
2918 // non-volatile const type (i.e., cv1 shall be const), or the reference
2919 // shall be an rvalue reference and the initializer expression shall be
2920 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002921 //
2922 // We actually handle one oddity of C++ [over.ics.ref] at this
2923 // point, which is that, due to p2 (which short-circuits reference
2924 // binding by only attempting a simple conversion for non-direct
2925 // bindings) and p3's strange wording, we allow a const volatile
2926 // reference to bind to an rvalue. Hence the check for the presence
2927 // of "const" rather than checking for "const" being the only
2928 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002929 // This is also the point where rvalue references and lvalue inits no longer
2930 // go together.
2931 if ((!isRValRef && !T1.isConstQualified()) ||
2932 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002933 return ICS;
2934
Sebastian Redld92badf2010-06-30 18:13:39 +00002935 // -- If T1 is a function type, then
2936 // -- if T2 is the same type as T1, the reference is bound to the
2937 // initializer expression lvalue;
2938 // -- if T2 is a class type and the initializer expression can be
2939 // implicitly converted to an lvalue of type T1 [...], the
2940 // reference is bound to the function lvalue that is the result
2941 // of the conversion;
2942 // This is the same as for the lvalue case above, so it was handled there.
2943 // -- otherwise, the program is ill-formed.
2944 // This is the one difference to the lvalue case.
2945 if (T1->isFunctionType())
2946 return ICS;
2947
2948 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002949 // -- the initializer expression is an rvalue and "cv1 T1"
2950 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002951 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002952 // -- T1 is not reference-related to T2 and the initializer
2953 // expression can be implicitly converted to an rvalue
2954 // of type "cv3 T3" (this conversion is selected by
2955 // enumerating the applicable conversion functions
2956 // (13.3.1.6) and choosing the best one through overload
2957 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002958 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002959 // then the reference is bound to the initializer
2960 // expression rvalue in the first case and to the object
2961 // that is the result of the conversion in the second case
2962 // (or, in either case, to the appropriate base class
2963 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002964 if (T2->isRecordType()) {
2965 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2966 // direct binding in C++0x but not in C++03.
2967 if (InitCategory.isRValue() &&
2968 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2969 ICS.setStandard();
2970 ICS.Standard.First = ICK_Identity;
2971 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2972 : ObjCConversion? ICK_Compatible_Conversion
2973 : ICK_Identity;
2974 ICS.Standard.Third = ICK_Identity;
2975 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2976 ICS.Standard.setToType(0, T2);
2977 ICS.Standard.setToType(1, T1);
2978 ICS.Standard.setToType(2, T1);
2979 ICS.Standard.ReferenceBinding = true;
2980 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2981 ICS.Standard.RRefBinding = isRValRef;
2982 ICS.Standard.CopyConstructor = 0;
2983 return ICS;
2984 }
2985
2986 // Second case: not reference-related.
2987 if (RefRelationship == Sema::Ref_Incompatible &&
2988 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2989 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2990 Init, T2, /*AllowRvalues=*/true,
2991 AllowExplicit))
2992 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002993 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002994
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002995 // -- Otherwise, a temporary of type "cv1 T1" is created and
2996 // initialized from the initializer expression using the
2997 // rules for a non-reference copy initialization (8.5). The
2998 // reference is then bound to the temporary. If T1 is
2999 // reference-related to T2, cv1 must be the same
3000 // cv-qualification as, or greater cv-qualification than,
3001 // cv2; otherwise, the program is ill-formed.
3002 if (RefRelationship == Sema::Ref_Related) {
3003 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3004 // we would be reference-compatible or reference-compatible with
3005 // added qualification. But that wasn't the case, so the reference
3006 // initialization fails.
3007 return ICS;
3008 }
3009
3010 // If at least one of the types is a class type, the types are not
3011 // related, and we aren't allowed any user conversions, the
3012 // reference binding fails. This case is important for breaking
3013 // recursion, since TryImplicitConversion below will attempt to
3014 // create a temporary through the use of a copy constructor.
3015 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3016 (T1->isRecordType() || T2->isRecordType()))
3017 return ICS;
3018
3019 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003020 // When a parameter of reference type is not bound directly to
3021 // an argument expression, the conversion sequence is the one
3022 // required to convert the argument expression to the
3023 // underlying type of the reference according to
3024 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3025 // to copy-initializing a temporary of the underlying type with
3026 // the argument expression. Any difference in top-level
3027 // cv-qualification is subsumed by the initialization itself
3028 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003029 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3030 /*AllowExplicit=*/false,
3031 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003032
3033 // Of course, that's still a reference binding.
3034 if (ICS.isStandard()) {
3035 ICS.Standard.ReferenceBinding = true;
3036 ICS.Standard.RRefBinding = isRValRef;
3037 } else if (ICS.isUserDefined()) {
3038 ICS.UserDefined.After.ReferenceBinding = true;
3039 ICS.UserDefined.After.RRefBinding = isRValRef;
3040 }
3041 return ICS;
3042}
3043
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003044/// TryCopyInitialization - Try to copy-initialize a value of type
3045/// ToType from the expression From. Return the implicit conversion
3046/// sequence required to pass this argument, which may be a bad
3047/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003048/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003049/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003050static ImplicitConversionSequence
3051TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003052 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003053 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003054 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003055 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003056 /*FIXME:*/From->getLocStart(),
3057 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003058 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003059
John McCall5c32be02010-08-24 20:38:10 +00003060 return TryImplicitConversion(S, From, ToType,
3061 SuppressUserConversions,
3062 /*AllowExplicit=*/false,
3063 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003064}
3065
Douglas Gregor436424c2008-11-18 23:14:02 +00003066/// TryObjectArgumentInitialization - Try to initialize the object
3067/// parameter of the given member function (@c Method) from the
3068/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003069static ImplicitConversionSequence
3070TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3071 CXXMethodDecl *Method,
3072 CXXRecordDecl *ActingContext) {
3073 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003074 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3075 // const volatile object.
3076 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3077 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003078 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003079
3080 // Set up the conversion sequence as a "bad" conversion, to allow us
3081 // to exit early.
3082 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003083
3084 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003085 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003086 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003087 FromType = PT->getPointeeType();
3088
3089 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003090
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003091 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003092 // where X is the class of which the function is a member
3093 // (C++ [over.match.funcs]p4). However, when finding an implicit
3094 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003095 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003096 // (C++ [over.match.funcs]p5). We perform a simplified version of
3097 // reference binding here, that allows class rvalues to bind to
3098 // non-constant references.
3099
3100 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3101 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003102 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003103 if (ImplicitParamType.getCVRQualifiers()
3104 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003105 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003106 ICS.setBad(BadConversionSequence::bad_qualifiers,
3107 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003108 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003109 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003110
3111 // Check that we have either the same type or a derived type. It
3112 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003113 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003114 ImplicitConversionKind SecondKind;
3115 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3116 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003117 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003118 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003119 else {
John McCall65eb8792010-02-25 01:37:24 +00003120 ICS.setBad(BadConversionSequence::unrelated_class,
3121 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003122 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003123 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003124
3125 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003126 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003127 ICS.Standard.setAsIdentityConversion();
3128 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003129 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003130 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003131 ICS.Standard.ReferenceBinding = true;
3132 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003133 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003134 return ICS;
3135}
3136
3137/// PerformObjectArgumentInitialization - Perform initialization of
3138/// the implicit object parameter for the given Method with the given
3139/// expression.
3140bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003141Sema::PerformObjectArgumentInitialization(Expr *&From,
3142 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003143 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003144 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003145 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003146 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003147 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003148
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003149 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003150 FromRecordType = PT->getPointeeType();
3151 DestType = Method->getThisType(Context);
3152 } else {
3153 FromRecordType = From->getType();
3154 DestType = ImplicitParamRecordType;
3155 }
3156
John McCall6e9f8f62009-12-03 04:06:58 +00003157 // Note that we always use the true parent context when performing
3158 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003159 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003160 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003161 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003162 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003163 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003164 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003165 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003167 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003168 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003169
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003170 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003171 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003172 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003173 return false;
3174}
3175
Douglas Gregor5fb53972009-01-14 15:45:31 +00003176/// TryContextuallyConvertToBool - Attempt to contextually convert the
3177/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003178static ImplicitConversionSequence
3179TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003180 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003181 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003182 // FIXME: Are these flags correct?
3183 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003184 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003185 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003186}
3187
3188/// PerformContextuallyConvertToBool - Perform a contextual conversion
3189/// of the expression From to bool (C++0x [conv]p3).
3190bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003191 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003192 if (!ICS.isBad())
3193 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003194
Fariborz Jahanian76197412009-11-18 18:26:29 +00003195 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003196 return Diag(From->getSourceRange().getBegin(),
3197 diag::err_typecheck_bool_condition)
3198 << From->getType() << From->getSourceRange();
3199 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003200}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003201
3202/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3203/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003204static ImplicitConversionSequence
3205TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3206 QualType Ty = S.Context.getObjCIdType();
3207 return TryImplicitConversion(S, From, Ty,
3208 // FIXME: Are these flags correct?
3209 /*SuppressUserConversions=*/false,
3210 /*AllowExplicit=*/true,
3211 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003212}
John McCall5c32be02010-08-24 20:38:10 +00003213
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003214/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3215/// of the expression From to 'id'.
3216bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003217 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003218 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003219 if (!ICS.isBad())
3220 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3221 return true;
3222}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003223
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003224/// \brief Attempt to convert the given expression to an integral or
3225/// enumeration type.
3226///
3227/// This routine will attempt to convert an expression of class type to an
3228/// integral or enumeration type, if that class type only has a single
3229/// conversion to an integral or enumeration type.
3230///
Douglas Gregor4799d032010-06-30 00:20:43 +00003231/// \param Loc The source location of the construct that requires the
3232/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003233///
Douglas Gregor4799d032010-06-30 00:20:43 +00003234/// \param FromE The expression we're converting from.
3235///
3236/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3237/// have integral or enumeration type.
3238///
3239/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3240/// incomplete class type.
3241///
3242/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3243/// explicit conversion function (because no implicit conversion functions
3244/// were available). This is a recovery mode.
3245///
3246/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3247/// showing which conversion was picked.
3248///
3249/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3250/// conversion function that could convert to integral or enumeration type.
3251///
3252/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3253/// usable conversion function.
3254///
3255/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3256/// function, which may be an extension in this case.
3257///
3258/// \returns The expression, converted to an integral or enumeration type if
3259/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003260ExprResult
John McCallb268a282010-08-23 23:25:46 +00003261Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003262 const PartialDiagnostic &NotIntDiag,
3263 const PartialDiagnostic &IncompleteDiag,
3264 const PartialDiagnostic &ExplicitConvDiag,
3265 const PartialDiagnostic &ExplicitConvNote,
3266 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003267 const PartialDiagnostic &AmbigNote,
3268 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003269 // We can't perform any more checking for type-dependent expressions.
3270 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003271 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003272
3273 // If the expression already has integral or enumeration type, we're golden.
3274 QualType T = From->getType();
3275 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003276 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003277
3278 // FIXME: Check for missing '()' if T is a function type?
3279
3280 // If we don't have a class type in C++, there's no way we can get an
3281 // expression of integral or enumeration type.
3282 const RecordType *RecordTy = T->getAs<RecordType>();
3283 if (!RecordTy || !getLangOptions().CPlusPlus) {
3284 Diag(Loc, NotIntDiag)
3285 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003286 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003287 }
3288
3289 // We must have a complete class type.
3290 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003291 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003292
3293 // Look for a conversion to an integral or enumeration type.
3294 UnresolvedSet<4> ViableConversions;
3295 UnresolvedSet<4> ExplicitConversions;
3296 const UnresolvedSetImpl *Conversions
3297 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3298
3299 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3300 E = Conversions->end();
3301 I != E;
3302 ++I) {
3303 if (CXXConversionDecl *Conversion
3304 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3305 if (Conversion->getConversionType().getNonReferenceType()
3306 ->isIntegralOrEnumerationType()) {
3307 if (Conversion->isExplicit())
3308 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3309 else
3310 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3311 }
3312 }
3313
3314 switch (ViableConversions.size()) {
3315 case 0:
3316 if (ExplicitConversions.size() == 1) {
3317 DeclAccessPair Found = ExplicitConversions[0];
3318 CXXConversionDecl *Conversion
3319 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3320
3321 // The user probably meant to invoke the given explicit
3322 // conversion; use it.
3323 QualType ConvTy
3324 = Conversion->getConversionType().getNonReferenceType();
3325 std::string TypeStr;
3326 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3327
3328 Diag(Loc, ExplicitConvDiag)
3329 << T << ConvTy
3330 << FixItHint::CreateInsertion(From->getLocStart(),
3331 "static_cast<" + TypeStr + ">(")
3332 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3333 ")");
3334 Diag(Conversion->getLocation(), ExplicitConvNote)
3335 << ConvTy->isEnumeralType() << ConvTy;
3336
3337 // If we aren't in a SFINAE context, build a call to the
3338 // explicit conversion function.
3339 if (isSFINAEContext())
3340 return ExprError();
3341
3342 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003343 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003344 }
3345
3346 // We'll complain below about a non-integral condition type.
3347 break;
3348
3349 case 1: {
3350 // Apply this conversion.
3351 DeclAccessPair Found = ViableConversions[0];
3352 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003353
3354 CXXConversionDecl *Conversion
3355 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3356 QualType ConvTy
3357 = Conversion->getConversionType().getNonReferenceType();
3358 if (ConvDiag.getDiagID()) {
3359 if (isSFINAEContext())
3360 return ExprError();
3361
3362 Diag(Loc, ConvDiag)
3363 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3364 }
3365
John McCallb268a282010-08-23 23:25:46 +00003366 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003367 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003368 break;
3369 }
3370
3371 default:
3372 Diag(Loc, AmbigDiag)
3373 << T << From->getSourceRange();
3374 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3375 CXXConversionDecl *Conv
3376 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3377 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3378 Diag(Conv->getLocation(), AmbigNote)
3379 << ConvTy->isEnumeralType() << ConvTy;
3380 }
John McCallb268a282010-08-23 23:25:46 +00003381 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003382 }
3383
Douglas Gregor5823da32010-06-29 23:25:20 +00003384 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003385 Diag(Loc, NotIntDiag)
3386 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003387
John McCallb268a282010-08-23 23:25:46 +00003388 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003389}
3390
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003391/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003392/// candidate functions, using the given function call arguments. If
3393/// @p SuppressUserConversions, then don't allow user-defined
3394/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003395///
3396/// \para PartialOverloading true if we are performing "partial" overloading
3397/// based on an incomplete set of function arguments. This feature is used by
3398/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003399void
3400Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003401 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003402 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003403 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003404 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003405 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003406 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003407 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003408 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003409 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003410 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003411
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003413 if (!isa<CXXConstructorDecl>(Method)) {
3414 // If we get here, it's because we're calling a member function
3415 // that is named without a member access expression (e.g.,
3416 // "this->f") that was either written explicitly or created
3417 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003418 // function, e.g., X::f(). We use an empty type for the implied
3419 // object argument (C++ [over.call.func]p3), and the acting context
3420 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003421 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003422 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003423 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003424 return;
3425 }
3426 // We treat a constructor like a non-member function, since its object
3427 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003428 }
3429
Douglas Gregorff7028a2009-11-13 23:59:09 +00003430 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003431 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003432
Douglas Gregor27381f32009-11-23 12:27:39 +00003433 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003434 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003435
Douglas Gregorffe14e32009-11-14 01:20:54 +00003436 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3437 // C++ [class.copy]p3:
3438 // A member function template is never instantiated to perform the copy
3439 // of a class object to an object of its class type.
3440 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3441 if (NumArgs == 1 &&
3442 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003443 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3444 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003445 return;
3446 }
3447
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003448 // Add this candidate
3449 CandidateSet.push_back(OverloadCandidate());
3450 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003451 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003452 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003453 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003454 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003455 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003456
3457 unsigned NumArgsInProto = Proto->getNumArgs();
3458
3459 // (C++ 13.3.2p2): A candidate function having fewer than m
3460 // parameters is viable only if it has an ellipsis in its parameter
3461 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003462 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3463 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003464 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003465 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003466 return;
3467 }
3468
3469 // (C++ 13.3.2p2): A candidate function having more than m parameters
3470 // is viable only if the (m+1)st parameter has a default argument
3471 // (8.3.6). For the purposes of overload resolution, the
3472 // parameter list is truncated on the right, so that there are
3473 // exactly m parameters.
3474 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003475 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003476 // Not enough arguments.
3477 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003478 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003479 return;
3480 }
3481
3482 // Determine the implicit conversion sequences for each of the
3483 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003484 Candidate.Conversions.resize(NumArgs);
3485 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3486 if (ArgIdx < NumArgsInProto) {
3487 // (C++ 13.3.2p3): for F to be a viable function, there shall
3488 // exist for each argument an implicit conversion sequence
3489 // (13.3.3.1) that converts that argument to the corresponding
3490 // parameter of F.
3491 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003492 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003493 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003494 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003495 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003496 if (Candidate.Conversions[ArgIdx].isBad()) {
3497 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003498 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003499 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003500 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003501 } else {
3502 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3503 // argument for which there is no corresponding parameter is
3504 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003505 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003506 }
3507 }
3508}
3509
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003510/// \brief Add all of the function declarations in the given function set to
3511/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003512void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003513 Expr **Args, unsigned NumArgs,
3514 OverloadCandidateSet& CandidateSet,
3515 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003516 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003517 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3518 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003519 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003520 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003521 cast<CXXMethodDecl>(FD)->getParent(),
3522 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003523 CandidateSet, SuppressUserConversions);
3524 else
John McCalla0296f72010-03-19 07:35:19 +00003525 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003526 SuppressUserConversions);
3527 } else {
John McCalla0296f72010-03-19 07:35:19 +00003528 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003529 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3530 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003531 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003532 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003533 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003534 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003535 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003536 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003537 else
John McCalla0296f72010-03-19 07:35:19 +00003538 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003539 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003540 Args, NumArgs, CandidateSet,
3541 SuppressUserConversions);
3542 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003543 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003544}
3545
John McCallf0f1cf02009-11-17 07:50:12 +00003546/// AddMethodCandidate - Adds a named decl (which is some kind of
3547/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003548void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003549 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003550 Expr **Args, unsigned NumArgs,
3551 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003552 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003553 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003554 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003555
3556 if (isa<UsingShadowDecl>(Decl))
3557 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3558
3559 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3560 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3561 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003562 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3563 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003564 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003565 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003566 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003567 } else {
John McCalla0296f72010-03-19 07:35:19 +00003568 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003569 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003570 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003571 }
3572}
3573
Douglas Gregor436424c2008-11-18 23:14:02 +00003574/// AddMethodCandidate - Adds the given C++ member function to the set
3575/// of candidate functions, using the given function call arguments
3576/// and the object argument (@c Object). For example, in a call
3577/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3578/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3579/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003580/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003581void
John McCalla0296f72010-03-19 07:35:19 +00003582Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003583 CXXRecordDecl *ActingContext, QualType ObjectType,
3584 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003585 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003586 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003587 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003588 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003589 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003590 assert(!isa<CXXConstructorDecl>(Method) &&
3591 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003592
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003593 if (!CandidateSet.isNewCandidate(Method))
3594 return;
3595
Douglas Gregor27381f32009-11-23 12:27:39 +00003596 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003597 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003598
Douglas Gregor436424c2008-11-18 23:14:02 +00003599 // Add this candidate
3600 CandidateSet.push_back(OverloadCandidate());
3601 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003602 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003603 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003604 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003605 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003606
3607 unsigned NumArgsInProto = Proto->getNumArgs();
3608
3609 // (C++ 13.3.2p2): A candidate function having fewer than m
3610 // parameters is viable only if it has an ellipsis in its parameter
3611 // list (8.3.5).
3612 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3613 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003614 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003615 return;
3616 }
3617
3618 // (C++ 13.3.2p2): A candidate function having more than m parameters
3619 // is viable only if the (m+1)st parameter has a default argument
3620 // (8.3.6). For the purposes of overload resolution, the
3621 // parameter list is truncated on the right, so that there are
3622 // exactly m parameters.
3623 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3624 if (NumArgs < MinRequiredArgs) {
3625 // Not enough arguments.
3626 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003627 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003628 return;
3629 }
3630
3631 Candidate.Viable = true;
3632 Candidate.Conversions.resize(NumArgs + 1);
3633
John McCall6e9f8f62009-12-03 04:06:58 +00003634 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003635 // The implicit object argument is ignored.
3636 Candidate.IgnoreObjectArgument = true;
3637 else {
3638 // Determine the implicit conversion sequence for the object
3639 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003640 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003641 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3642 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003643 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003644 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003645 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003646 return;
3647 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003648 }
3649
3650 // Determine the implicit conversion sequences for each of the
3651 // arguments.
3652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3653 if (ArgIdx < NumArgsInProto) {
3654 // (C++ 13.3.2p3): for F to be a viable function, there shall
3655 // exist for each argument an implicit conversion sequence
3656 // (13.3.3.1) that converts that argument to the corresponding
3657 // parameter of F.
3658 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003659 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003660 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003661 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003662 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003663 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003664 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003665 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003666 break;
3667 }
3668 } else {
3669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3670 // argument for which there is no corresponding parameter is
3671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003672 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003673 }
3674 }
3675}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003676
Douglas Gregor97628d62009-08-21 00:16:32 +00003677/// \brief Add a C++ member function template as a candidate to the candidate
3678/// set, using template argument deduction to produce an appropriate member
3679/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003680void
Douglas Gregor97628d62009-08-21 00:16:32 +00003681Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003682 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003683 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003684 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003685 QualType ObjectType,
3686 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003687 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003688 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003689 if (!CandidateSet.isNewCandidate(MethodTmpl))
3690 return;
3691
Douglas Gregor97628d62009-08-21 00:16:32 +00003692 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003693 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003694 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003695 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003696 // candidate functions in the usual way.113) A given name can refer to one
3697 // or more function templates and also to a set of overloaded non-template
3698 // functions. In such a case, the candidate functions generated from each
3699 // function template are combined with the set of non-template candidate
3700 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003701 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003702 FunctionDecl *Specialization = 0;
3703 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003704 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003705 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003706 CandidateSet.push_back(OverloadCandidate());
3707 OverloadCandidate &Candidate = CandidateSet.back();
3708 Candidate.FoundDecl = FoundDecl;
3709 Candidate.Function = MethodTmpl->getTemplatedDecl();
3710 Candidate.Viable = false;
3711 Candidate.FailureKind = ovl_fail_bad_deduction;
3712 Candidate.IsSurrogate = false;
3713 Candidate.IgnoreObjectArgument = false;
3714 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3715 Info);
3716 return;
3717 }
Mike Stump11289f42009-09-09 15:08:12 +00003718
Douglas Gregor97628d62009-08-21 00:16:32 +00003719 // Add the function template specialization produced by template argument
3720 // deduction as a candidate.
3721 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003722 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003723 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003724 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003725 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003726 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003727}
3728
Douglas Gregor05155d82009-08-21 23:19:43 +00003729/// \brief Add a C++ function template specialization as a candidate
3730/// in the candidate set, using template argument deduction to produce
3731/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003732void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003733Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003734 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003735 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003736 Expr **Args, unsigned NumArgs,
3737 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003738 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003739 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3740 return;
3741
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003742 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003743 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003744 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003745 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003746 // candidate functions in the usual way.113) A given name can refer to one
3747 // or more function templates and also to a set of overloaded non-template
3748 // functions. In such a case, the candidate functions generated from each
3749 // function template are combined with the set of non-template candidate
3750 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003751 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003752 FunctionDecl *Specialization = 0;
3753 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003754 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003755 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003756 CandidateSet.push_back(OverloadCandidate());
3757 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003758 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003759 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3760 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003761 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003762 Candidate.IsSurrogate = false;
3763 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003764 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3765 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003766 return;
3767 }
Mike Stump11289f42009-09-09 15:08:12 +00003768
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003769 // Add the function template specialization produced by template argument
3770 // deduction as a candidate.
3771 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003772 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003773 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003774}
Mike Stump11289f42009-09-09 15:08:12 +00003775
Douglas Gregora1f013e2008-11-07 22:36:19 +00003776/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003777/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003778/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003779/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003780/// (which may or may not be the same type as the type that the
3781/// conversion function produces).
3782void
3783Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003784 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003785 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003786 Expr *From, QualType ToType,
3787 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003788 assert(!Conversion->getDescribedFunctionTemplate() &&
3789 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003790 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003791 if (!CandidateSet.isNewCandidate(Conversion))
3792 return;
3793
Douglas Gregor27381f32009-11-23 12:27:39 +00003794 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003795 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003796
Douglas Gregora1f013e2008-11-07 22:36:19 +00003797 // Add this candidate
3798 CandidateSet.push_back(OverloadCandidate());
3799 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003800 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003801 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003802 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003803 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003804 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003805 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003806 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003807 Candidate.Viable = true;
3808 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003809
Douglas Gregor6affc782010-08-19 15:37:02 +00003810 // C++ [over.match.funcs]p4:
3811 // For conversion functions, the function is considered to be a member of
3812 // the class of the implicit implied object argument for the purpose of
3813 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003814 //
3815 // Determine the implicit conversion sequence for the implicit
3816 // object parameter.
3817 QualType ImplicitParamType = From->getType();
3818 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3819 ImplicitParamType = FromPtrType->getPointeeType();
3820 CXXRecordDecl *ConversionContext
3821 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3822
3823 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003824 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003825 ConversionContext);
3826
John McCall0d1da222010-01-12 00:44:57 +00003827 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003828 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003829 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003830 return;
3831 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003832
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003833 // We won't go through a user-define type conversion function to convert a
3834 // derived to base as such conversions are given Conversion Rank. They only
3835 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3836 QualType FromCanon
3837 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3838 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3839 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3840 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003841 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003842 return;
3843 }
3844
Douglas Gregora1f013e2008-11-07 22:36:19 +00003845 // To determine what the conversion from the result of calling the
3846 // conversion function to the type we're eventually trying to
3847 // convert to (ToType), we need to synthesize a call to the
3848 // conversion function and attempt copy initialization from it. This
3849 // makes sure that we get the right semantics with respect to
3850 // lvalues/rvalues and the type. Fortunately, we can allocate this
3851 // call on the stack and we don't need its arguments to be
3852 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003853 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003854 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003855 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3856 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003857 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003858 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003859
3860 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003861 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3862 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003863 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003864 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003865 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003866 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003867 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003868 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003869 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003870
John McCall0d1da222010-01-12 00:44:57 +00003871 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003872 case ImplicitConversionSequence::StandardConversion:
3873 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003874
3875 // C++ [over.ics.user]p3:
3876 // If the user-defined conversion is specified by a specialization of a
3877 // conversion function template, the second standard conversion sequence
3878 // shall have exact match rank.
3879 if (Conversion->getPrimaryTemplate() &&
3880 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3881 Candidate.Viable = false;
3882 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3883 }
3884
Douglas Gregora1f013e2008-11-07 22:36:19 +00003885 break;
3886
3887 case ImplicitConversionSequence::BadConversion:
3888 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003889 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003890 break;
3891
3892 default:
Mike Stump11289f42009-09-09 15:08:12 +00003893 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003894 "Can only end up with a standard conversion sequence or failure");
3895 }
3896}
3897
Douglas Gregor05155d82009-08-21 23:19:43 +00003898/// \brief Adds a conversion function template specialization
3899/// candidate to the overload set, using template argument deduction
3900/// to deduce the template arguments of the conversion function
3901/// template from the type that we are converting to (C++
3902/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003903void
Douglas Gregor05155d82009-08-21 23:19:43 +00003904Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003905 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003906 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003907 Expr *From, QualType ToType,
3908 OverloadCandidateSet &CandidateSet) {
3909 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3910 "Only conversion function templates permitted here");
3911
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003912 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3913 return;
3914
John McCallbc077cf2010-02-08 23:07:23 +00003915 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003916 CXXConversionDecl *Specialization = 0;
3917 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003918 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003919 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003920 CandidateSet.push_back(OverloadCandidate());
3921 OverloadCandidate &Candidate = CandidateSet.back();
3922 Candidate.FoundDecl = FoundDecl;
3923 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3924 Candidate.Viable = false;
3925 Candidate.FailureKind = ovl_fail_bad_deduction;
3926 Candidate.IsSurrogate = false;
3927 Candidate.IgnoreObjectArgument = false;
3928 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3929 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003930 return;
3931 }
Mike Stump11289f42009-09-09 15:08:12 +00003932
Douglas Gregor05155d82009-08-21 23:19:43 +00003933 // Add the conversion function template specialization produced by
3934 // template argument deduction as a candidate.
3935 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003936 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003937 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003938}
3939
Douglas Gregorab7897a2008-11-19 22:57:39 +00003940/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3941/// converts the given @c Object to a function pointer via the
3942/// conversion function @c Conversion, and then attempts to call it
3943/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3944/// the type of function that we'll eventually be calling.
3945void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003946 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003947 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003948 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003949 QualType ObjectType,
3950 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003951 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003952 if (!CandidateSet.isNewCandidate(Conversion))
3953 return;
3954
Douglas Gregor27381f32009-11-23 12:27:39 +00003955 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003956 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003957
Douglas Gregorab7897a2008-11-19 22:57:39 +00003958 CandidateSet.push_back(OverloadCandidate());
3959 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003960 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003961 Candidate.Function = 0;
3962 Candidate.Surrogate = Conversion;
3963 Candidate.Viable = true;
3964 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003965 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003966 Candidate.Conversions.resize(NumArgs + 1);
3967
3968 // Determine the implicit conversion sequence for the implicit
3969 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003970 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00003971 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3972 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003973 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003974 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003975 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003976 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003977 return;
3978 }
3979
3980 // The first conversion is actually a user-defined conversion whose
3981 // first conversion is ObjectInit's standard conversion (which is
3982 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003983 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003984 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003985 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003986 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003987 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003988 = Candidate.Conversions[0].UserDefined.Before;
3989 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3990
Mike Stump11289f42009-09-09 15:08:12 +00003991 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003992 unsigned NumArgsInProto = Proto->getNumArgs();
3993
3994 // (C++ 13.3.2p2): A candidate function having fewer than m
3995 // parameters is viable only if it has an ellipsis in its parameter
3996 // list (8.3.5).
3997 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3998 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003999 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004000 return;
4001 }
4002
4003 // Function types don't have any default arguments, so just check if
4004 // we have enough arguments.
4005 if (NumArgs < NumArgsInProto) {
4006 // Not enough arguments.
4007 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004008 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004009 return;
4010 }
4011
4012 // Determine the implicit conversion sequences for each of the
4013 // arguments.
4014 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4015 if (ArgIdx < NumArgsInProto) {
4016 // (C++ 13.3.2p3): for F to be a viable function, there shall
4017 // exist for each argument an implicit conversion sequence
4018 // (13.3.3.1) that converts that argument to the corresponding
4019 // parameter of F.
4020 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004021 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004022 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004023 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004024 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004025 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004026 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004027 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004028 break;
4029 }
4030 } else {
4031 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4032 // argument for which there is no corresponding parameter is
4033 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004034 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004035 }
4036 }
4037}
4038
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004039/// \brief Add overload candidates for overloaded operators that are
4040/// member functions.
4041///
4042/// Add the overloaded operator candidates that are member functions
4043/// for the operator Op that was used in an operator expression such
4044/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4045/// CandidateSet will store the added overload candidates. (C++
4046/// [over.match.oper]).
4047void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4048 SourceLocation OpLoc,
4049 Expr **Args, unsigned NumArgs,
4050 OverloadCandidateSet& CandidateSet,
4051 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004052 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4053
4054 // C++ [over.match.oper]p3:
4055 // For a unary operator @ with an operand of a type whose
4056 // cv-unqualified version is T1, and for a binary operator @ with
4057 // a left operand of a type whose cv-unqualified version is T1 and
4058 // a right operand of a type whose cv-unqualified version is T2,
4059 // three sets of candidate functions, designated member
4060 // candidates, non-member candidates and built-in candidates, are
4061 // constructed as follows:
4062 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004063
4064 // -- If T1 is a class type, the set of member candidates is the
4065 // result of the qualified lookup of T1::operator@
4066 // (13.3.1.1.1); otherwise, the set of member candidates is
4067 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004068 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004069 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004070 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004071 return;
Mike Stump11289f42009-09-09 15:08:12 +00004072
John McCall27b18f82009-11-17 02:14:36 +00004073 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4074 LookupQualifiedName(Operators, T1Rec->getDecl());
4075 Operators.suppressDiagnostics();
4076
Mike Stump11289f42009-09-09 15:08:12 +00004077 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004078 OperEnd = Operators.end();
4079 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004080 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004081 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004082 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004083 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004084 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004085}
4086
Douglas Gregora11693b2008-11-12 17:17:38 +00004087/// AddBuiltinCandidate - Add a candidate for a built-in
4088/// operator. ResultTy and ParamTys are the result and parameter types
4089/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004090/// arguments being passed to the candidate. IsAssignmentOperator
4091/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004092/// operator. NumContextualBoolArguments is the number of arguments
4093/// (at the beginning of the argument list) that will be contextually
4094/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004095void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004096 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004097 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004098 bool IsAssignmentOperator,
4099 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004100 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004101 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004102
Douglas Gregora11693b2008-11-12 17:17:38 +00004103 // Add this candidate
4104 CandidateSet.push_back(OverloadCandidate());
4105 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004106 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004107 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004108 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004109 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004110 Candidate.BuiltinTypes.ResultTy = ResultTy;
4111 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4112 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4113
4114 // Determine the implicit conversion sequences for each of the
4115 // arguments.
4116 Candidate.Viable = true;
4117 Candidate.Conversions.resize(NumArgs);
4118 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004119 // C++ [over.match.oper]p4:
4120 // For the built-in assignment operators, conversions of the
4121 // left operand are restricted as follows:
4122 // -- no temporaries are introduced to hold the left operand, and
4123 // -- no user-defined conversions are applied to the left
4124 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004125 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004126 //
4127 // We block these conversions by turning off user-defined
4128 // conversions, since that is the only way that initialization of
4129 // a reference to a non-class type can occur from something that
4130 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004131 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004132 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004133 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004134 Candidate.Conversions[ArgIdx]
4135 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004136 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004137 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004138 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004139 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004140 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004141 }
John McCall0d1da222010-01-12 00:44:57 +00004142 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004144 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004145 break;
4146 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004147 }
4148}
4149
4150/// BuiltinCandidateTypeSet - A set of types that will be used for the
4151/// candidate operator functions for built-in operators (C++
4152/// [over.built]). The types are separated into pointer types and
4153/// enumeration types.
4154class BuiltinCandidateTypeSet {
4155 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004156 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004157
4158 /// PointerTypes - The set of pointer types that will be used in the
4159 /// built-in candidates.
4160 TypeSet PointerTypes;
4161
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004162 /// MemberPointerTypes - The set of member pointer types that will be
4163 /// used in the built-in candidates.
4164 TypeSet MemberPointerTypes;
4165
Douglas Gregora11693b2008-11-12 17:17:38 +00004166 /// EnumerationTypes - The set of enumeration types that will be
4167 /// used in the built-in candidates.
4168 TypeSet EnumerationTypes;
4169
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004170 /// \brief The set of vector types that will be used in the built-in
4171 /// candidates.
4172 TypeSet VectorTypes;
4173
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004174 /// Sema - The semantic analysis instance where we are building the
4175 /// candidate type set.
4176 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004177
Douglas Gregora11693b2008-11-12 17:17:38 +00004178 /// Context - The AST context in which we will build the type sets.
4179 ASTContext &Context;
4180
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004181 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4182 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004183 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004184
4185public:
4186 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004187 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004188
Mike Stump11289f42009-09-09 15:08:12 +00004189 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004190 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004191
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004192 void AddTypesConvertedFrom(QualType Ty,
4193 SourceLocation Loc,
4194 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004195 bool AllowExplicitConversions,
4196 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004197
4198 /// pointer_begin - First pointer type found;
4199 iterator pointer_begin() { return PointerTypes.begin(); }
4200
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004201 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004202 iterator pointer_end() { return PointerTypes.end(); }
4203
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004204 /// member_pointer_begin - First member pointer type found;
4205 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4206
4207 /// member_pointer_end - Past the last member pointer type found;
4208 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4209
Douglas Gregora11693b2008-11-12 17:17:38 +00004210 /// enumeration_begin - First enumeration type found;
4211 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4212
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004213 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004214 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004215
4216 iterator vector_begin() { return VectorTypes.begin(); }
4217 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004218};
4219
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004220/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004221/// the set of pointer types along with any more-qualified variants of
4222/// that type. For example, if @p Ty is "int const *", this routine
4223/// will add "int const *", "int const volatile *", "int const
4224/// restrict *", and "int const volatile restrict *" to the set of
4225/// pointer types. Returns true if the add of @p Ty itself succeeded,
4226/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004227///
4228/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004229bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004230BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4231 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004232
Douglas Gregora11693b2008-11-12 17:17:38 +00004233 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004234 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004235 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004236
4237 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004238 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004239 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004240 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004241 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004242 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004243 buildObjCPtr = true;
4244 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004245 else
4246 assert(false && "type was not a pointer type!");
4247 }
4248 else
4249 PointeeTy = PointerTy->getPointeeType();
4250
Sebastian Redl4990a632009-11-18 20:39:26 +00004251 // Don't add qualified variants of arrays. For one, they're not allowed
4252 // (the qualifier would sink to the element type), and for another, the
4253 // only overload situation where it matters is subscript or pointer +- int,
4254 // and those shouldn't have qualifier variants anyway.
4255 if (PointeeTy->isArrayType())
4256 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004257 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004258 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004259 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004260 bool hasVolatile = VisibleQuals.hasVolatile();
4261 bool hasRestrict = VisibleQuals.hasRestrict();
4262
John McCall8ccfcb52009-09-24 19:53:00 +00004263 // Iterate through all strict supersets of BaseCVR.
4264 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4265 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004266 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4267 // in the types.
4268 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4269 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004270 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004271 if (!buildObjCPtr)
4272 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4273 else
4274 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004275 }
4276
4277 return true;
4278}
4279
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004280/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4281/// to the set of pointer types along with any more-qualified variants of
4282/// that type. For example, if @p Ty is "int const *", this routine
4283/// will add "int const *", "int const volatile *", "int const
4284/// restrict *", and "int const volatile restrict *" to the set of
4285/// pointer types. Returns true if the add of @p Ty itself succeeded,
4286/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004287///
4288/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004289bool
4290BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4291 QualType Ty) {
4292 // Insert this type.
4293 if (!MemberPointerTypes.insert(Ty))
4294 return false;
4295
John McCall8ccfcb52009-09-24 19:53:00 +00004296 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4297 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004298
John McCall8ccfcb52009-09-24 19:53:00 +00004299 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004300 // Don't add qualified variants of arrays. For one, they're not allowed
4301 // (the qualifier would sink to the element type), and for another, the
4302 // only overload situation where it matters is subscript or pointer +- int,
4303 // and those shouldn't have qualifier variants anyway.
4304 if (PointeeTy->isArrayType())
4305 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004306 const Type *ClassTy = PointerTy->getClass();
4307
4308 // Iterate through all strict supersets of the pointee type's CVR
4309 // qualifiers.
4310 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4311 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4312 if ((CVR | BaseCVR) != CVR) continue;
4313
4314 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4315 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004316 }
4317
4318 return true;
4319}
4320
Douglas Gregora11693b2008-11-12 17:17:38 +00004321/// AddTypesConvertedFrom - Add each of the types to which the type @p
4322/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004323/// primarily interested in pointer types and enumeration types. We also
4324/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004325/// AllowUserConversions is true if we should look at the conversion
4326/// functions of a class type, and AllowExplicitConversions if we
4327/// should also include the explicit conversion functions of a class
4328/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004329void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004330BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004331 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004332 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004333 bool AllowExplicitConversions,
4334 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004335 // Only deal with canonical types.
4336 Ty = Context.getCanonicalType(Ty);
4337
4338 // Look through reference types; they aren't part of the type of an
4339 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004340 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004341 Ty = RefTy->getPointeeType();
4342
4343 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004344 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004345
Sebastian Redl65ae2002009-11-05 16:36:20 +00004346 // If we're dealing with an array type, decay to the pointer.
4347 if (Ty->isArrayType())
4348 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004349 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4350 PointerTypes.insert(Ty);
4351 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004352 // Insert our type, and its more-qualified variants, into the set
4353 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004354 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004355 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004356 } else if (Ty->isMemberPointerType()) {
4357 // Member pointers are far easier, since the pointee can't be converted.
4358 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4359 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004360 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004361 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004362 } else if (Ty->isVectorType()) {
4363 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004364 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004365 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004366 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004367 // No conversion functions in incomplete types.
4368 return;
4369 }
Mike Stump11289f42009-09-09 15:08:12 +00004370
Douglas Gregora11693b2008-11-12 17:17:38 +00004371 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004372 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004373 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004374 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004375 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004376 NamedDecl *D = I.getDecl();
4377 if (isa<UsingShadowDecl>(D))
4378 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004379
Mike Stump11289f42009-09-09 15:08:12 +00004380 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004381 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004382 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004383 continue;
4384
John McCallda4458e2010-03-31 01:36:47 +00004385 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004386 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004387 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004388 VisibleQuals);
4389 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004390 }
4391 }
4392 }
4393}
4394
Douglas Gregor84605ae2009-08-24 13:43:27 +00004395/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4396/// the volatile- and non-volatile-qualified assignment operators for the
4397/// given type to the candidate set.
4398static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4399 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004400 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004401 unsigned NumArgs,
4402 OverloadCandidateSet &CandidateSet) {
4403 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004404
Douglas Gregor84605ae2009-08-24 13:43:27 +00004405 // T& operator=(T&, T)
4406 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4407 ParamTypes[1] = T;
4408 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4409 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004410
Douglas Gregor84605ae2009-08-24 13:43:27 +00004411 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4412 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004413 ParamTypes[0]
4414 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004415 ParamTypes[1] = T;
4416 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004417 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004418 }
4419}
Mike Stump11289f42009-09-09 15:08:12 +00004420
Sebastian Redl1054fae2009-10-25 17:03:50 +00004421/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4422/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004423static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4424 Qualifiers VRQuals;
4425 const RecordType *TyRec;
4426 if (const MemberPointerType *RHSMPType =
4427 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004428 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004429 else
4430 TyRec = ArgExpr->getType()->getAs<RecordType>();
4431 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004432 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004433 VRQuals.addVolatile();
4434 VRQuals.addRestrict();
4435 return VRQuals;
4436 }
4437
4438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004439 if (!ClassDecl->hasDefinition())
4440 return VRQuals;
4441
John McCallad371252010-01-20 00:46:10 +00004442 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004443 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004444
John McCallad371252010-01-20 00:46:10 +00004445 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004446 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004447 NamedDecl *D = I.getDecl();
4448 if (isa<UsingShadowDecl>(D))
4449 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4450 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004451 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4452 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4453 CanTy = ResTypeRef->getPointeeType();
4454 // Need to go down the pointer/mempointer chain and add qualifiers
4455 // as see them.
4456 bool done = false;
4457 while (!done) {
4458 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4459 CanTy = ResTypePtr->getPointeeType();
4460 else if (const MemberPointerType *ResTypeMPtr =
4461 CanTy->getAs<MemberPointerType>())
4462 CanTy = ResTypeMPtr->getPointeeType();
4463 else
4464 done = true;
4465 if (CanTy.isVolatileQualified())
4466 VRQuals.addVolatile();
4467 if (CanTy.isRestrictQualified())
4468 VRQuals.addRestrict();
4469 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4470 return VRQuals;
4471 }
4472 }
4473 }
4474 return VRQuals;
4475}
4476
Douglas Gregord08452f2008-11-19 15:42:04 +00004477/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4478/// operator overloads to the candidate set (C++ [over.built]), based
4479/// on the operator @p Op and the arguments given. For example, if the
4480/// operator is a binary '+', this routine might add "int
4481/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004482void
Mike Stump11289f42009-09-09 15:08:12 +00004483Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004484 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004485 Expr **Args, unsigned NumArgs,
4486 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004487 // The set of "promoted arithmetic types", which are the arithmetic
4488 // types are that preserved by promotion (C++ [over.built]p2). Note
4489 // that the first few of these types are the promoted integral
4490 // types; these types need to be first.
4491 // FIXME: What about complex?
4492 const unsigned FirstIntegralType = 0;
4493 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004494 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004495 LastPromotedIntegralType = 13;
4496 const unsigned FirstPromotedArithmeticType = 7,
4497 LastPromotedArithmeticType = 16;
4498 const unsigned NumArithmeticTypes = 16;
4499 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004500 Context.BoolTy, Context.CharTy, Context.WCharTy,
4501// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004502 Context.SignedCharTy, Context.ShortTy,
4503 Context.UnsignedCharTy, Context.UnsignedShortTy,
4504 Context.IntTy, Context.LongTy, Context.LongLongTy,
4505 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4506 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4507 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004508 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4509 "Invalid first promoted integral type");
4510 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4511 == Context.UnsignedLongLongTy &&
4512 "Invalid last promoted integral type");
4513 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4514 "Invalid first promoted arithmetic type");
4515 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4516 == Context.LongDoubleTy &&
4517 "Invalid last promoted arithmetic type");
4518
Douglas Gregora11693b2008-11-12 17:17:38 +00004519 // Find all of the types that the arguments can convert to, but only
4520 // if the operator we're looking at has built-in operator candidates
4521 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004522 Qualifiers VisibleTypeConversionsQuals;
4523 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004524 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4525 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4526
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004527 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004528 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4529 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4530 OpLoc,
4531 true,
4532 (Op == OO_Exclaim ||
4533 Op == OO_AmpAmp ||
4534 Op == OO_PipePipe),
4535 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004536
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004537 // C++ [over.built]p1:
4538 // If there is a user-written candidate with the same name and parameter
4539 // types as a built-in candidate operator function, the built-in operator
4540 // function is hidden and is not included in the set of candidate functions.
4541 //
4542 // The text is actually in a note, but if we don't implement it then we end
4543 // up with ambiguities when the user provides an overloaded operator for
4544 // an enumeration type. Note that only enumeration types have this problem,
4545 // so we track which enumeration types we've seen operators for.
4546 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4547 UserDefinedBinaryOperators;
4548
4549 if (CandidateTypes.enumeration_begin() != CandidateTypes.enumeration_end()) {
4550 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4551 CEnd = CandidateSet.end();
4552 C != CEnd; ++C) {
4553 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4554 continue;
4555
4556 // Check if the first parameter is of enumeration type.
4557 QualType FirstParamType
4558 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4559 if (!FirstParamType->isEnumeralType())
4560 continue;
4561
4562 // Check if the second parameter is of enumeration type.
4563 QualType SecondParamType
4564 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4565 if (!SecondParamType->isEnumeralType())
4566 continue;
4567
4568 // Add this operator to the set of known user-defined operators.
4569 UserDefinedBinaryOperators.insert(
4570 std::make_pair(Context.getCanonicalType(FirstParamType),
4571 Context.getCanonicalType(SecondParamType)));
4572 }
4573 }
4574
Douglas Gregora11693b2008-11-12 17:17:38 +00004575 bool isComparison = false;
4576 switch (Op) {
4577 case OO_None:
4578 case NUM_OVERLOADED_OPERATORS:
4579 assert(false && "Expected an overloaded operator");
4580 break;
4581
Douglas Gregord08452f2008-11-19 15:42:04 +00004582 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004583 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004584 goto UnaryStar;
4585 else
4586 goto BinaryStar;
4587 break;
4588
4589 case OO_Plus: // '+' is either unary or binary
4590 if (NumArgs == 1)
4591 goto UnaryPlus;
4592 else
4593 goto BinaryPlus;
4594 break;
4595
4596 case OO_Minus: // '-' is either unary or binary
4597 if (NumArgs == 1)
4598 goto UnaryMinus;
4599 else
4600 goto BinaryMinus;
4601 break;
4602
4603 case OO_Amp: // '&' is either unary or binary
4604 if (NumArgs == 1)
4605 goto UnaryAmp;
4606 else
4607 goto BinaryAmp;
4608
4609 case OO_PlusPlus:
4610 case OO_MinusMinus:
4611 // C++ [over.built]p3:
4612 //
4613 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4614 // is either volatile or empty, there exist candidate operator
4615 // functions of the form
4616 //
4617 // VQ T& operator++(VQ T&);
4618 // T operator++(VQ T&, int);
4619 //
4620 // C++ [over.built]p4:
4621 //
4622 // For every pair (T, VQ), where T is an arithmetic type other
4623 // than bool, and VQ is either volatile or empty, there exist
4624 // candidate operator functions of the form
4625 //
4626 // VQ T& operator--(VQ T&);
4627 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004628 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004629 Arith < NumArithmeticTypes; ++Arith) {
4630 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004631 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004632 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004633
4634 // Non-volatile version.
4635 if (NumArgs == 1)
4636 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4637 else
4638 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004639 // heuristic to reduce number of builtin candidates in the set.
4640 // Add volatile version only if there are conversions to a volatile type.
4641 if (VisibleTypeConversionsQuals.hasVolatile()) {
4642 // Volatile version
4643 ParamTypes[0]
4644 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4645 if (NumArgs == 1)
4646 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4647 else
4648 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4649 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004650 }
4651
4652 // C++ [over.built]p5:
4653 //
4654 // For every pair (T, VQ), where T is a cv-qualified or
4655 // cv-unqualified object type, and VQ is either volatile or
4656 // empty, there exist candidate operator functions of the form
4657 //
4658 // T*VQ& operator++(T*VQ&);
4659 // T*VQ& operator--(T*VQ&);
4660 // T* operator++(T*VQ&, int);
4661 // T* operator--(T*VQ&, int);
4662 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4663 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4664 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004665 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004666 continue;
4667
Mike Stump11289f42009-09-09 15:08:12 +00004668 QualType ParamTypes[2] = {
4669 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004670 };
Mike Stump11289f42009-09-09 15:08:12 +00004671
Douglas Gregord08452f2008-11-19 15:42:04 +00004672 // Without volatile
4673 if (NumArgs == 1)
4674 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4675 else
4676 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4677
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004678 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4679 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004680 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004681 ParamTypes[0]
4682 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004683 if (NumArgs == 1)
4684 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4685 else
4686 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4687 }
4688 }
4689 break;
4690
4691 UnaryStar:
4692 // C++ [over.built]p6:
4693 // For every cv-qualified or cv-unqualified object type T, there
4694 // exist candidate operator functions of the form
4695 //
4696 // T& operator*(T*);
4697 //
4698 // C++ [over.built]p7:
4699 // For every function type T, there exist candidate operator
4700 // functions of the form
4701 // T& operator*(T*);
4702 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4703 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4704 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004705 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004706 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004707 &ParamTy, Args, 1, CandidateSet);
4708 }
4709 break;
4710
4711 UnaryPlus:
4712 // C++ [over.built]p8:
4713 // For every type T, there exist candidate operator functions of
4714 // the form
4715 //
4716 // T* operator+(T*);
4717 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4718 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4719 QualType ParamTy = *Ptr;
4720 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4721 }
Mike Stump11289f42009-09-09 15:08:12 +00004722
Douglas Gregord08452f2008-11-19 15:42:04 +00004723 // Fall through
4724
4725 UnaryMinus:
4726 // C++ [over.built]p9:
4727 // For every promoted arithmetic type T, there exist candidate
4728 // operator functions of the form
4729 //
4730 // T operator+(T);
4731 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004732 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004733 Arith < LastPromotedArithmeticType; ++Arith) {
4734 QualType ArithTy = ArithmeticTypes[Arith];
4735 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4736 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004737
4738 // Extension: We also add these operators for vector types.
4739 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4740 VecEnd = CandidateTypes.vector_end();
4741 Vec != VecEnd; ++Vec) {
4742 QualType VecTy = *Vec;
4743 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4744 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004745 break;
4746
4747 case OO_Tilde:
4748 // C++ [over.built]p10:
4749 // For every promoted integral type T, there exist candidate
4750 // operator functions of the form
4751 //
4752 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004753 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004754 Int < LastPromotedIntegralType; ++Int) {
4755 QualType IntTy = ArithmeticTypes[Int];
4756 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4757 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004758
4759 // Extension: We also add this operator for vector types.
4760 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4761 VecEnd = CandidateTypes.vector_end();
4762 Vec != VecEnd; ++Vec) {
4763 QualType VecTy = *Vec;
4764 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4765 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004766 break;
4767
Douglas Gregora11693b2008-11-12 17:17:38 +00004768 case OO_New:
4769 case OO_Delete:
4770 case OO_Array_New:
4771 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004772 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004773 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004774 break;
4775
4776 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004777 UnaryAmp:
4778 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004779 // C++ [over.match.oper]p3:
4780 // -- For the operator ',', the unary operator '&', or the
4781 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004782 break;
4783
Douglas Gregor84605ae2009-08-24 13:43:27 +00004784 case OO_EqualEqual:
4785 case OO_ExclaimEqual:
4786 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004787 // For every pointer to member type T, there exist candidate operator
4788 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004789 //
4790 // bool operator==(T,T);
4791 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004792 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004793 MemPtr = CandidateTypes.member_pointer_begin(),
4794 MemPtrEnd = CandidateTypes.member_pointer_end();
4795 MemPtr != MemPtrEnd;
4796 ++MemPtr) {
4797 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4798 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4799 }
Mike Stump11289f42009-09-09 15:08:12 +00004800
Douglas Gregor84605ae2009-08-24 13:43:27 +00004801 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004802
Douglas Gregora11693b2008-11-12 17:17:38 +00004803 case OO_Less:
4804 case OO_Greater:
4805 case OO_LessEqual:
4806 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004807 // C++ [over.built]p15:
4808 //
4809 // For every pointer or enumeration type T, there exist
4810 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004811 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004812 // bool operator<(T, T);
4813 // bool operator>(T, T);
4814 // bool operator<=(T, T);
4815 // bool operator>=(T, T);
4816 // bool operator==(T, T);
4817 // bool operator!=(T, T);
4818 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4819 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4820 QualType ParamTypes[2] = { *Ptr, *Ptr };
4821 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004824 = CandidateTypes.enumeration_begin();
4825 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4826 QualType ParamTypes[2] = { *Enum, *Enum };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004827 CanQualType CanonType = Context.getCanonicalType(*Enum);
4828 if (!UserDefinedBinaryOperators.count(
4829 std::make_pair(CanonType, CanonType)))
4830 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregora11693b2008-11-12 17:17:38 +00004831 }
4832
4833 // Fall through.
4834 isComparison = true;
4835
Douglas Gregord08452f2008-11-19 15:42:04 +00004836 BinaryPlus:
4837 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004838 if (!isComparison) {
4839 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4840
4841 // C++ [over.built]p13:
4842 //
4843 // For every cv-qualified or cv-unqualified object type T
4844 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004845 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004846 // T* operator+(T*, ptrdiff_t);
4847 // T& operator[](T*, ptrdiff_t); [BELOW]
4848 // T* operator-(T*, ptrdiff_t);
4849 // T* operator+(ptrdiff_t, T*);
4850 // T& operator[](ptrdiff_t, T*); [BELOW]
4851 //
4852 // C++ [over.built]p14:
4853 //
4854 // For every T, where T is a pointer to object type, there
4855 // exist candidate operator functions of the form
4856 //
4857 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004858 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004859 = CandidateTypes.pointer_begin();
4860 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4861 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4862
4863 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4864 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4865
4866 if (Op == OO_Plus) {
4867 // T* operator+(ptrdiff_t, T*);
4868 ParamTypes[0] = ParamTypes[1];
4869 ParamTypes[1] = *Ptr;
4870 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4871 } else {
4872 // ptrdiff_t operator-(T, T);
4873 ParamTypes[1] = *Ptr;
4874 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4875 Args, 2, CandidateSet);
4876 }
4877 }
4878 }
4879 // Fall through
4880
Douglas Gregora11693b2008-11-12 17:17:38 +00004881 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004882 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004883 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004884 // C++ [over.built]p12:
4885 //
4886 // For every pair of promoted arithmetic types L and R, there
4887 // exist candidate operator functions of the form
4888 //
4889 // LR operator*(L, R);
4890 // LR operator/(L, R);
4891 // LR operator+(L, R);
4892 // LR operator-(L, R);
4893 // bool operator<(L, R);
4894 // bool operator>(L, R);
4895 // bool operator<=(L, R);
4896 // bool operator>=(L, R);
4897 // bool operator==(L, R);
4898 // bool operator!=(L, R);
4899 //
4900 // where LR is the result of the usual arithmetic conversions
4901 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004902 //
4903 // C++ [over.built]p24:
4904 //
4905 // For every pair of promoted arithmetic types L and R, there exist
4906 // candidate operator functions of the form
4907 //
4908 // LR operator?(bool, L, R);
4909 //
4910 // where LR is the result of the usual arithmetic conversions
4911 // between types L and R.
4912 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004913 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004914 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004915 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004916 Right < LastPromotedArithmeticType; ++Right) {
4917 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004918 QualType Result
4919 = isComparison
4920 ? Context.BoolTy
4921 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004922 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4923 }
4924 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004925
4926 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4927 // conditional operator for vector types.
4928 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4929 Vec1End = CandidateTypes.vector_end();
4930 Vec1 != Vec1End; ++Vec1)
4931 for (BuiltinCandidateTypeSet::iterator
4932 Vec2 = CandidateTypes.vector_begin(),
4933 Vec2End = CandidateTypes.vector_end();
4934 Vec2 != Vec2End; ++Vec2) {
4935 QualType LandR[2] = { *Vec1, *Vec2 };
4936 QualType Result;
4937 if (isComparison)
4938 Result = Context.BoolTy;
4939 else {
4940 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4941 Result = *Vec1;
4942 else
4943 Result = *Vec2;
4944 }
4945
4946 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4947 }
4948
Douglas Gregora11693b2008-11-12 17:17:38 +00004949 break;
4950
4951 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004952 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004953 case OO_Caret:
4954 case OO_Pipe:
4955 case OO_LessLess:
4956 case OO_GreaterGreater:
4957 // C++ [over.built]p17:
4958 //
4959 // For every pair of promoted integral types L and R, there
4960 // exist candidate operator functions of the form
4961 //
4962 // LR operator%(L, R);
4963 // LR operator&(L, R);
4964 // LR operator^(L, R);
4965 // LR operator|(L, R);
4966 // L operator<<(L, R);
4967 // L operator>>(L, R);
4968 //
4969 // where LR is the result of the usual arithmetic conversions
4970 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004971 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004972 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004973 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004974 Right < LastPromotedIntegralType; ++Right) {
4975 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4976 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4977 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004978 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004979 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4980 }
4981 }
4982 break;
4983
4984 case OO_Equal:
4985 // C++ [over.built]p20:
4986 //
4987 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004988 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004989 // empty, there exist candidate operator functions of the form
4990 //
4991 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004992 for (BuiltinCandidateTypeSet::iterator
4993 Enum = CandidateTypes.enumeration_begin(),
4994 EnumEnd = CandidateTypes.enumeration_end();
4995 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004996 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004997 CandidateSet);
4998 for (BuiltinCandidateTypeSet::iterator
4999 MemPtr = CandidateTypes.member_pointer_begin(),
5000 MemPtrEnd = CandidateTypes.member_pointer_end();
5001 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00005002 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005003 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005004
5005 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005006
5007 case OO_PlusEqual:
5008 case OO_MinusEqual:
5009 // C++ [over.built]p19:
5010 //
5011 // For every pair (T, VQ), where T is any type and VQ is either
5012 // volatile or empty, there exist candidate operator functions
5013 // of the form
5014 //
5015 // T*VQ& operator=(T*VQ&, T*);
5016 //
5017 // C++ [over.built]p21:
5018 //
5019 // For every pair (T, VQ), where T is a cv-qualified or
5020 // cv-unqualified object type and VQ is either volatile or
5021 // empty, there exist candidate operator functions of the form
5022 //
5023 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5024 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5025 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5026 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5027 QualType ParamTypes[2];
5028 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5029
5030 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005031 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005032 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5033 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005034
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005035 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5036 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005037 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005038 ParamTypes[0]
5039 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005040 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5041 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005042 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005043 }
5044 // Fall through.
5045
5046 case OO_StarEqual:
5047 case OO_SlashEqual:
5048 // C++ [over.built]p18:
5049 //
5050 // For every triple (L, VQ, R), where L is an arithmetic type,
5051 // VQ is either volatile or empty, and R is a promoted
5052 // arithmetic type, there exist candidate operator functions of
5053 // the form
5054 //
5055 // VQ L& operator=(VQ L&, R);
5056 // VQ L& operator*=(VQ L&, R);
5057 // VQ L& operator/=(VQ L&, R);
5058 // VQ L& operator+=(VQ L&, R);
5059 // VQ L& operator-=(VQ L&, R);
5060 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005061 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005062 Right < LastPromotedArithmeticType; ++Right) {
5063 QualType ParamTypes[2];
5064 ParamTypes[1] = ArithmeticTypes[Right];
5065
5066 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005067 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005068 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5069 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005070
5071 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005072 if (VisibleTypeConversionsQuals.hasVolatile()) {
5073 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5074 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5075 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5076 /*IsAssigmentOperator=*/Op == OO_Equal);
5077 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005078 }
5079 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005080
5081 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5082 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
5083 Vec1End = CandidateTypes.vector_end();
5084 Vec1 != Vec1End; ++Vec1)
5085 for (BuiltinCandidateTypeSet::iterator
5086 Vec2 = CandidateTypes.vector_begin(),
5087 Vec2End = CandidateTypes.vector_end();
5088 Vec2 != Vec2End; ++Vec2) {
5089 QualType ParamTypes[2];
5090 ParamTypes[1] = *Vec2;
5091 // Add this built-in operator as a candidate (VQ is empty).
5092 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5093 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5094 /*IsAssigmentOperator=*/Op == OO_Equal);
5095
5096 // Add this built-in operator as a candidate (VQ is 'volatile').
5097 if (VisibleTypeConversionsQuals.hasVolatile()) {
5098 ParamTypes[0] = Context.getVolatileType(*Vec1);
5099 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5100 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5101 /*IsAssigmentOperator=*/Op == OO_Equal);
5102 }
5103 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005104 break;
5105
5106 case OO_PercentEqual:
5107 case OO_LessLessEqual:
5108 case OO_GreaterGreaterEqual:
5109 case OO_AmpEqual:
5110 case OO_CaretEqual:
5111 case OO_PipeEqual:
5112 // C++ [over.built]p22:
5113 //
5114 // For every triple (L, VQ, R), where L is an integral type, VQ
5115 // is either volatile or empty, and R is a promoted integral
5116 // type, there exist candidate operator functions of the form
5117 //
5118 // VQ L& operator%=(VQ L&, R);
5119 // VQ L& operator<<=(VQ L&, R);
5120 // VQ L& operator>>=(VQ L&, R);
5121 // VQ L& operator&=(VQ L&, R);
5122 // VQ L& operator^=(VQ L&, R);
5123 // VQ L& operator|=(VQ L&, R);
5124 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005125 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005126 Right < LastPromotedIntegralType; ++Right) {
5127 QualType ParamTypes[2];
5128 ParamTypes[1] = ArithmeticTypes[Right];
5129
5130 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005131 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005132 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005133 if (VisibleTypeConversionsQuals.hasVolatile()) {
5134 // Add this built-in operator as a candidate (VQ is 'volatile').
5135 ParamTypes[0] = ArithmeticTypes[Left];
5136 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5137 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5138 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5139 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005140 }
5141 }
5142 break;
5143
Douglas Gregord08452f2008-11-19 15:42:04 +00005144 case OO_Exclaim: {
5145 // C++ [over.operator]p23:
5146 //
5147 // There also exist candidate operator functions of the form
5148 //
Mike Stump11289f42009-09-09 15:08:12 +00005149 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005150 // bool operator&&(bool, bool); [BELOW]
5151 // bool operator||(bool, bool); [BELOW]
5152 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005153 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5154 /*IsAssignmentOperator=*/false,
5155 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005156 break;
5157 }
5158
Douglas Gregora11693b2008-11-12 17:17:38 +00005159 case OO_AmpAmp:
5160 case OO_PipePipe: {
5161 // C++ [over.operator]p23:
5162 //
5163 // There also exist candidate operator functions of the form
5164 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005165 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005166 // bool operator&&(bool, bool);
5167 // bool operator||(bool, bool);
5168 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005169 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5170 /*IsAssignmentOperator=*/false,
5171 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005172 break;
5173 }
5174
5175 case OO_Subscript:
5176 // C++ [over.built]p13:
5177 //
5178 // For every cv-qualified or cv-unqualified object type T there
5179 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005180 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005181 // T* operator+(T*, ptrdiff_t); [ABOVE]
5182 // T& operator[](T*, ptrdiff_t);
5183 // T* operator-(T*, ptrdiff_t); [ABOVE]
5184 // T* operator+(ptrdiff_t, T*); [ABOVE]
5185 // T& operator[](ptrdiff_t, T*);
5186 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5187 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5188 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005189 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005190 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005191
5192 // T& operator[](T*, ptrdiff_t)
5193 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5194
5195 // T& operator[](ptrdiff_t, T*);
5196 ParamTypes[0] = ParamTypes[1];
5197 ParamTypes[1] = *Ptr;
5198 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005199 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005200 break;
5201
5202 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005203 // C++ [over.built]p11:
5204 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5205 // C1 is the same type as C2 or is a derived class of C2, T is an object
5206 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5207 // there exist candidate operator functions of the form
5208 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5209 // where CV12 is the union of CV1 and CV2.
5210 {
5211 for (BuiltinCandidateTypeSet::iterator Ptr =
5212 CandidateTypes.pointer_begin();
5213 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5214 QualType C1Ty = (*Ptr);
5215 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005216 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005217 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5218 if (!isa<RecordType>(C1))
5219 continue;
5220 // heuristic to reduce number of builtin candidates in the set.
5221 // Add volatile/restrict version only if there are conversions to a
5222 // volatile/restrict type.
5223 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5224 continue;
5225 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5226 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005227 for (BuiltinCandidateTypeSet::iterator
5228 MemPtr = CandidateTypes.member_pointer_begin(),
5229 MemPtrEnd = CandidateTypes.member_pointer_end();
5230 MemPtr != MemPtrEnd; ++MemPtr) {
5231 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5232 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005233 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005234 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5235 break;
5236 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5237 // build CV12 T&
5238 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005239 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5240 T.isVolatileQualified())
5241 continue;
5242 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5243 T.isRestrictQualified())
5244 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005245 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005246 QualType ResultTy = Context.getLValueReferenceType(T);
5247 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5248 }
5249 }
5250 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005251 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005252
5253 case OO_Conditional:
5254 // Note that we don't consider the first argument, since it has been
5255 // contextually converted to bool long ago. The candidates below are
5256 // therefore added as binary.
5257 //
5258 // C++ [over.built]p24:
5259 // For every type T, where T is a pointer or pointer-to-member type,
5260 // there exist candidate operator functions of the form
5261 //
5262 // T operator?(bool, T, T);
5263 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005264 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5265 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5266 QualType ParamTypes[2] = { *Ptr, *Ptr };
5267 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5268 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005269 for (BuiltinCandidateTypeSet::iterator Ptr =
5270 CandidateTypes.member_pointer_begin(),
5271 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5272 QualType ParamTypes[2] = { *Ptr, *Ptr };
5273 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5274 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005275 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005276 }
5277}
5278
Douglas Gregore254f902009-02-04 00:32:51 +00005279/// \brief Add function candidates found via argument-dependent lookup
5280/// to the set of overloading candidates.
5281///
5282/// This routine performs argument-dependent name lookup based on the
5283/// given function name (which may also be an operator name) and adds
5284/// all of the overload candidates found by ADL to the overload
5285/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005286void
Douglas Gregore254f902009-02-04 00:32:51 +00005287Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005288 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005289 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005290 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005291 OverloadCandidateSet& CandidateSet,
5292 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005293 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005294
John McCall91f61fc2010-01-26 06:04:06 +00005295 // FIXME: This approach for uniquing ADL results (and removing
5296 // redundant candidates from the set) relies on pointer-equality,
5297 // which means we need to key off the canonical decl. However,
5298 // always going back to the canonical decl might not get us the
5299 // right set of default arguments. What default arguments are
5300 // we supposed to consider on ADL candidates, anyway?
5301
Douglas Gregorcabea402009-09-22 15:41:20 +00005302 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005303 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005304
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005305 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005306 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5307 CandEnd = CandidateSet.end();
5308 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005309 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005310 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005311 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005312 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005313 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005314
5315 // For each of the ADL candidates we found, add it to the overload
5316 // set.
John McCall8fe68082010-01-26 07:16:45 +00005317 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005318 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005319 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005320 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005321 continue;
5322
John McCalla0296f72010-03-19 07:35:19 +00005323 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005324 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005325 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005326 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005327 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005328 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005329 }
Douglas Gregore254f902009-02-04 00:32:51 +00005330}
5331
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005332/// isBetterOverloadCandidate - Determines whether the first overload
5333/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005334bool
John McCall5c32be02010-08-24 20:38:10 +00005335isBetterOverloadCandidate(Sema &S,
5336 const OverloadCandidate& Cand1,
5337 const OverloadCandidate& Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005338 SourceLocation Loc,
5339 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005340 // Define viable functions to be better candidates than non-viable
5341 // functions.
5342 if (!Cand2.Viable)
5343 return Cand1.Viable;
5344 else if (!Cand1.Viable)
5345 return false;
5346
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005347 // C++ [over.match.best]p1:
5348 //
5349 // -- if F is a static member function, ICS1(F) is defined such
5350 // that ICS1(F) is neither better nor worse than ICS1(G) for
5351 // any function G, and, symmetrically, ICS1(G) is neither
5352 // better nor worse than ICS1(F).
5353 unsigned StartArg = 0;
5354 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5355 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005356
Douglas Gregord3cb3562009-07-07 23:38:56 +00005357 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005358 // A viable function F1 is defined to be a better function than another
5359 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005360 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005361 unsigned NumArgs = Cand1.Conversions.size();
5362 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5363 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005364 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005365 switch (CompareImplicitConversionSequences(S,
5366 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005367 Cand2.Conversions[ArgIdx])) {
5368 case ImplicitConversionSequence::Better:
5369 // Cand1 has a better conversion sequence.
5370 HasBetterConversion = true;
5371 break;
5372
5373 case ImplicitConversionSequence::Worse:
5374 // Cand1 can't be better than Cand2.
5375 return false;
5376
5377 case ImplicitConversionSequence::Indistinguishable:
5378 // Do nothing.
5379 break;
5380 }
5381 }
5382
Mike Stump11289f42009-09-09 15:08:12 +00005383 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005384 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005385 if (HasBetterConversion)
5386 return true;
5387
Mike Stump11289f42009-09-09 15:08:12 +00005388 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005389 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005390 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005391 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5392 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005393
5394 // -- F1 and F2 are function template specializations, and the function
5395 // template for F1 is more specialized than the template for F2
5396 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005397 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005398 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5399 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005400 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005401 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5402 Cand2.Function->getPrimaryTemplate(),
5403 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005404 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5405 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005406 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005407
Douglas Gregora1f013e2008-11-07 22:36:19 +00005408 // -- the context is an initialization by user-defined conversion
5409 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5410 // from the return type of F1 to the destination type (i.e.,
5411 // the type of the entity being initialized) is a better
5412 // conversion sequence than the standard conversion sequence
5413 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005414 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005415 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005416 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005417 switch (CompareStandardConversionSequences(S,
5418 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005419 Cand2.FinalConversion)) {
5420 case ImplicitConversionSequence::Better:
5421 // Cand1 has a better conversion sequence.
5422 return true;
5423
5424 case ImplicitConversionSequence::Worse:
5425 // Cand1 can't be better than Cand2.
5426 return false;
5427
5428 case ImplicitConversionSequence::Indistinguishable:
5429 // Do nothing
5430 break;
5431 }
5432 }
5433
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005434 return false;
5435}
5436
Mike Stump11289f42009-09-09 15:08:12 +00005437/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005438/// within an overload candidate set.
5439///
5440/// \param CandidateSet the set of candidate functions.
5441///
5442/// \param Loc the location of the function name (or operator symbol) for
5443/// which overload resolution occurs.
5444///
Mike Stump11289f42009-09-09 15:08:12 +00005445/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005446/// function, Best points to the candidate function found.
5447///
5448/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005449OverloadingResult
5450OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005451 iterator& Best,
5452 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005453 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005454 Best = end();
5455 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5456 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005457 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5458 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005459 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005460 }
5461
5462 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005463 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005464 return OR_No_Viable_Function;
5465
5466 // Make sure that this function is better than every other viable
5467 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005468 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005469 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005470 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005471 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5472 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005473 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005474 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005475 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005476 }
Mike Stump11289f42009-09-09 15:08:12 +00005477
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005478 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005479 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005480 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005481 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005482 return OR_Deleted;
5483
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005484 // C++ [basic.def.odr]p2:
5485 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005486 // when referred to from a potentially-evaluated expression. [Note: this
5487 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005488 // (clause 13), user-defined conversions (12.3.2), allocation function for
5489 // placement new (5.3.4), as well as non-default initialization (8.5).
5490 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005491 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005492
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005493 return OR_Success;
5494}
5495
John McCall53262c92010-01-12 02:15:36 +00005496namespace {
5497
5498enum OverloadCandidateKind {
5499 oc_function,
5500 oc_method,
5501 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005502 oc_function_template,
5503 oc_method_template,
5504 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005505 oc_implicit_default_constructor,
5506 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005507 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005508};
5509
John McCalle1ac8d12010-01-13 00:25:19 +00005510OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5511 FunctionDecl *Fn,
5512 std::string &Description) {
5513 bool isTemplate = false;
5514
5515 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5516 isTemplate = true;
5517 Description = S.getTemplateArgumentBindingsText(
5518 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5519 }
John McCallfd0b2f82010-01-06 09:43:14 +00005520
5521 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005522 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005523 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005524
John McCall53262c92010-01-12 02:15:36 +00005525 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5526 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005527 }
5528
5529 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5530 // This actually gets spelled 'candidate function' for now, but
5531 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005532 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005533 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005534
Douglas Gregorec3bec02010-09-27 22:37:28 +00005535 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005536 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005537 return oc_implicit_copy_assignment;
5538 }
5539
John McCalle1ac8d12010-01-13 00:25:19 +00005540 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005541}
5542
5543} // end anonymous namespace
5544
5545// Notes the location of an overload candidate.
5546void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005547 std::string FnDesc;
5548 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5549 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5550 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005551}
5552
John McCall0d1da222010-01-12 00:44:57 +00005553/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5554/// "lead" diagnostic; it will be given two arguments, the source and
5555/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005556void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5557 Sema &S,
5558 SourceLocation CaretLoc,
5559 const PartialDiagnostic &PDiag) const {
5560 S.Diag(CaretLoc, PDiag)
5561 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005562 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005563 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5564 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005565 }
John McCall12f97bc2010-01-08 04:41:39 +00005566}
5567
John McCall0d1da222010-01-12 00:44:57 +00005568namespace {
5569
John McCall6a61b522010-01-13 09:16:55 +00005570void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5571 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5572 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005573 assert(Cand->Function && "for now, candidate must be a function");
5574 FunctionDecl *Fn = Cand->Function;
5575
5576 // There's a conversion slot for the object argument if this is a
5577 // non-constructor method. Note that 'I' corresponds the
5578 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005579 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005580 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005581 if (I == 0)
5582 isObjectArgument = true;
5583 else
5584 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005585 }
5586
John McCalle1ac8d12010-01-13 00:25:19 +00005587 std::string FnDesc;
5588 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5589
John McCall6a61b522010-01-13 09:16:55 +00005590 Expr *FromExpr = Conv.Bad.FromExpr;
5591 QualType FromTy = Conv.Bad.getFromType();
5592 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005593
John McCallfb7ad0f2010-02-02 02:42:52 +00005594 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005595 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005596 Expr *E = FromExpr->IgnoreParens();
5597 if (isa<UnaryOperator>(E))
5598 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005599 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005600
5601 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5602 << (unsigned) FnKind << FnDesc
5603 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5604 << ToTy << Name << I+1;
5605 return;
5606 }
5607
John McCall6d174642010-01-23 08:10:49 +00005608 // Do some hand-waving analysis to see if the non-viability is due
5609 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005610 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5611 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5612 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5613 CToTy = RT->getPointeeType();
5614 else {
5615 // TODO: detect and diagnose the full richness of const mismatches.
5616 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5617 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5618 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5619 }
5620
5621 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5622 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5623 // It is dumb that we have to do this here.
5624 while (isa<ArrayType>(CFromTy))
5625 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5626 while (isa<ArrayType>(CToTy))
5627 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5628
5629 Qualifiers FromQs = CFromTy.getQualifiers();
5630 Qualifiers ToQs = CToTy.getQualifiers();
5631
5632 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5633 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5634 << (unsigned) FnKind << FnDesc
5635 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5636 << FromTy
5637 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5638 << (unsigned) isObjectArgument << I+1;
5639 return;
5640 }
5641
5642 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5643 assert(CVR && "unexpected qualifiers mismatch");
5644
5645 if (isObjectArgument) {
5646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5647 << (unsigned) FnKind << FnDesc
5648 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5649 << FromTy << (CVR - 1);
5650 } else {
5651 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5652 << (unsigned) FnKind << FnDesc
5653 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5654 << FromTy << (CVR - 1) << I+1;
5655 }
5656 return;
5657 }
5658
John McCall6d174642010-01-23 08:10:49 +00005659 // Diagnose references or pointers to incomplete types differently,
5660 // since it's far from impossible that the incompleteness triggered
5661 // the failure.
5662 QualType TempFromTy = FromTy.getNonReferenceType();
5663 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5664 TempFromTy = PTy->getPointeeType();
5665 if (TempFromTy->isIncompleteType()) {
5666 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5667 << (unsigned) FnKind << FnDesc
5668 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5669 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5670 return;
5671 }
5672
Douglas Gregor56f2e342010-06-30 23:01:39 +00005673 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005674 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005675 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5676 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5677 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5678 FromPtrTy->getPointeeType()) &&
5679 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5680 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5681 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5682 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005683 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005684 }
5685 } else if (const ObjCObjectPointerType *FromPtrTy
5686 = FromTy->getAs<ObjCObjectPointerType>()) {
5687 if (const ObjCObjectPointerType *ToPtrTy
5688 = ToTy->getAs<ObjCObjectPointerType>())
5689 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5690 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5691 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5692 FromPtrTy->getPointeeType()) &&
5693 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005694 BaseToDerivedConversion = 2;
5695 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5696 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5697 !FromTy->isIncompleteType() &&
5698 !ToRefTy->getPointeeType()->isIncompleteType() &&
5699 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5700 BaseToDerivedConversion = 3;
5701 }
5702
5703 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005704 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005705 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005706 << (unsigned) FnKind << FnDesc
5707 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005708 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005709 << FromTy << ToTy << I+1;
5710 return;
5711 }
5712
John McCall47000992010-01-14 03:28:57 +00005713 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5715 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005716 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005717 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005718}
5719
5720void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5721 unsigned NumFormalArgs) {
5722 // TODO: treat calls to a missing default constructor as a special case
5723
5724 FunctionDecl *Fn = Cand->Function;
5725 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5726
5727 unsigned MinParams = Fn->getMinRequiredArguments();
5728
5729 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005730 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005731 unsigned mode, modeCount;
5732 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005733 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5734 (Cand->FailureKind == ovl_fail_bad_deduction &&
5735 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005736 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5737 mode = 0; // "at least"
5738 else
5739 mode = 2; // "exactly"
5740 modeCount = MinParams;
5741 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005742 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5743 (Cand->FailureKind == ovl_fail_bad_deduction &&
5744 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005745 if (MinParams != FnTy->getNumArgs())
5746 mode = 1; // "at most"
5747 else
5748 mode = 2; // "exactly"
5749 modeCount = FnTy->getNumArgs();
5750 }
5751
5752 std::string Description;
5753 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5754
5755 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005756 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5757 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005758}
5759
John McCall8b9ed552010-02-01 18:53:26 +00005760/// Diagnose a failed template-argument deduction.
5761void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5762 Expr **Args, unsigned NumArgs) {
5763 FunctionDecl *Fn = Cand->Function; // pattern
5764
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005765 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005766 NamedDecl *ParamD;
5767 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5768 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5769 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005770 switch (Cand->DeductionFailure.Result) {
5771 case Sema::TDK_Success:
5772 llvm_unreachable("TDK_success while diagnosing bad deduction");
5773
5774 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005775 assert(ParamD && "no parameter found for incomplete deduction result");
5776 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5777 << ParamD->getDeclName();
5778 return;
5779 }
5780
John McCall42d7d192010-08-05 09:05:08 +00005781 case Sema::TDK_Underqualified: {
5782 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5783 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5784
5785 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5786
5787 // Param will have been canonicalized, but it should just be a
5788 // qualified version of ParamD, so move the qualifiers to that.
5789 QualifierCollector Qs(S.Context);
5790 Qs.strip(Param);
5791 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5792 assert(S.Context.hasSameType(Param, NonCanonParam));
5793
5794 // Arg has also been canonicalized, but there's nothing we can do
5795 // about that. It also doesn't matter as much, because it won't
5796 // have any template parameters in it (because deduction isn't
5797 // done on dependent types).
5798 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5799
5800 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5801 << ParamD->getDeclName() << Arg << NonCanonParam;
5802 return;
5803 }
5804
5805 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005806 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005807 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005808 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005809 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005810 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005811 which = 1;
5812 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005813 which = 2;
5814 }
5815
5816 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5817 << which << ParamD->getDeclName()
5818 << *Cand->DeductionFailure.getFirstArg()
5819 << *Cand->DeductionFailure.getSecondArg();
5820 return;
5821 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005822
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005823 case Sema::TDK_InvalidExplicitArguments:
5824 assert(ParamD && "no parameter found for invalid explicit arguments");
5825 if (ParamD->getDeclName())
5826 S.Diag(Fn->getLocation(),
5827 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5828 << ParamD->getDeclName();
5829 else {
5830 int index = 0;
5831 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5832 index = TTP->getIndex();
5833 else if (NonTypeTemplateParmDecl *NTTP
5834 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5835 index = NTTP->getIndex();
5836 else
5837 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5838 S.Diag(Fn->getLocation(),
5839 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5840 << (index + 1);
5841 }
5842 return;
5843
Douglas Gregor02eb4832010-05-08 18:13:28 +00005844 case Sema::TDK_TooManyArguments:
5845 case Sema::TDK_TooFewArguments:
5846 DiagnoseArityMismatch(S, Cand, NumArgs);
5847 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005848
5849 case Sema::TDK_InstantiationDepth:
5850 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5851 return;
5852
5853 case Sema::TDK_SubstitutionFailure: {
5854 std::string ArgString;
5855 if (TemplateArgumentList *Args
5856 = Cand->DeductionFailure.getTemplateArgumentList())
5857 ArgString = S.getTemplateArgumentBindingsText(
5858 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5859 *Args);
5860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5861 << ArgString;
5862 return;
5863 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005864
John McCall8b9ed552010-02-01 18:53:26 +00005865 // TODO: diagnose these individually, then kill off
5866 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005867 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005868 case Sema::TDK_FailedOverloadResolution:
5869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5870 return;
5871 }
5872}
5873
5874/// Generates a 'note' diagnostic for an overload candidate. We've
5875/// already generated a primary error at the call site.
5876///
5877/// It really does need to be a single diagnostic with its caret
5878/// pointed at the candidate declaration. Yes, this creates some
5879/// major challenges of technical writing. Yes, this makes pointing
5880/// out problems with specific arguments quite awkward. It's still
5881/// better than generating twenty screens of text for every failed
5882/// overload.
5883///
5884/// It would be great to be able to express per-candidate problems
5885/// more richly for those diagnostic clients that cared, but we'd
5886/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005887void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5888 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005889 FunctionDecl *Fn = Cand->Function;
5890
John McCall12f97bc2010-01-08 04:41:39 +00005891 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005892 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005893 std::string FnDesc;
5894 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005895
5896 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005897 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005898 return;
John McCall12f97bc2010-01-08 04:41:39 +00005899 }
5900
John McCalle1ac8d12010-01-13 00:25:19 +00005901 // We don't really have anything else to say about viable candidates.
5902 if (Cand->Viable) {
5903 S.NoteOverloadCandidate(Fn);
5904 return;
5905 }
John McCall0d1da222010-01-12 00:44:57 +00005906
John McCall6a61b522010-01-13 09:16:55 +00005907 switch (Cand->FailureKind) {
5908 case ovl_fail_too_many_arguments:
5909 case ovl_fail_too_few_arguments:
5910 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005911
John McCall6a61b522010-01-13 09:16:55 +00005912 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005913 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5914
John McCallfe796dd2010-01-23 05:17:32 +00005915 case ovl_fail_trivial_conversion:
5916 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005917 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005918 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005919
John McCall65eb8792010-02-25 01:37:24 +00005920 case ovl_fail_bad_conversion: {
5921 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5922 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005923 if (Cand->Conversions[I].isBad())
5924 return DiagnoseBadConversion(S, Cand, I);
5925
5926 // FIXME: this currently happens when we're called from SemaInit
5927 // when user-conversion overload fails. Figure out how to handle
5928 // those conditions and diagnose them well.
5929 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005930 }
John McCall65eb8792010-02-25 01:37:24 +00005931 }
John McCalld3224162010-01-08 00:58:21 +00005932}
5933
5934void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5935 // Desugar the type of the surrogate down to a function type,
5936 // retaining as many typedefs as possible while still showing
5937 // the function type (and, therefore, its parameter types).
5938 QualType FnType = Cand->Surrogate->getConversionType();
5939 bool isLValueReference = false;
5940 bool isRValueReference = false;
5941 bool isPointer = false;
5942 if (const LValueReferenceType *FnTypeRef =
5943 FnType->getAs<LValueReferenceType>()) {
5944 FnType = FnTypeRef->getPointeeType();
5945 isLValueReference = true;
5946 } else if (const RValueReferenceType *FnTypeRef =
5947 FnType->getAs<RValueReferenceType>()) {
5948 FnType = FnTypeRef->getPointeeType();
5949 isRValueReference = true;
5950 }
5951 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5952 FnType = FnTypePtr->getPointeeType();
5953 isPointer = true;
5954 }
5955 // Desugar down to a function type.
5956 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5957 // Reconstruct the pointer/reference as appropriate.
5958 if (isPointer) FnType = S.Context.getPointerType(FnType);
5959 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5960 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5961
5962 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5963 << FnType;
5964}
5965
5966void NoteBuiltinOperatorCandidate(Sema &S,
5967 const char *Opc,
5968 SourceLocation OpLoc,
5969 OverloadCandidate *Cand) {
5970 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5971 std::string TypeStr("operator");
5972 TypeStr += Opc;
5973 TypeStr += "(";
5974 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5975 if (Cand->Conversions.size() == 1) {
5976 TypeStr += ")";
5977 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5978 } else {
5979 TypeStr += ", ";
5980 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5981 TypeStr += ")";
5982 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5983 }
5984}
5985
5986void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5987 OverloadCandidate *Cand) {
5988 unsigned NoOperands = Cand->Conversions.size();
5989 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5990 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005991 if (ICS.isBad()) break; // all meaningless after first invalid
5992 if (!ICS.isAmbiguous()) continue;
5993
John McCall5c32be02010-08-24 20:38:10 +00005994 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005995 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005996 }
5997}
5998
John McCall3712d9e2010-01-15 23:32:50 +00005999SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6000 if (Cand->Function)
6001 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006002 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006003 return Cand->Surrogate->getLocation();
6004 return SourceLocation();
6005}
6006
John McCallad2587a2010-01-12 00:48:53 +00006007struct CompareOverloadCandidatesForDisplay {
6008 Sema &S;
6009 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006010
6011 bool operator()(const OverloadCandidate *L,
6012 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006013 // Fast-path this check.
6014 if (L == R) return false;
6015
John McCall12f97bc2010-01-08 04:41:39 +00006016 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006017 if (L->Viable) {
6018 if (!R->Viable) return true;
6019
6020 // TODO: introduce a tri-valued comparison for overload
6021 // candidates. Would be more worthwhile if we had a sort
6022 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006023 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6024 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006025 } else if (R->Viable)
6026 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006027
John McCall3712d9e2010-01-15 23:32:50 +00006028 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006029
John McCall3712d9e2010-01-15 23:32:50 +00006030 // Criteria by which we can sort non-viable candidates:
6031 if (!L->Viable) {
6032 // 1. Arity mismatches come after other candidates.
6033 if (L->FailureKind == ovl_fail_too_many_arguments ||
6034 L->FailureKind == ovl_fail_too_few_arguments)
6035 return false;
6036 if (R->FailureKind == ovl_fail_too_many_arguments ||
6037 R->FailureKind == ovl_fail_too_few_arguments)
6038 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006039
John McCallfe796dd2010-01-23 05:17:32 +00006040 // 2. Bad conversions come first and are ordered by the number
6041 // of bad conversions and quality of good conversions.
6042 if (L->FailureKind == ovl_fail_bad_conversion) {
6043 if (R->FailureKind != ovl_fail_bad_conversion)
6044 return true;
6045
6046 // If there's any ordering between the defined conversions...
6047 // FIXME: this might not be transitive.
6048 assert(L->Conversions.size() == R->Conversions.size());
6049
6050 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006051 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6052 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006053 switch (CompareImplicitConversionSequences(S,
6054 L->Conversions[I],
6055 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006056 case ImplicitConversionSequence::Better:
6057 leftBetter++;
6058 break;
6059
6060 case ImplicitConversionSequence::Worse:
6061 leftBetter--;
6062 break;
6063
6064 case ImplicitConversionSequence::Indistinguishable:
6065 break;
6066 }
6067 }
6068 if (leftBetter > 0) return true;
6069 if (leftBetter < 0) return false;
6070
6071 } else if (R->FailureKind == ovl_fail_bad_conversion)
6072 return false;
6073
John McCall3712d9e2010-01-15 23:32:50 +00006074 // TODO: others?
6075 }
6076
6077 // Sort everything else by location.
6078 SourceLocation LLoc = GetLocationForCandidate(L);
6079 SourceLocation RLoc = GetLocationForCandidate(R);
6080
6081 // Put candidates without locations (e.g. builtins) at the end.
6082 if (LLoc.isInvalid()) return false;
6083 if (RLoc.isInvalid()) return true;
6084
6085 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006086 }
6087};
6088
John McCallfe796dd2010-01-23 05:17:32 +00006089/// CompleteNonViableCandidate - Normally, overload resolution only
6090/// computes up to the first
6091void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6092 Expr **Args, unsigned NumArgs) {
6093 assert(!Cand->Viable);
6094
6095 // Don't do anything on failures other than bad conversion.
6096 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6097
6098 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006099 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006100 unsigned ConvCount = Cand->Conversions.size();
6101 while (true) {
6102 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6103 ConvIdx++;
6104 if (Cand->Conversions[ConvIdx - 1].isBad())
6105 break;
6106 }
6107
6108 if (ConvIdx == ConvCount)
6109 return;
6110
John McCall65eb8792010-02-25 01:37:24 +00006111 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6112 "remaining conversion is initialized?");
6113
Douglas Gregoradc7a702010-04-16 17:45:54 +00006114 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006115 // operation somehow.
6116 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006117
6118 const FunctionProtoType* Proto;
6119 unsigned ArgIdx = ConvIdx;
6120
6121 if (Cand->IsSurrogate) {
6122 QualType ConvType
6123 = Cand->Surrogate->getConversionType().getNonReferenceType();
6124 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6125 ConvType = ConvPtrType->getPointeeType();
6126 Proto = ConvType->getAs<FunctionProtoType>();
6127 ArgIdx--;
6128 } else if (Cand->Function) {
6129 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6130 if (isa<CXXMethodDecl>(Cand->Function) &&
6131 !isa<CXXConstructorDecl>(Cand->Function))
6132 ArgIdx--;
6133 } else {
6134 // Builtin binary operator with a bad first conversion.
6135 assert(ConvCount <= 3);
6136 for (; ConvIdx != ConvCount; ++ConvIdx)
6137 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006138 = TryCopyInitialization(S, Args[ConvIdx],
6139 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6140 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006141 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006142 return;
6143 }
6144
6145 // Fill in the rest of the conversions.
6146 unsigned NumArgsInProto = Proto->getNumArgs();
6147 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6148 if (ArgIdx < NumArgsInProto)
6149 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006150 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6151 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006152 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006153 else
6154 Cand->Conversions[ConvIdx].setEllipsis();
6155 }
6156}
6157
John McCalld3224162010-01-08 00:58:21 +00006158} // end anonymous namespace
6159
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006160/// PrintOverloadCandidates - When overload resolution fails, prints
6161/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006162/// set.
John McCall5c32be02010-08-24 20:38:10 +00006163void OverloadCandidateSet::NoteCandidates(Sema &S,
6164 OverloadCandidateDisplayKind OCD,
6165 Expr **Args, unsigned NumArgs,
6166 const char *Opc,
6167 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006168 // Sort the candidates by viability and position. Sorting directly would
6169 // be prohibitive, so we make a set of pointers and sort those.
6170 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006171 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6172 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006173 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006174 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006175 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006176 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006177 if (Cand->Function || Cand->IsSurrogate)
6178 Cands.push_back(Cand);
6179 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6180 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006181 }
6182 }
6183
John McCallad2587a2010-01-12 00:48:53 +00006184 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006185 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006186
John McCall0d1da222010-01-12 00:44:57 +00006187 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006188
John McCall12f97bc2010-01-08 04:41:39 +00006189 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006190 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006191 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006192 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6193 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006194
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006195 // Set an arbitrary limit on the number of candidate functions we'll spam
6196 // the user with. FIXME: This limit should depend on details of the
6197 // candidate list.
6198 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6199 break;
6200 }
6201 ++CandsShown;
6202
John McCalld3224162010-01-08 00:58:21 +00006203 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006204 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006205 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006206 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006207 else {
6208 assert(Cand->Viable &&
6209 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006210 // Generally we only see ambiguities including viable builtin
6211 // operators if overload resolution got screwed up by an
6212 // ambiguous user-defined conversion.
6213 //
6214 // FIXME: It's quite possible for different conversions to see
6215 // different ambiguities, though.
6216 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006217 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006218 ReportedAmbiguousConversions = true;
6219 }
John McCalld3224162010-01-08 00:58:21 +00006220
John McCall0d1da222010-01-12 00:44:57 +00006221 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006222 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006223 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006224 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006225
6226 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006227 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006228}
6229
John McCalla0296f72010-03-19 07:35:19 +00006230static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006231 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006232 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006233
John McCalla0296f72010-03-19 07:35:19 +00006234 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006235}
6236
Douglas Gregorcd695e52008-11-10 20:40:00 +00006237/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6238/// an overloaded function (C++ [over.over]), where @p From is an
6239/// expression with overloaded function type and @p ToType is the type
6240/// we're trying to resolve to. For example:
6241///
6242/// @code
6243/// int f(double);
6244/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006245///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006246/// int (*pfd)(double) = f; // selects f(double)
6247/// @endcode
6248///
6249/// This routine returns the resulting FunctionDecl if it could be
6250/// resolved, and NULL otherwise. When @p Complain is true, this
6251/// routine will emit diagnostics if there is an error.
6252FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006253Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006254 bool Complain,
6255 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006256 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006257 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006258 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006259 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006260 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006261 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006262 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006263 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006264 FunctionType = MemTypePtr->getPointeeType();
6265 IsMember = true;
6266 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006267
Douglas Gregorcd695e52008-11-10 20:40:00 +00006268 // C++ [over.over]p1:
6269 // [...] [Note: any redundant set of parentheses surrounding the
6270 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006271 // C++ [over.over]p1:
6272 // [...] The overloaded function name can be preceded by the &
6273 // operator.
John McCall7d460512010-08-24 23:26:21 +00006274 // However, remember whether the expression has member-pointer form:
6275 // C++ [expr.unary.op]p4:
6276 // A pointer to member is only formed when an explicit & is used
6277 // and its operand is a qualified-id not enclosed in
6278 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006279 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6280 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006281
Douglas Gregor064fdb22010-04-14 23:11:21 +00006282 // We expect a pointer or reference to function, or a function pointer.
6283 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6284 if (!FunctionType->isFunctionType()) {
6285 if (Complain)
6286 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6287 << OvlExpr->getName() << ToType;
6288
6289 return 0;
6290 }
6291
John McCall24d18942010-08-24 22:52:39 +00006292 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006293 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006294 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006295 if (!Complain) return 0;
6296
6297 // TODO: Should we condition this on whether any functions might
6298 // have matched, or is it more appropriate to do that in callers?
6299 // TODO: a fixit wouldn't hurt.
6300 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6301 << ToType << OvlExpr->getSourceRange();
6302 return 0;
6303 }
6304
6305 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6306 if (OvlExpr->hasExplicitTemplateArgs()) {
6307 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6308 ExplicitTemplateArgs = &ETABuffer;
6309 }
6310
Douglas Gregor064fdb22010-04-14 23:11:21 +00006311 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006312
Douglas Gregorcd695e52008-11-10 20:40:00 +00006313 // Look through all of the overloaded functions, searching for one
6314 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006315 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006316 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006317
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006318 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006319 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6320 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006321 // Look through any using declarations to find the underlying function.
6322 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6323
Douglas Gregorcd695e52008-11-10 20:40:00 +00006324 // C++ [over.over]p3:
6325 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006326 // targets of type "pointer-to-function" or "reference-to-function."
6327 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006328 // type "pointer-to-member-function."
6329 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006330
Mike Stump11289f42009-09-09 15:08:12 +00006331 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006332 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006333 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006334 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006335 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006336 // static when converting to member pointer.
6337 if (Method->isStatic() == IsMember)
6338 continue;
6339 } else if (IsMember)
6340 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006341
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006342 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006343 // If the name is a function template, template argument deduction is
6344 // done (14.8.2.2), and if the argument deduction succeeds, the
6345 // resulting template argument list is used to generate a single
6346 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006347 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006348 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006349 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006350 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006351 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006352 FunctionType, Specialization, Info)) {
6353 // FIXME: make a note of the failed deduction for diagnostics.
6354 (void)Result;
6355 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006356 // Template argument deduction ensures that we have an exact match.
6357 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006358 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006359 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006360 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006361 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006362 }
John McCalld14a8642009-11-21 08:51:07 +00006363
6364 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006365 }
Mike Stump11289f42009-09-09 15:08:12 +00006366
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006368 // Skip non-static functions when converting to pointer, and static
6369 // when converting to member pointer.
6370 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006371 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006372
6373 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006374 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006375 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006376 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006377 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006378
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006379 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006380 QualType ResultTy;
6381 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6382 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6383 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006384 Matches.push_back(std::make_pair(I.getPair(),
6385 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006386 FoundNonTemplateFunction = true;
6387 }
Mike Stump11289f42009-09-09 15:08:12 +00006388 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006389 }
6390
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006391 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006392 if (Matches.empty()) {
6393 if (Complain) {
6394 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6395 << OvlExpr->getName() << FunctionType;
6396 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6397 E = OvlExpr->decls_end();
6398 I != E; ++I)
6399 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6400 NoteOverloadCandidate(F);
6401 }
6402
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006403 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006404 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006405 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006406 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006407 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006408 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006409 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006410 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006411 return Result;
6412 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006413
6414 // C++ [over.over]p4:
6415 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006416 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006417 // [...] and any given function template specialization F1 is
6418 // eliminated if the set contains a second function template
6419 // specialization whose function template is more specialized
6420 // than the function template of F1 according to the partial
6421 // ordering rules of 14.5.5.2.
6422
6423 // The algorithm specified above is quadratic. We instead use a
6424 // two-pass algorithm (similar to the one used to identify the
6425 // best viable function in an overload set) that identifies the
6426 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006427
6428 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6429 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6430 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006431
6432 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006433 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006434 TPOC_Other, From->getLocStart(),
6435 PDiag(),
6436 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006437 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006438 PDiag(diag::note_ovl_candidate)
6439 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006440 if (Result == MatchesCopy.end())
6441 return 0;
6442
John McCall58cc69d2010-01-27 01:50:18 +00006443 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006444 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006445 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006446 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006447 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006448 }
Mike Stump11289f42009-09-09 15:08:12 +00006449
Douglas Gregorfae1d712009-09-26 03:56:17 +00006450 // [...] any function template specializations in the set are
6451 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006452 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006453 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006454 ++I;
6455 else {
John McCalla0296f72010-03-19 07:35:19 +00006456 Matches[I] = Matches[--N];
6457 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006458 }
6459 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006460
Mike Stump11289f42009-09-09 15:08:12 +00006461 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006462 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006463 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006464 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006465 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006466 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006467 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6468 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006469 }
Mike Stump11289f42009-09-09 15:08:12 +00006470
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006471 // FIXME: We should probably return the same thing that BestViableFunction
6472 // returns (even if we issue the diagnostics here).
6473 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006474 << Matches[0].second->getDeclName();
6475 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6476 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006477 return 0;
6478}
6479
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006480/// \brief Given an expression that refers to an overloaded function, try to
6481/// resolve that overloaded function expression down to a single function.
6482///
6483/// This routine can only resolve template-ids that refer to a single function
6484/// template, where that template-id refers to a single template whose template
6485/// arguments are either provided by the template-id or have defaults,
6486/// as described in C++0x [temp.arg.explicit]p3.
6487FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6488 // C++ [over.over]p1:
6489 // [...] [Note: any redundant set of parentheses surrounding the
6490 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006491 // C++ [over.over]p1:
6492 // [...] The overloaded function name can be preceded by the &
6493 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006494
6495 if (From->getType() != Context.OverloadTy)
6496 return 0;
6497
John McCall8d08b9b2010-08-27 09:08:28 +00006498 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006499
6500 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006501 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006502 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006503
6504 TemplateArgumentListInfo ExplicitTemplateArgs;
6505 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006506
6507 // Look through all of the overloaded functions, searching for one
6508 // whose type matches exactly.
6509 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006510 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6511 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006512 // C++0x [temp.arg.explicit]p3:
6513 // [...] In contexts where deduction is done and fails, or in contexts
6514 // where deduction is not done, if a template argument list is
6515 // specified and it, along with any default template arguments,
6516 // identifies a single function template specialization, then the
6517 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006518 FunctionTemplateDecl *FunctionTemplate
6519 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006520
6521 // C++ [over.over]p2:
6522 // If the name is a function template, template argument deduction is
6523 // done (14.8.2.2), and if the argument deduction succeeds, the
6524 // resulting template argument list is used to generate a single
6525 // function template specialization, which is added to the set of
6526 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006527 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006528 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006529 if (TemplateDeductionResult Result
6530 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6531 Specialization, Info)) {
6532 // FIXME: make a note of the failed deduction for diagnostics.
6533 (void)Result;
6534 continue;
6535 }
6536
6537 // Multiple matches; we can't resolve to a single declaration.
6538 if (Matched)
6539 return 0;
6540
6541 Matched = Specialization;
6542 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006543
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006544 return Matched;
6545}
6546
Douglas Gregorcabea402009-09-22 15:41:20 +00006547/// \brief Add a single candidate to the overload set.
6548static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006549 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006550 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006551 Expr **Args, unsigned NumArgs,
6552 OverloadCandidateSet &CandidateSet,
6553 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006554 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006555 if (isa<UsingShadowDecl>(Callee))
6556 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6557
Douglas Gregorcabea402009-09-22 15:41:20 +00006558 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006559 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006560 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006561 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006562 return;
John McCalld14a8642009-11-21 08:51:07 +00006563 }
6564
6565 if (FunctionTemplateDecl *FuncTemplate
6566 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006567 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6568 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006569 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006570 return;
6571 }
6572
6573 assert(false && "unhandled case in overloaded call candidate");
6574
6575 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006576}
6577
6578/// \brief Add the overload candidates named by callee and/or found by argument
6579/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006580void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006581 Expr **Args, unsigned NumArgs,
6582 OverloadCandidateSet &CandidateSet,
6583 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006584
6585#ifndef NDEBUG
6586 // Verify that ArgumentDependentLookup is consistent with the rules
6587 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006588 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006589 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6590 // and let Y be the lookup set produced by argument dependent
6591 // lookup (defined as follows). If X contains
6592 //
6593 // -- a declaration of a class member, or
6594 //
6595 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006596 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006597 //
6598 // -- a declaration that is neither a function or a function
6599 // template
6600 //
6601 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006602
John McCall57500772009-12-16 12:17:52 +00006603 if (ULE->requiresADL()) {
6604 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6605 E = ULE->decls_end(); I != E; ++I) {
6606 assert(!(*I)->getDeclContext()->isRecord());
6607 assert(isa<UsingShadowDecl>(*I) ||
6608 !(*I)->getDeclContext()->isFunctionOrMethod());
6609 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006610 }
6611 }
6612#endif
6613
John McCall57500772009-12-16 12:17:52 +00006614 // It would be nice to avoid this copy.
6615 TemplateArgumentListInfo TABuffer;
6616 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6617 if (ULE->hasExplicitTemplateArgs()) {
6618 ULE->copyTemplateArgumentsInto(TABuffer);
6619 ExplicitTemplateArgs = &TABuffer;
6620 }
6621
6622 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6623 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006624 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006625 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006626 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006627
John McCall57500772009-12-16 12:17:52 +00006628 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006629 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6630 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006631 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006632 CandidateSet,
6633 PartialOverloading);
6634}
John McCalld681c392009-12-16 08:11:27 +00006635
6636/// Attempts to recover from a call where no functions were found.
6637///
6638/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006639static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006640BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006641 UnresolvedLookupExpr *ULE,
6642 SourceLocation LParenLoc,
6643 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006644 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006645
6646 CXXScopeSpec SS;
6647 if (ULE->getQualifier()) {
6648 SS.setScopeRep(ULE->getQualifier());
6649 SS.setRange(ULE->getQualifierRange());
6650 }
6651
John McCall57500772009-12-16 12:17:52 +00006652 TemplateArgumentListInfo TABuffer;
6653 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6654 if (ULE->hasExplicitTemplateArgs()) {
6655 ULE->copyTemplateArgumentsInto(TABuffer);
6656 ExplicitTemplateArgs = &TABuffer;
6657 }
6658
John McCalld681c392009-12-16 08:11:27 +00006659 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6660 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006661 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006662 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006663
John McCall57500772009-12-16 12:17:52 +00006664 assert(!R.empty() && "lookup results empty despite recovery");
6665
6666 // Build an implicit member call if appropriate. Just drop the
6667 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006668 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006669 if ((*R.begin())->isCXXClassMember())
6670 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6671 else if (ExplicitTemplateArgs)
6672 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6673 else
6674 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6675
6676 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006677 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006678
6679 // This shouldn't cause an infinite loop because we're giving it
6680 // an expression with non-empty lookup results, which should never
6681 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006682 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006683 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006684}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006685
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006686/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006687/// (which eventually refers to the declaration Func) and the call
6688/// arguments Args/NumArgs, attempt to resolve the function call down
6689/// to a specific function. If overload resolution succeeds, returns
6690/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006691/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006692/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006693ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006694Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006695 SourceLocation LParenLoc,
6696 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006697 SourceLocation RParenLoc) {
6698#ifndef NDEBUG
6699 if (ULE->requiresADL()) {
6700 // To do ADL, we must have found an unqualified name.
6701 assert(!ULE->getQualifier() && "qualified name with ADL");
6702
6703 // We don't perform ADL for implicit declarations of builtins.
6704 // Verify that this was correctly set up.
6705 FunctionDecl *F;
6706 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6707 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6708 F->getBuiltinID() && F->isImplicit())
6709 assert(0 && "performing ADL for builtin");
6710
6711 // We don't perform ADL in C.
6712 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6713 }
6714#endif
6715
John McCallbc077cf2010-02-08 23:07:23 +00006716 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006717
John McCall57500772009-12-16 12:17:52 +00006718 // Add the functions denoted by the callee to the set of candidate
6719 // functions, including those from argument-dependent lookup.
6720 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006721
6722 // If we found nothing, try to recover.
6723 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6724 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006725 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006726 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006727 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006728
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006729 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006730 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006731 case OR_Success: {
6732 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006733 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006734 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006735 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006736 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6737 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006738
6739 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006740 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006741 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006742 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006743 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006744 break;
6745
6746 case OR_Ambiguous:
6747 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006748 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006749 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006750 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006751
6752 case OR_Deleted:
6753 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6754 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006755 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006756 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006757 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006758 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006759 }
6760
Douglas Gregorb412e172010-07-25 18:17:45 +00006761 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006762 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006763}
6764
John McCall4c4c1df2010-01-26 03:27:55 +00006765static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006766 return Functions.size() > 1 ||
6767 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6768}
6769
Douglas Gregor084d8552009-03-13 23:49:33 +00006770/// \brief Create a unary operation that may resolve to an overloaded
6771/// operator.
6772///
6773/// \param OpLoc The location of the operator itself (e.g., '*').
6774///
6775/// \param OpcIn The UnaryOperator::Opcode that describes this
6776/// operator.
6777///
6778/// \param Functions The set of non-member functions that will be
6779/// considered by overload resolution. The caller needs to build this
6780/// set based on the context using, e.g.,
6781/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6782/// set should not contain any member functions; those will be added
6783/// by CreateOverloadedUnaryOp().
6784///
6785/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00006786ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00006787Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6788 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00006789 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006790 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00006791
6792 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6793 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6794 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006795 // TODO: provide better source location info.
6796 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006797
6798 Expr *Args[2] = { Input, 0 };
6799 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006800
Douglas Gregor084d8552009-03-13 23:49:33 +00006801 // For post-increment and post-decrement, add the implicit '0' as
6802 // the second argument, so that we know this is a post-increment or
6803 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00006804 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006805 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006806 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6807 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00006808 NumArgs = 2;
6809 }
6810
6811 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006812 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00006813 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00006814 Opc,
6815 Context.DependentTy,
6816 OpLoc));
6817
John McCall58cc69d2010-01-27 01:50:18 +00006818 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006819 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006820 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006821 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006822 /*ADL*/ true, IsOverloaded(Fns),
6823 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006824 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6825 &Args[0], NumArgs,
6826 Context.DependentTy,
6827 OpLoc));
6828 }
6829
6830 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006831 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006832
6833 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006834 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006835
6836 // Add operator candidates that are member functions.
6837 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6838
John McCall4c4c1df2010-01-26 03:27:55 +00006839 // Add candidates from ADL.
6840 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006841 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006842 /*ExplicitTemplateArgs*/ 0,
6843 CandidateSet);
6844
Douglas Gregor084d8552009-03-13 23:49:33 +00006845 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006846 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006847
6848 // Perform overload resolution.
6849 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006850 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006851 case OR_Success: {
6852 // We found a built-in operator or an overloaded operator.
6853 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006854
Douglas Gregor084d8552009-03-13 23:49:33 +00006855 if (FnDecl) {
6856 // We matched an overloaded operator. Build a call to that
6857 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006858
Douglas Gregor084d8552009-03-13 23:49:33 +00006859 // Convert the arguments.
6860 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006861 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006862
John McCall16df1e52010-03-30 21:47:33 +00006863 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6864 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006865 return ExprError();
6866 } else {
6867 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00006868 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00006869 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00006870 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006871 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006872 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00006873 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00006874 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006875 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00006876 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00006877 }
6878
John McCall4fa0d5f2010-05-06 18:15:07 +00006879 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6880
Douglas Gregor084d8552009-03-13 23:49:33 +00006881 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006882 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006883
Douglas Gregor084d8552009-03-13 23:49:33 +00006884 // Build the actual expression node.
6885 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6886 SourceLocation());
6887 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006888
Eli Friedman030eee42009-11-18 03:58:17 +00006889 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00006890 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006891 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00006892 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00006893
John McCallb268a282010-08-23 23:25:46 +00006894 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006895 FnDecl))
6896 return ExprError();
6897
John McCallb268a282010-08-23 23:25:46 +00006898 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00006899 } else {
6900 // We matched a built-in operator. Convert the arguments, then
6901 // break out so that we will build the appropriate built-in
6902 // operator node.
6903 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006904 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006905 return ExprError();
6906
6907 break;
6908 }
6909 }
6910
6911 case OR_No_Viable_Function:
6912 // No viable function; fall through to handling this as a
6913 // built-in operator, which will produce an error message for us.
6914 break;
6915
6916 case OR_Ambiguous:
6917 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6918 << UnaryOperator::getOpcodeStr(Opc)
6919 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006920 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6921 Args, NumArgs,
6922 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006923 return ExprError();
6924
6925 case OR_Deleted:
6926 Diag(OpLoc, diag::err_ovl_deleted_oper)
6927 << Best->Function->isDeleted()
6928 << UnaryOperator::getOpcodeStr(Opc)
6929 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006930 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006931 return ExprError();
6932 }
6933
6934 // Either we found no viable overloaded operator or we matched a
6935 // built-in operator. In either case, fall through to trying to
6936 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00006937 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006938}
6939
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006940/// \brief Create a binary operation that may resolve to an overloaded
6941/// operator.
6942///
6943/// \param OpLoc The location of the operator itself (e.g., '+').
6944///
6945/// \param OpcIn The BinaryOperator::Opcode that describes this
6946/// operator.
6947///
6948/// \param Functions The set of non-member functions that will be
6949/// considered by overload resolution. The caller needs to build this
6950/// set based on the context using, e.g.,
6951/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6952/// set should not contain any member functions; those will be added
6953/// by CreateOverloadedBinOp().
6954///
6955/// \param LHS Left-hand argument.
6956/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00006957ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006958Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006959 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006960 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006961 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006962 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006963 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006964
6965 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6966 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6967 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6968
6969 // If either side is type-dependent, create an appropriate dependent
6970 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006971 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006972 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006973 // If there are no functions to store, just build a dependent
6974 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00006975 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00006976 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6977 Context.DependentTy, OpLoc));
6978
6979 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6980 Context.DependentTy,
6981 Context.DependentTy,
6982 Context.DependentTy,
6983 OpLoc));
6984 }
John McCall4c4c1df2010-01-26 03:27:55 +00006985
6986 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006987 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006988 // TODO: provide better source location info in DNLoc component.
6989 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006990 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006991 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006992 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006993 /*ADL*/ true, IsOverloaded(Fns),
6994 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006995 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006996 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006997 Context.DependentTy,
6998 OpLoc));
6999 }
7000
7001 // If this is the .* operator, which is not overloadable, just
7002 // create a built-in binary operator.
John McCalle3027922010-08-25 11:45:40 +00007003 if (Opc == BO_PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00007004 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007005
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007006 // If this is the assignment operator, we only perform overload resolution
7007 // if the left-hand side is a class or enumeration type. This is actually
7008 // a hack. The standard requires that we do overload resolution between the
7009 // various built-in candidates, but as DR507 points out, this can lead to
7010 // problems. So we do it this way, which pretty much follows what GCC does.
7011 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007012 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007013 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007014
Douglas Gregor084d8552009-03-13 23:49:33 +00007015 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007016 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007017
7018 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007019 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007020
7021 // Add operator candidates that are member functions.
7022 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7023
John McCall4c4c1df2010-01-26 03:27:55 +00007024 // Add candidates from ADL.
7025 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7026 Args, 2,
7027 /*ExplicitTemplateArgs*/ 0,
7028 CandidateSet);
7029
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007030 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007031 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007032
7033 // Perform overload resolution.
7034 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007035 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007036 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007037 // We found a built-in operator or an overloaded operator.
7038 FunctionDecl *FnDecl = Best->Function;
7039
7040 if (FnDecl) {
7041 // We matched an overloaded operator. Build a call to that
7042 // operator.
7043
7044 // Convert the arguments.
7045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007046 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007047 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007048
John McCalldadc5752010-08-24 06:29:42 +00007049 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007050 = PerformCopyInitialization(
7051 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007052 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007053 FnDecl->getParamDecl(0)),
7054 SourceLocation(),
7055 Owned(Args[1]));
7056 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007057 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007058
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007059 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007060 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007061 return ExprError();
7062
7063 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007064 } else {
7065 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007066 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007067 = PerformCopyInitialization(
7068 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007069 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007070 FnDecl->getParamDecl(0)),
7071 SourceLocation(),
7072 Owned(Args[0]));
7073 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007074 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007075
John McCalldadc5752010-08-24 06:29:42 +00007076 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007077 = PerformCopyInitialization(
7078 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007079 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007080 FnDecl->getParamDecl(1)),
7081 SourceLocation(),
7082 Owned(Args[1]));
7083 if (Arg1.isInvalid())
7084 return ExprError();
7085 Args[0] = LHS = Arg0.takeAs<Expr>();
7086 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007087 }
7088
John McCall4fa0d5f2010-05-06 18:15:07 +00007089 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7090
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007091 // Determine the result type
7092 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007093 = FnDecl->getType()->getAs<FunctionType>()
7094 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007095
7096 // Build the actual expression node.
7097 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00007098 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007099 UsualUnaryConversions(FnExpr);
7100
John McCallb268a282010-08-23 23:25:46 +00007101 CXXOperatorCallExpr *TheCall =
7102 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7103 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007104
John McCallb268a282010-08-23 23:25:46 +00007105 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007106 FnDecl))
7107 return ExprError();
7108
John McCallb268a282010-08-23 23:25:46 +00007109 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007110 } else {
7111 // We matched a built-in operator. Convert the arguments, then
7112 // break out so that we will build the appropriate built-in
7113 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007114 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007115 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007116 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007117 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007118 return ExprError();
7119
7120 break;
7121 }
7122 }
7123
Douglas Gregor66950a32009-09-30 21:46:01 +00007124 case OR_No_Viable_Function: {
7125 // C++ [over.match.oper]p9:
7126 // If the operator is the operator , [...] and there are no
7127 // viable functions, then the operator is assumed to be the
7128 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007129 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007130 break;
7131
Sebastian Redl027de2a2009-05-21 11:50:50 +00007132 // For class as left operand for assignment or compound assigment operator
7133 // do not fall through to handling in built-in, but report that no overloaded
7134 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007135 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007136 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007137 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007138 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7139 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007140 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007141 } else {
7142 // No viable function; try to create a built-in operation, which will
7143 // produce an error. Then, show the non-viable candidates.
7144 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007145 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007146 assert(Result.isInvalid() &&
7147 "C++ binary operator overloading is missing candidates!");
7148 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007149 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7150 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007151 return move(Result);
7152 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007153
7154 case OR_Ambiguous:
7155 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7156 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007157 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007158 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7159 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007160 return ExprError();
7161
7162 case OR_Deleted:
7163 Diag(OpLoc, diag::err_ovl_deleted_oper)
7164 << Best->Function->isDeleted()
7165 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007166 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007167 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007168 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007169 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007170
Douglas Gregor66950a32009-09-30 21:46:01 +00007171 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007172 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007173}
7174
John McCalldadc5752010-08-24 06:29:42 +00007175ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007176Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7177 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007178 Expr *Base, Expr *Idx) {
7179 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007180 DeclarationName OpName =
7181 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7182
7183 // If either side is type-dependent, create an appropriate dependent
7184 // expression.
7185 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7186
John McCall58cc69d2010-01-27 01:50:18 +00007187 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007188 // CHECKME: no 'operator' keyword?
7189 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7190 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007191 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007192 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007193 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007194 /*ADL*/ true, /*Overloaded*/ false,
7195 UnresolvedSetIterator(),
7196 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007197 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007198
Sebastian Redladba46e2009-10-29 20:17:01 +00007199 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7200 Args, 2,
7201 Context.DependentTy,
7202 RLoc));
7203 }
7204
7205 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007206 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007207
7208 // Subscript can only be overloaded as a member function.
7209
7210 // Add operator candidates that are member functions.
7211 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7212
7213 // Add builtin operator candidates.
7214 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7215
7216 // Perform overload resolution.
7217 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007218 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007219 case OR_Success: {
7220 // We found a built-in operator or an overloaded operator.
7221 FunctionDecl *FnDecl = Best->Function;
7222
7223 if (FnDecl) {
7224 // We matched an overloaded operator. Build a call to that
7225 // operator.
7226
John McCalla0296f72010-03-19 07:35:19 +00007227 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007228 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007229
Sebastian Redladba46e2009-10-29 20:17:01 +00007230 // Convert the arguments.
7231 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007232 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007233 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007234 return ExprError();
7235
Anders Carlssona68e51e2010-01-29 18:37:50 +00007236 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007237 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007238 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007239 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007240 FnDecl->getParamDecl(0)),
7241 SourceLocation(),
7242 Owned(Args[1]));
7243 if (InputInit.isInvalid())
7244 return ExprError();
7245
7246 Args[1] = InputInit.takeAs<Expr>();
7247
Sebastian Redladba46e2009-10-29 20:17:01 +00007248 // Determine the result type
7249 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007250 = FnDecl->getType()->getAs<FunctionType>()
7251 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007252
7253 // Build the actual expression node.
7254 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7255 LLoc);
7256 UsualUnaryConversions(FnExpr);
7257
John McCallb268a282010-08-23 23:25:46 +00007258 CXXOperatorCallExpr *TheCall =
7259 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7260 FnExpr, Args, 2,
7261 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007262
John McCallb268a282010-08-23 23:25:46 +00007263 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007264 FnDecl))
7265 return ExprError();
7266
John McCallb268a282010-08-23 23:25:46 +00007267 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007268 } else {
7269 // We matched a built-in operator. Convert the arguments, then
7270 // break out so that we will build the appropriate built-in
7271 // operator node.
7272 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007273 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007274 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007275 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007276 return ExprError();
7277
7278 break;
7279 }
7280 }
7281
7282 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007283 if (CandidateSet.empty())
7284 Diag(LLoc, diag::err_ovl_no_oper)
7285 << Args[0]->getType() << /*subscript*/ 0
7286 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7287 else
7288 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7289 << Args[0]->getType()
7290 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007291 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7292 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007293 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007294 }
7295
7296 case OR_Ambiguous:
7297 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7298 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007299 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7300 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007301 return ExprError();
7302
7303 case OR_Deleted:
7304 Diag(LLoc, diag::err_ovl_deleted_oper)
7305 << Best->Function->isDeleted() << "[]"
7306 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007307 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7308 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007309 return ExprError();
7310 }
7311
7312 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007313 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007314}
7315
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007316/// BuildCallToMemberFunction - Build a call to a member
7317/// function. MemExpr is the expression that refers to the member
7318/// function (and includes the object parameter), Args/NumArgs are the
7319/// arguments to the function call (not including the object
7320/// parameter). The caller needs to validate that the member
7321/// expression refers to a member function or an overloaded member
7322/// function.
John McCalldadc5752010-08-24 06:29:42 +00007323ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007324Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7325 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007326 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007327 // Dig out the member expression. This holds both the object
7328 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007329 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7330
John McCall10eae182009-11-30 22:42:35 +00007331 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007332 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007333 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007334 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007335 if (isa<MemberExpr>(NakedMemExpr)) {
7336 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007337 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007338 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007339 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007340 } else {
7341 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007342 Qualifier = UnresExpr->getQualifier();
7343
John McCall6e9f8f62009-12-03 04:06:58 +00007344 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007345
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007346 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007347 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007348
John McCall2d74de92009-12-01 22:10:20 +00007349 // FIXME: avoid copy.
7350 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7351 if (UnresExpr->hasExplicitTemplateArgs()) {
7352 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7353 TemplateArgs = &TemplateArgsBuffer;
7354 }
7355
John McCall10eae182009-11-30 22:42:35 +00007356 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7357 E = UnresExpr->decls_end(); I != E; ++I) {
7358
John McCall6e9f8f62009-12-03 04:06:58 +00007359 NamedDecl *Func = *I;
7360 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7361 if (isa<UsingShadowDecl>(Func))
7362 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7363
John McCall10eae182009-11-30 22:42:35 +00007364 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007365 // If explicit template arguments were provided, we can't call a
7366 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007367 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007368 continue;
7369
John McCalla0296f72010-03-19 07:35:19 +00007370 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007371 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007372 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007373 } else {
John McCall10eae182009-11-30 22:42:35 +00007374 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007375 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007376 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007377 CandidateSet,
7378 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007379 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007380 }
Mike Stump11289f42009-09-09 15:08:12 +00007381
John McCall10eae182009-11-30 22:42:35 +00007382 DeclarationName DeclName = UnresExpr->getMemberName();
7383
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007384 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007385 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7386 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007387 case OR_Success:
7388 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007389 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007390 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007391 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007392 break;
7393
7394 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007395 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007396 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007397 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007398 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007399 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007400 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007401
7402 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007403 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007404 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007405 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007406 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007407 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007408
7409 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007410 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007411 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007412 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007414 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007415 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007416 }
7417
John McCall16df1e52010-03-30 21:47:33 +00007418 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007419
John McCall2d74de92009-12-01 22:10:20 +00007420 // If overload resolution picked a static member, build a
7421 // non-member call based on that function.
7422 if (Method->isStatic()) {
7423 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7424 Args, NumArgs, RParenLoc);
7425 }
7426
John McCall10eae182009-11-30 22:42:35 +00007427 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007428 }
7429
7430 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007431 CXXMemberCallExpr *TheCall =
7432 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7433 Method->getCallResultType(),
7434 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007435
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007436 // Check for a valid return type.
7437 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007438 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007439 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007440
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007441 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007442 // We only need to do this if there was actually an overload; otherwise
7443 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007444 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007445 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007446 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7447 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007448 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007449 MemExpr->setBase(ObjectArg);
7450
7451 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007452 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007453 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007454 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007455 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007456
John McCallb268a282010-08-23 23:25:46 +00007457 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007458 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007459
John McCallb268a282010-08-23 23:25:46 +00007460 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007461}
7462
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007463/// BuildCallToObjectOfClassType - Build a call to an object of class
7464/// type (C++ [over.call.object]), which can end up invoking an
7465/// overloaded function call operator (@c operator()) or performing a
7466/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007467ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007468Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007469 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007470 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007471 SourceLocation RParenLoc) {
7472 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007473 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007474
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007475 // C++ [over.call.object]p1:
7476 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007477 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007478 // candidate functions includes at least the function call
7479 // operators of T. The function call operators of T are obtained by
7480 // ordinary lookup of the name operator() in the context of
7481 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007482 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007483 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007484
7485 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007486 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007487 << Object->getSourceRange()))
7488 return true;
7489
John McCall27b18f82009-11-17 02:14:36 +00007490 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7491 LookupQualifiedName(R, Record->getDecl());
7492 R.suppressDiagnostics();
7493
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007494 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007495 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007496 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007497 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007498 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007499 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007500
Douglas Gregorab7897a2008-11-19 22:57:39 +00007501 // C++ [over.call.object]p2:
7502 // In addition, for each conversion function declared in T of the
7503 // form
7504 //
7505 // operator conversion-type-id () cv-qualifier;
7506 //
7507 // where cv-qualifier is the same cv-qualification as, or a
7508 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007509 // denotes the type "pointer to function of (P1,...,Pn) returning
7510 // R", or the type "reference to pointer to function of
7511 // (P1,...,Pn) returning R", or the type "reference to function
7512 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007513 // is also considered as a candidate function. Similarly,
7514 // surrogate call functions are added to the set of candidate
7515 // functions for each conversion function declared in an
7516 // accessible base class provided the function is not hidden
7517 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007518 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007519 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007520 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007521 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007522 NamedDecl *D = *I;
7523 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7524 if (isa<UsingShadowDecl>(D))
7525 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7526
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007527 // Skip over templated conversion functions; they aren't
7528 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007529 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007530 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007531
John McCall6e9f8f62009-12-03 04:06:58 +00007532 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007533
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007534 // Strip the reference type (if any) and then the pointer type (if
7535 // any) to get down to what might be a function type.
7536 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7537 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7538 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007539
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007540 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007541 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007542 Object->getType(), Args, NumArgs,
7543 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007544 }
Mike Stump11289f42009-09-09 15:08:12 +00007545
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007546 // Perform overload resolution.
7547 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007548 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7549 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007550 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007551 // Overload resolution succeeded; we'll build the appropriate call
7552 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007553 break;
7554
7555 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007556 if (CandidateSet.empty())
7557 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7558 << Object->getType() << /*call*/ 1
7559 << Object->getSourceRange();
7560 else
7561 Diag(Object->getSourceRange().getBegin(),
7562 diag::err_ovl_no_viable_object_call)
7563 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007564 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007565 break;
7566
7567 case OR_Ambiguous:
7568 Diag(Object->getSourceRange().getBegin(),
7569 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007570 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007571 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007572 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007573
7574 case OR_Deleted:
7575 Diag(Object->getSourceRange().getBegin(),
7576 diag::err_ovl_deleted_object_call)
7577 << Best->Function->isDeleted()
7578 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007579 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007580 break;
Mike Stump11289f42009-09-09 15:08:12 +00007581 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007582
Douglas Gregorb412e172010-07-25 18:17:45 +00007583 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007584 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007585
Douglas Gregorab7897a2008-11-19 22:57:39 +00007586 if (Best->Function == 0) {
7587 // Since there is no function declaration, this is one of the
7588 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007589 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007590 = cast<CXXConversionDecl>(
7591 Best->Conversions[0].UserDefined.ConversionFunction);
7592
John McCalla0296f72010-03-19 07:35:19 +00007593 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007594 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007595
Douglas Gregorab7897a2008-11-19 22:57:39 +00007596 // We selected one of the surrogate functions that converts the
7597 // object parameter to a function pointer. Perform the conversion
7598 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007599
7600 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007601 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007602 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7603 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007604
John McCallfaf5fb42010-08-26 23:41:50 +00007605 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007606 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007607 }
7608
John McCalla0296f72010-03-19 07:35:19 +00007609 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007610 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007611
Douglas Gregorab7897a2008-11-19 22:57:39 +00007612 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7613 // that calls this method, using Object for the implicit object
7614 // parameter and passing along the remaining arguments.
7615 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007616 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007617
7618 unsigned NumArgsInProto = Proto->getNumArgs();
7619 unsigned NumArgsToCheck = NumArgs;
7620
7621 // Build the full argument list for the method call (the
7622 // implicit object parameter is placed at the beginning of the
7623 // list).
7624 Expr **MethodArgs;
7625 if (NumArgs < NumArgsInProto) {
7626 NumArgsToCheck = NumArgsInProto;
7627 MethodArgs = new Expr*[NumArgsInProto + 1];
7628 } else {
7629 MethodArgs = new Expr*[NumArgs + 1];
7630 }
7631 MethodArgs[0] = Object;
7632 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7633 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007634
7635 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007636 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007637 UsualUnaryConversions(NewFn);
7638
7639 // Once we've built TheCall, all of the expressions are properly
7640 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007641 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007642 CXXOperatorCallExpr *TheCall =
7643 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7644 MethodArgs, NumArgs + 1,
7645 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007646 delete [] MethodArgs;
7647
John McCallb268a282010-08-23 23:25:46 +00007648 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007649 Method))
7650 return true;
7651
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007652 // We may have default arguments. If so, we need to allocate more
7653 // slots in the call for them.
7654 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007655 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007656 else if (NumArgs > NumArgsInProto)
7657 NumArgsToCheck = NumArgsInProto;
7658
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007659 bool IsError = false;
7660
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007661 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007662 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007663 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007664 TheCall->setArg(0, Object);
7665
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007666
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007667 // Check the argument types.
7668 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007669 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007670 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007671 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007672
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007673 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007674
John McCalldadc5752010-08-24 06:29:42 +00007675 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007676 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007677 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007678 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007679 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007680
7681 IsError |= InputInit.isInvalid();
7682 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007683 } else {
John McCalldadc5752010-08-24 06:29:42 +00007684 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007685 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7686 if (DefArg.isInvalid()) {
7687 IsError = true;
7688 break;
7689 }
7690
7691 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007692 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007693
7694 TheCall->setArg(i + 1, Arg);
7695 }
7696
7697 // If this is a variadic call, handle args passed through "...".
7698 if (Proto->isVariadic()) {
7699 // Promote the arguments (C99 6.5.2.2p7).
7700 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7701 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007702 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007703 TheCall->setArg(i + 1, Arg);
7704 }
7705 }
7706
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007707 if (IsError) return true;
7708
John McCallb268a282010-08-23 23:25:46 +00007709 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007710 return true;
7711
John McCalle172be52010-08-24 06:09:16 +00007712 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007713}
7714
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007715/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007716/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007717/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007718ExprResult
John McCallb268a282010-08-23 23:25:46 +00007719Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007720 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007721
John McCallbc077cf2010-02-08 23:07:23 +00007722 SourceLocation Loc = Base->getExprLoc();
7723
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007724 // C++ [over.ref]p1:
7725 //
7726 // [...] An expression x->m is interpreted as (x.operator->())->m
7727 // for a class object x of type T if T::operator->() exists and if
7728 // the operator is selected as the best match function by the
7729 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007730 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007731 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007732 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007733
John McCallbc077cf2010-02-08 23:07:23 +00007734 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007735 PDiag(diag::err_typecheck_incomplete_tag)
7736 << Base->getSourceRange()))
7737 return ExprError();
7738
John McCall27b18f82009-11-17 02:14:36 +00007739 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7740 LookupQualifiedName(R, BaseRecord->getDecl());
7741 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007742
7743 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007744 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007745 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007746 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007747 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007748
7749 // Perform overload resolution.
7750 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007751 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007752 case OR_Success:
7753 // Overload resolution succeeded; we'll build the call below.
7754 break;
7755
7756 case OR_No_Viable_Function:
7757 if (CandidateSet.empty())
7758 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007759 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007760 else
7761 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007762 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007763 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007764 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007765
7766 case OR_Ambiguous:
7767 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007768 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007769 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007770 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007771
7772 case OR_Deleted:
7773 Diag(OpLoc, diag::err_ovl_deleted_oper)
7774 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007775 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007776 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007777 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007778 }
7779
John McCalla0296f72010-03-19 07:35:19 +00007780 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007781 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007782
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007783 // Convert the object parameter.
7784 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007785 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7786 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007787 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007788
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007789 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007790 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7791 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007792 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007793
Douglas Gregor603d81b2010-07-13 08:18:22 +00007794 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007795 CXXOperatorCallExpr *TheCall =
7796 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7797 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007798
John McCallb268a282010-08-23 23:25:46 +00007799 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007800 Method))
7801 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007802 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007803}
7804
Douglas Gregorcd695e52008-11-10 20:40:00 +00007805/// FixOverloadedFunctionReference - E is an expression that refers to
7806/// a C++ overloaded function (possibly with some parentheses and
7807/// perhaps a '&' around it). We have resolved the overloaded function
7808/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007809/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007810Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007811 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007812 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007813 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7814 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007815 if (SubExpr == PE->getSubExpr())
7816 return PE->Retain();
7817
7818 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7819 }
7820
7821 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007822 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7823 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007824 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007825 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007826 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007827 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007828 if (SubExpr == ICE->getSubExpr())
7829 return ICE->Retain();
7830
John McCallcf142162010-08-07 06:22:56 +00007831 return ImplicitCastExpr::Create(Context, ICE->getType(),
7832 ICE->getCastKind(),
7833 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00007834 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007835 }
7836
7837 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00007838 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007839 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007840 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7841 if (Method->isStatic()) {
7842 // Do nothing: static member functions aren't any different
7843 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007844 } else {
John McCalle66edc12009-11-24 19:00:30 +00007845 // Fix the sub expression, which really has to be an
7846 // UnresolvedLookupExpr holding an overloaded member function
7847 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007848 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7849 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007850 if (SubExpr == UnOp->getSubExpr())
7851 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007852
John McCalld14a8642009-11-21 08:51:07 +00007853 assert(isa<DeclRefExpr>(SubExpr)
7854 && "fixed to something other than a decl ref");
7855 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7856 && "fixed to a member ref with no nested name qualifier");
7857
7858 // We have taken the address of a pointer to member
7859 // function. Perform the computation here so that we get the
7860 // appropriate pointer to member type.
7861 QualType ClassType
7862 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7863 QualType MemPtrType
7864 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7865
John McCalle3027922010-08-25 11:45:40 +00007866 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCalld14a8642009-11-21 08:51:07 +00007867 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007868 }
7869 }
John McCall16df1e52010-03-30 21:47:33 +00007870 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7871 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007872 if (SubExpr == UnOp->getSubExpr())
7873 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007874
John McCalle3027922010-08-25 11:45:40 +00007875 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007876 Context.getPointerType(SubExpr->getType()),
7877 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007878 }
John McCalld14a8642009-11-21 08:51:07 +00007879
7880 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007881 // FIXME: avoid copy.
7882 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007883 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007884 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7885 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007886 }
7887
John McCalld14a8642009-11-21 08:51:07 +00007888 return DeclRefExpr::Create(Context,
7889 ULE->getQualifier(),
7890 ULE->getQualifierRange(),
7891 Fn,
7892 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007893 Fn->getType(),
7894 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007895 }
7896
John McCall10eae182009-11-30 22:42:35 +00007897 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007898 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007899 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7900 if (MemExpr->hasExplicitTemplateArgs()) {
7901 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7902 TemplateArgs = &TemplateArgsBuffer;
7903 }
John McCall6b51f282009-11-23 01:53:49 +00007904
John McCall2d74de92009-12-01 22:10:20 +00007905 Expr *Base;
7906
7907 // If we're filling in
7908 if (MemExpr->isImplicitAccess()) {
7909 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7910 return DeclRefExpr::Create(Context,
7911 MemExpr->getQualifier(),
7912 MemExpr->getQualifierRange(),
7913 Fn,
7914 MemExpr->getMemberLoc(),
7915 Fn->getType(),
7916 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007917 } else {
7918 SourceLocation Loc = MemExpr->getMemberLoc();
7919 if (MemExpr->getQualifier())
7920 Loc = MemExpr->getQualifierRange().getBegin();
7921 Base = new (Context) CXXThisExpr(Loc,
7922 MemExpr->getBaseType(),
7923 /*isImplicit=*/true);
7924 }
John McCall2d74de92009-12-01 22:10:20 +00007925 } else
7926 Base = MemExpr->getBase()->Retain();
7927
7928 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007929 MemExpr->isArrow(),
7930 MemExpr->getQualifier(),
7931 MemExpr->getQualifierRange(),
7932 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007933 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007934 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007935 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007936 Fn->getType());
7937 }
7938
Douglas Gregor51c538b2009-11-20 19:42:02 +00007939 assert(false && "Invalid reference to overloaded function");
7940 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007941}
7942
John McCalldadc5752010-08-24 06:29:42 +00007943ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7944 DeclAccessPair Found,
7945 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007946 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007947}
7948
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007949} // end namespace clang