blob: 5ea7414026cf74156a0c76ba5fcfd7660be1ce72 [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 McCall7decc9e2010-11-18 06:31:45 +000036/// A convenience routine for creating a decayed reference to a
37/// function.
38static Expr *
39CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
40 SourceLocation Loc = SourceLocation()) {
41 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
42 S.DefaultFunctionArrayConversion(E);
43 return E;
44}
45
John McCall5c32be02010-08-24 20:38:10 +000046static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
47 bool InOverloadResolution,
48 StandardConversionSequence &SCS);
49static OverloadingResult
50IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
51 UserDefinedConversionSequence& User,
52 OverloadCandidateSet& Conversions,
53 bool AllowExplicit);
54
55
56static ImplicitConversionSequence::CompareKind
57CompareStandardConversionSequences(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61static ImplicitConversionSequence::CompareKind
62CompareQualificationConversions(Sema &S,
63 const StandardConversionSequence& SCS1,
64 const StandardConversionSequence& SCS2);
65
66static ImplicitConversionSequence::CompareKind
67CompareDerivedToBaseConversions(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71
72
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073/// GetConversionCategory - Retrieve the implicit conversion
74/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000075ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076GetConversionCategory(ImplicitConversionKind Kind) {
77 static const ImplicitConversionCategory
78 Category[(int)ICK_Num_Conversion_Kinds] = {
79 ICC_Identity,
80 ICC_Lvalue_Transformation,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000083 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 ICC_Qualification_Adjustment,
85 ICC_Promotion,
86 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000087 ICC_Promotion,
88 ICC_Conversion,
89 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000090 ICC_Conversion,
91 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000095 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000096 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000097 ICC_Conversion,
98 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000099 ICC_Conversion
100 };
101 return Category[(int)Kind];
102}
103
104/// GetConversionRank - Retrieve the implicit conversion rank
105/// corresponding to the given implicit conversion kind.
106ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
107 static const ImplicitConversionRank
108 Rank[(int)ICK_Num_Conversion_Kinds] = {
109 ICR_Exact_Match,
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000114 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000115 ICR_Promotion,
116 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000117 ICR_Promotion,
118 ICR_Conversion,
119 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 ICR_Conversion,
121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000125 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000126 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000127 ICR_Conversion,
128 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000129 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000130 };
131 return Rank[(int)Kind];
132}
133
134/// GetImplicitConversionName - Return the name of this kind of
135/// implicit conversion.
136const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000137 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000138 "No conversion",
139 "Lvalue-to-rvalue",
140 "Array-to-pointer",
141 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000142 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143 "Qualification",
144 "Integral promotion",
145 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000146 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "Integral conversion",
148 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000149 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 "Floating-integral conversion",
151 "Pointer conversion",
152 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000153 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000154 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000155 "Derived-to-base conversion",
156 "Vector conversion",
157 "Vector splat",
158 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 };
160 return Name[Kind];
161}
162
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000163/// StandardConversionSequence - Set the standard conversion
164/// sequence to the identity conversion.
165void StandardConversionSequence::setAsIdentityConversion() {
166 First = ICK_Identity;
167 Second = ICK_Identity;
168 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000169 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000170 ReferenceBinding = false;
171 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000172 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000173 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000174}
175
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000176/// getRank - Retrieve the rank of this standard conversion sequence
177/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
178/// implicit conversions.
179ImplicitConversionRank StandardConversionSequence::getRank() const {
180 ImplicitConversionRank Rank = ICR_Exact_Match;
181 if (GetConversionRank(First) > Rank)
182 Rank = GetConversionRank(First);
183 if (GetConversionRank(Second) > Rank)
184 Rank = GetConversionRank(Second);
185 if (GetConversionRank(Third) > Rank)
186 Rank = GetConversionRank(Third);
187 return Rank;
188}
189
190/// isPointerConversionToBool - Determines whether this conversion is
191/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000192/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000193/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000194bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 // Note that FromType has not necessarily been transformed by the
196 // array-to-pointer or function-to-pointer implicit conversions, so
197 // check for their presence as well as checking whether FromType is
198 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000199 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000200 (getFromType()->isPointerType() ||
201 getFromType()->isObjCObjectPointerType() ||
202 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000203 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
205 return true;
206
207 return false;
208}
209
Douglas Gregor5c407d92008-10-23 00:40:37 +0000210/// isPointerConversionToVoidPointer - Determines whether this
211/// conversion is a conversion of a pointer to a void pointer. This is
212/// used as part of the ranking of standard conversion sequences (C++
213/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000214bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000215StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000216isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000217 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000218 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000219
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer implicit conversion, so check for its presence
222 // and redo the conversion to get a pointer.
223 if (First == ICK_Array_To_Pointer)
224 FromType = Context.getArrayDecayedType(FromType);
225
John McCall75851b12010-10-26 06:40:27 +0000226 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000227 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000228 return ToPtrType->getPointeeType()->isVoidType();
229
230 return false;
231}
232
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233/// DebugPrint - Print this standard conversion sequence to standard
234/// error. Useful for debugging overloading issues.
235void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000236 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000237 bool PrintedSomething = false;
238 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 PrintedSomething = true;
241 }
242
243 if (Second != ICK_Identity) {
244 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000245 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000246 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000247 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000248
249 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000251 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000253 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000254 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000255 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000256 PrintedSomething = true;
257 }
258
259 if (Third != ICK_Identity) {
260 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000261 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000262 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000263 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000264 PrintedSomething = true;
265 }
266
267 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 }
270}
271
272/// DebugPrint - Print this user-defined conversion sequence to standard
273/// error. Useful for debugging overloading issues.
274void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000276 if (Before.First || Before.Second || Before.Third) {
277 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000280 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000282 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000283 After.DebugPrint();
284 }
285}
286
287/// DebugPrint - Print this implicit conversion sequence to standard
288/// error. Useful for debugging overloading issues.
289void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000290 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000291 switch (ConversionKind) {
292 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 Standard.DebugPrint();
295 break;
296 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000297 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 UserDefined.DebugPrint();
299 break;
300 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000301 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000302 break;
John McCall0d1da222010-01-12 00:44:57 +0000303 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000304 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000305 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 break;
309 }
310
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000311 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000312}
313
John McCall0d1da222010-01-12 00:44:57 +0000314void AmbiguousConversionSequence::construct() {
315 new (&conversions()) ConversionSet();
316}
317
318void AmbiguousConversionSequence::destruct() {
319 conversions().~ConversionSet();
320}
321
322void
323AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
324 FromTypePtr = O.FromTypePtr;
325 ToTypePtr = O.ToTypePtr;
326 new (&conversions()) ConversionSet(O.conversions());
327}
328
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000329namespace {
330 // Structure used by OverloadCandidate::DeductionFailureInfo to store
331 // template parameter and template argument information.
332 struct DFIParamWithArguments {
333 TemplateParameter Param;
334 TemplateArgument FirstArg;
335 TemplateArgument SecondArg;
336 };
337}
338
339/// \brief Convert from Sema's representation of template deduction information
340/// to the form used in overload-candidate information.
341OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000342static MakeDeductionFailureInfo(ASTContext &Context,
343 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000345 OverloadCandidate::DeductionFailureInfo Result;
346 Result.Result = static_cast<unsigned>(TDK);
347 Result.Data = 0;
348 switch (TDK) {
349 case Sema::TDK_Success:
350 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000351 case Sema::TDK_TooManyArguments:
352 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 break;
354
355 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000356 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000357 Result.Data = Info.Param.getOpaqueValue();
358 break;
359
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000361 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000362 // FIXME: Should allocate from normal heap so that we can free this later.
363 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364 Saved->Param = Info.Param;
365 Saved->FirstArg = Info.FirstArg;
366 Saved->SecondArg = Info.SecondArg;
367 Result.Data = Saved;
368 break;
369 }
370
371 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000372 Result.Data = Info.take();
373 break;
374
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000375 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 case Sema::TDK_FailedOverloadResolution:
377 break;
378 }
379
380 return Result;
381}
John McCall0d1da222010-01-12 00:44:57 +0000382
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383void OverloadCandidate::DeductionFailureInfo::Destroy() {
384 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
385 case Sema::TDK_Success:
386 case Sema::TDK_InstantiationDepth:
387 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000388 case Sema::TDK_TooManyArguments:
389 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000390 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000391 break;
392
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000394 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000395 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 Data = 0;
397 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000398
399 case Sema::TDK_SubstitutionFailure:
400 // FIXME: Destroy the template arugment list?
401 Data = 0;
402 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000403
Douglas Gregor461761d2010-05-08 18:20:53 +0000404 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000405 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 case Sema::TDK_FailedOverloadResolution:
407 break;
408 }
409}
410
411TemplateParameter
412OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
413 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
414 case Sema::TDK_Success:
415 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000416 case Sema::TDK_TooManyArguments:
417 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000418 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 return TemplateParameter();
420
421 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000422 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000423 return TemplateParameter::getFromOpaqueValue(Data);
424
425 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000426 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000427 return static_cast<DFIParamWithArguments*>(Data)->Param;
428
429 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000430 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_FailedOverloadResolution:
432 break;
433 }
434
435 return TemplateParameter();
436}
Douglas Gregord09efd42010-05-08 20:07:26 +0000437
438TemplateArgumentList *
439OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
440 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
441 case Sema::TDK_Success:
442 case Sema::TDK_InstantiationDepth:
443 case Sema::TDK_TooManyArguments:
444 case Sema::TDK_TooFewArguments:
445 case Sema::TDK_Incomplete:
446 case Sema::TDK_InvalidExplicitArguments:
447 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000448 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000449 return 0;
450
451 case Sema::TDK_SubstitutionFailure:
452 return static_cast<TemplateArgumentList*>(Data);
453
454 // Unhandled
455 case Sema::TDK_NonDeducedMismatch:
456 case Sema::TDK_FailedOverloadResolution:
457 break;
458 }
459
460 return 0;
461}
462
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000463const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
464 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
465 case Sema::TDK_Success:
466 case Sema::TDK_InstantiationDepth:
467 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000468 case Sema::TDK_TooManyArguments:
469 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000470 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000471 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000472 return 0;
473
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000474 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000475 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000476 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
477
Douglas Gregor461761d2010-05-08 18:20:53 +0000478 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000479 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000480 case Sema::TDK_FailedOverloadResolution:
481 break;
482 }
483
484 return 0;
485}
486
487const TemplateArgument *
488OverloadCandidate::DeductionFailureInfo::getSecondArg() {
489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
490 case Sema::TDK_Success:
491 case Sema::TDK_InstantiationDepth:
492 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 case Sema::TDK_TooManyArguments:
494 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000495 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000496 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 return 0;
498
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000499 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000500 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000501 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
502
Douglas Gregor461761d2010-05-08 18:20:53 +0000503 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_FailedOverloadResolution:
506 break;
507 }
508
509 return 0;
510}
511
512void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000513 inherited::clear();
514 Functions.clear();
515}
516
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000518// overload of the declarations in Old. This routine returns false if
519// New and Old cannot be overloaded, e.g., if New has the same
520// signature as some function in Old (C++ 1.3.10) or if the Old
521// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000522// it does return false, MatchedDecl will point to the decl that New
523// cannot be overloaded with. This decl may be a UsingShadowDecl on
524// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525//
526// Example: Given the following input:
527//
528// void f(int, float); // #1
529// void f(int, int); // #2
530// int f(int, int); // #3
531//
532// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000533// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534//
John McCall3d988d92009-12-02 08:47:38 +0000535// When we process #2, Old contains only the FunctionDecl for #1. By
536// comparing the parameter types, we see that #1 and #2 are overloaded
537// (since they have different signatures), so this routine returns
538// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539//
John McCall3d988d92009-12-02 08:47:38 +0000540// When we process #3, Old is an overload set containing #1 and #2. We
541// compare the signatures of #3 to #1 (they're overloaded, so we do
542// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
543// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000544// signature), IsOverload returns false and MatchedDecl will be set to
545// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000546//
547// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
548// into a class by a using declaration. The rules for whether to hide
549// shadow declarations ignore some properties which otherwise figure
550// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000551Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000552Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
553 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000554 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000555 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000556 NamedDecl *OldD = *I;
557
558 bool OldIsUsingDecl = false;
559 if (isa<UsingShadowDecl>(OldD)) {
560 OldIsUsingDecl = true;
561
562 // We can always introduce two using declarations into the same
563 // context, even if they have identical signatures.
564 if (NewIsUsingDecl) continue;
565
566 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
567 }
568
569 // If either declaration was introduced by a using declaration,
570 // we'll need to use slightly different rules for matching.
571 // Essentially, these rules are the normal rules, except that
572 // function templates hide function templates with different
573 // return types or template parameter lists.
574 bool UseMemberUsingDeclRules =
575 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
576
John McCall3d988d92009-12-02 08:47:38 +0000577 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCalldaa3d6b2009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000586 }
John McCall3d988d92009-12-02 08:47:38 +0000587 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000588 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
589 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
590 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
591 continue;
592 }
593
John McCalldaa3d6b2009-12-09 03:35:25 +0000594 Match = *I;
595 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000596 }
John McCalla8987a2942010-11-10 03:01:53 +0000597 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000598 // We can overload with these, which can show up when doing
599 // redeclaration checks for UsingDecls.
600 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000601 } else if (isa<TagDecl>(OldD)) {
602 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000603 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
604 // Optimistically assume that an unresolved using decl will
605 // overload; if it doesn't, we'll have to diagnose during
606 // template instantiation.
607 } else {
John McCall1f82f242009-11-18 22:49:29 +0000608 // (C++ 13p1):
609 // Only function declarations can be overloaded; object and type
610 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000613 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000614 }
John McCall1f82f242009-11-18 22:49:29 +0000615
John McCalldaa3d6b2009-12-09 03:35:25 +0000616 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000617}
618
John McCalle9cccd82010-06-16 08:42:20 +0000619bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
620 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000621 // If both of the functions are extern "C", then they are not
622 // overloads.
623 if (Old->isExternC() && New->isExternC())
624 return false;
625
John McCall1f82f242009-11-18 22:49:29 +0000626 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
627 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
628
629 // C++ [temp.fct]p2:
630 // A function template can be overloaded with other function templates
631 // and with normal (non-template) functions.
632 if ((OldTemplate == 0) != (NewTemplate == 0))
633 return true;
634
635 // Is the function New an overload of the function Old?
636 QualType OldQType = Context.getCanonicalType(Old->getType());
637 QualType NewQType = Context.getCanonicalType(New->getType());
638
639 // Compare the signatures (C++ 1.3.10) of the two functions to
640 // determine whether they are overloads. If we find any mismatch
641 // in the signature, they are overloads.
642
643 // If either of these functions is a K&R-style function (no
644 // prototype), then we consider them to have matching signatures.
645 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
646 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
647 return false;
648
649 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
650 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
651
652 // The signature of a function includes the types of its
653 // parameters (C++ 1.3.10), which includes the presence or absence
654 // of the ellipsis; see C++ DR 357).
655 if (OldQType != NewQType &&
656 (OldType->getNumArgs() != NewType->getNumArgs() ||
657 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000658 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000659 return true;
660
661 // C++ [temp.over.link]p4:
662 // The signature of a function template consists of its function
663 // signature, its return type and its template parameter list. The names
664 // of the template parameters are significant only for establishing the
665 // relationship between the template parameters and the rest of the
666 // signature.
667 //
668 // We check the return type and template parameter lists for function
669 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000670 //
671 // However, we don't consider either of these when deciding whether
672 // a member introduced by a shadow declaration is hidden.
673 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000674 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
675 OldTemplate->getTemplateParameters(),
676 false, TPL_TemplateMatch) ||
677 OldType->getResultType() != NewType->getResultType()))
678 return true;
679
680 // If the function is a class member, its signature includes the
681 // cv-qualifiers (if any) on the function itself.
682 //
683 // As part of this, also check whether one of the member functions
684 // is static, in which case they are not overloads (C++
685 // 13.1p2). While not part of the definition of the signature,
686 // this check is important to determine whether these functions
687 // can be overloaded.
688 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
689 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
690 if (OldMethod && NewMethod &&
691 !OldMethod->isStatic() && !NewMethod->isStatic() &&
692 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
693 return true;
694
695 // The signatures match; this is not an overload.
696 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000697}
698
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000699/// TryImplicitConversion - Attempt to perform an implicit conversion
700/// from the given expression (Expr) to the given type (ToType). This
701/// function returns an implicit conversion sequence that can be used
702/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000703///
704/// void f(float f);
705/// void g(int i) { f(i); }
706///
707/// this routine would produce an implicit conversion sequence to
708/// describe the initialization of f from i, which will be a standard
709/// conversion sequence containing an lvalue-to-rvalue conversion (C++
710/// 4.1) followed by a floating-integral conversion (C++ 4.9).
711//
712/// Note that this routine only determines how the conversion can be
713/// performed; it does not actually perform the conversion. As such,
714/// it will not produce any diagnostics if no conversion is available,
715/// but will instead return an implicit conversion sequence of kind
716/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000717///
718/// If @p SuppressUserConversions, then user-defined conversions are
719/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000720/// If @p AllowExplicit, then explicit user-defined conversions are
721/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000722static ImplicitConversionSequence
723TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
724 bool SuppressUserConversions,
725 bool AllowExplicit,
726 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000727 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000728 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
729 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000730 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000731 return ICS;
732 }
733
John McCall5c32be02010-08-24 20:38:10 +0000734 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000735 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000736 return ICS;
737 }
738
Douglas Gregor836a7e82010-08-11 02:15:33 +0000739 // C++ [over.ics.user]p4:
740 // A conversion of an expression of class type to the same class
741 // type is given Exact Match rank, and a conversion of an
742 // expression of class type to a base class of that type is
743 // given Conversion rank, in spite of the fact that a copy/move
744 // constructor (i.e., a user-defined conversion function) is
745 // called for those cases.
746 QualType FromType = From->getType();
747 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000748 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
749 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000750 ICS.setStandard();
751 ICS.Standard.setAsIdentityConversion();
752 ICS.Standard.setFromType(FromType);
753 ICS.Standard.setAllToTypes(ToType);
754
755 // We don't actually check at this point whether there is a valid
756 // copy/move constructor, since overloading just assumes that it
757 // exists. When we actually perform initialization, we'll find the
758 // appropriate constructor to copy the returned object, if needed.
759 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000760
Douglas Gregor5ab11652010-04-17 22:01:05 +0000761 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000762 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000763 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000764
765 return ICS;
766 }
767
768 if (SuppressUserConversions) {
769 // We're not in the case above, so there is no conversion that
770 // we can perform.
771 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000772 return ICS;
773 }
774
775 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000776 OverloadCandidateSet Conversions(From->getExprLoc());
777 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000778 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000779 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000780
781 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000782 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000783 // C++ [over.ics.user]p4:
784 // A conversion of an expression of class type to the same class
785 // type is given Exact Match rank, and a conversion of an
786 // expression of class type to a base class of that type is
787 // given Conversion rank, in spite of the fact that a copy
788 // constructor (i.e., a user-defined conversion function) is
789 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000790 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000791 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000792 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000793 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
794 QualType ToCanon
795 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000796 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000797 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000798 // Turn this into a "standard" conversion sequence, so that it
799 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000800 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000801 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000802 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000803 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000804 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000805 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000806 ICS.Standard.Second = ICK_Derived_To_Base;
807 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000808 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000809
810 // C++ [over.best.ics]p4:
811 // However, when considering the argument of a user-defined
812 // conversion function that is a candidate by 13.3.1.3 when
813 // invoked for the copying of the temporary in the second step
814 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
815 // 13.3.1.6 in all cases, only standard conversion sequences and
816 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000817 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000818 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000819 }
John McCalle8c8cd22010-01-13 22:30:33 +0000820 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000821 ICS.setAmbiguous();
822 ICS.Ambiguous.setFromType(From->getType());
823 ICS.Ambiguous.setToType(ToType);
824 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
825 Cand != Conversions.end(); ++Cand)
826 if (Cand->Viable)
827 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000828 } else {
John McCall65eb8792010-02-25 01:37:24 +0000829 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000830 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000831
832 return ICS;
833}
834
John McCall5c32be02010-08-24 20:38:10 +0000835bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
836 const InitializedEntity &Entity,
837 Expr *Initializer,
838 bool SuppressUserConversions,
839 bool AllowExplicitConversions,
840 bool InOverloadResolution) {
841 ImplicitConversionSequence ICS
842 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
843 SuppressUserConversions,
844 AllowExplicitConversions,
845 InOverloadResolution);
846 if (ICS.isBad()) return true;
847
848 // Perform the actual conversion.
849 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
850 return false;
851}
852
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000853/// PerformImplicitConversion - Perform an implicit conversion of the
854/// expression From to the type ToType. Returns true if there was an
855/// error, false otherwise. The expression From is replaced with the
856/// converted expression. Flavor is the kind of conversion we're
857/// performing, used in the error message. If @p AllowExplicit,
858/// explicit user-defined conversions are permitted.
859bool
860Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
861 AssignmentAction Action, bool AllowExplicit) {
862 ImplicitConversionSequence ICS;
863 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
864}
865
866bool
867Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
868 AssignmentAction Action, bool AllowExplicit,
869 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000870 ICS = clang::TryImplicitConversion(*this, From, ToType,
871 /*SuppressUserConversions=*/false,
872 AllowExplicit,
873 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000874 return PerformImplicitConversion(From, ToType, ICS, Action);
875}
876
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000877/// \brief Determine whether the conversion from FromType to ToType is a valid
878/// conversion that strips "noreturn" off the nested function type.
879static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
880 QualType ToType, QualType &ResultTy) {
881 if (Context.hasSameUnqualifiedType(FromType, ToType))
882 return false;
883
884 // Strip the noreturn off the type we're converting from; noreturn can
885 // safely be removed.
886 FromType = Context.getNoReturnType(FromType, false);
887 if (!Context.hasSameUnqualifiedType(FromType, ToType))
888 return false;
889
890 ResultTy = FromType;
891 return true;
892}
Douglas Gregor46188682010-05-18 22:42:18 +0000893
894/// \brief Determine whether the conversion from FromType to ToType is a valid
895/// vector conversion.
896///
897/// \param ICK Will be set to the vector conversion kind, if this is a vector
898/// conversion.
899static bool IsVectorConversion(ASTContext &Context, QualType FromType,
900 QualType ToType, ImplicitConversionKind &ICK) {
901 // We need at least one of these types to be a vector type to have a vector
902 // conversion.
903 if (!ToType->isVectorType() && !FromType->isVectorType())
904 return false;
905
906 // Identical types require no conversions.
907 if (Context.hasSameUnqualifiedType(FromType, ToType))
908 return false;
909
910 // There are no conversions between extended vector types, only identity.
911 if (ToType->isExtVectorType()) {
912 // There are no conversions between extended vector types other than the
913 // identity conversion.
914 if (FromType->isExtVectorType())
915 return false;
916
917 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000918 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000919 ICK = ICK_Vector_Splat;
920 return true;
921 }
922 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000923
924 // We can perform the conversion between vector types in the following cases:
925 // 1)vector types are equivalent AltiVec and GCC vector types
926 // 2)lax vector conversions are permitted and the vector types are of the
927 // same size
928 if (ToType->isVectorType() && FromType->isVectorType()) {
929 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000930 (Context.getLangOptions().LaxVectorConversions &&
931 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000932 ICK = ICK_Vector_Conversion;
933 return true;
934 }
Douglas Gregor46188682010-05-18 22:42:18 +0000935 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000936
Douglas Gregor46188682010-05-18 22:42:18 +0000937 return false;
938}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000939
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000940/// IsStandardConversion - Determines whether there is a standard
941/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
942/// expression From to the type ToType. Standard conversion sequences
943/// only consider non-class types; for conversions that involve class
944/// types, use TryImplicitConversion. If a conversion exists, SCS will
945/// contain the standard conversion sequence required to perform this
946/// conversion and this routine will return true. Otherwise, this
947/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000948static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
949 bool InOverloadResolution,
950 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000952
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000953 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000954 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000956 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000957 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000958 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000959
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000960 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000961 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000962 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000963 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000964 return false;
965
Mike Stump11289f42009-09-09 15:08:12 +0000966 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000967 }
968
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 // The first conversion can be an lvalue-to-rvalue conversion,
970 // array-to-pointer conversion, or function-to-pointer conversion
971 // (C++ 4p1).
972
John McCall5c32be02010-08-24 20:38:10 +0000973 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000974 DeclAccessPair AccessPair;
975 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000976 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
977 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000978 // We were able to resolve the address of the overloaded function,
979 // so we can convert to the type of that function.
980 FromType = Fn->getType();
981 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
982 if (!Method->isStatic()) {
983 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000984 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
985 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000986 }
987 }
988
989 // If the "from" expression takes the address of the overloaded
990 // function, update the type of the resulting expression accordingly.
991 if (FromType->getAs<FunctionType>())
992 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000993 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000994 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000995
996 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000997 assert(S.Context.hasSameType(FromType,
998 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +0000999 } else {
1000 return false;
1001 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004 // An lvalue (3.10) of a non-function, non-array type T can be
1005 // converted to an rvalue.
John McCall5c32be02010-08-24 20:38:10 +00001006 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001007 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001008 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001009 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001010 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001011
1012 // If T is a non-class type, the type of the rvalue is the
1013 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001014 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1015 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001016 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001017 } else if (FromType->isArrayType()) {
1018 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001019 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001020
1021 // An lvalue or rvalue of type "array of N T" or "array of unknown
1022 // bound of T" can be converted to an rvalue of type "pointer to
1023 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001024 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025
John McCall5c32be02010-08-24 20:38:10 +00001026 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001028 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001029
1030 // For the purpose of ranking in overload resolution
1031 // (13.3.3.1.1), this conversion is considered an
1032 // array-to-pointer conversion followed by a qualification
1033 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001034 SCS.Second = ICK_Identity;
1035 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001036 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001037 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 }
Mike Stump12b8ce12009-08-04 21:02:39 +00001039 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1040 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001041 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001042
1043 // An lvalue of function type T can be converted to an rvalue of
1044 // type "pointer to T." The result is a pointer to the
1045 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001046 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001047 } else {
1048 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001049 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001050 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001051 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052
1053 // The second conversion can be an integral promotion, floating
1054 // point promotion, integral conversion, floating point conversion,
1055 // floating-integral conversion, pointer conversion,
1056 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001057 // For overloading in C, this can also be a "compatible-type"
1058 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001059 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001060 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001061 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // The unqualified versions of the types are the same: there's no
1063 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001064 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001065 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001066 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001067 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001069 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001070 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001071 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001073 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001074 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001075 SCS.Second = ICK_Complex_Promotion;
1076 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001077 } else if (ToType->isBooleanType() &&
1078 (FromType->isArithmeticType() ||
1079 FromType->isAnyPointerType() ||
1080 FromType->isBlockPointerType() ||
1081 FromType->isMemberPointerType() ||
1082 FromType->isNullPtrType())) {
1083 // Boolean conversions (C++ 4.12).
1084 SCS.Second = ICK_Boolean_Conversion;
1085 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001086 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001087 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001088 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001089 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001090 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001091 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001092 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001093 SCS.Second = ICK_Complex_Conversion;
1094 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001095 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1096 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001097 // Complex-real conversions (C99 6.3.1.7)
1098 SCS.Second = ICK_Complex_Real;
1099 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001100 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001101 // Floating point conversions (C++ 4.8).
1102 SCS.Second = ICK_Floating_Conversion;
1103 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001104 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001105 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001106 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001107 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001108 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001111 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1112 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001113 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001114 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001115 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001116 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1117 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001118 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001119 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001120 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001121 SCS.Second = SecondICK;
1122 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001123 } else if (!S.getLangOptions().CPlusPlus &&
1124 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001125 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001126 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001127 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001128 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001129 // Treat a conversion that strips "noreturn" as an identity conversion.
1130 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001131 } else {
1132 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001133 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001134 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001135 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001136
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001137 QualType CanonFrom;
1138 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001139 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001140 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001141 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001143 CanonFrom = S.Context.getCanonicalType(FromType);
1144 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 } else {
1146 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 SCS.Third = ICK_Identity;
1148
Mike Stump11289f42009-09-09 15:08:12 +00001149 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001150 // [...] Any difference in top-level cv-qualification is
1151 // subsumed by the initialization itself and does not constitute
1152 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001153 CanonFrom = S.Context.getCanonicalType(FromType);
1154 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001155 if (CanonFrom.getLocalUnqualifiedType()
1156 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001157 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1158 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001159 FromType = ToType;
1160 CanonFrom = CanonTo;
1161 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001163 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001164
1165 // If we have not converted the argument type to the parameter type,
1166 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001167 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001168 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001169
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001170 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171}
1172
1173/// IsIntegralPromotion - Determines whether the conversion from the
1174/// expression From (whose potentially-adjusted type is FromType) to
1175/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1176/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001177bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001178 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001179 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001180 if (!To) {
1181 return false;
1182 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183
1184 // An rvalue of type char, signed char, unsigned char, short int, or
1185 // unsigned short int can be converted to an rvalue of type int if
1186 // int can represent all the values of the source type; otherwise,
1187 // the source rvalue can be converted to an rvalue of type unsigned
1188 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001189 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1190 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001191 if (// We can promote any signed, promotable integer type to an int
1192 (FromType->isSignedIntegerType() ||
1193 // We can promote any unsigned integer type whose size is
1194 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001195 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001196 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001198 }
1199
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200 return To->getKind() == BuiltinType::UInt;
1201 }
1202
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001203 // C++0x [conv.prom]p3:
1204 // A prvalue of an unscoped enumeration type whose underlying type is not
1205 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1206 // following types that can represent all the values of the enumeration
1207 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1208 // unsigned int, long int, unsigned long int, long long int, or unsigned
1209 // long long int. If none of the types in that list can represent all the
1210 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1211 // type can be converted to an rvalue a prvalue of the extended integer type
1212 // with lowest integer conversion rank (4.13) greater than the rank of long
1213 // long in which all the values of the enumeration can be represented. If
1214 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001215 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1216 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1217 // provided for a scoped enumeration.
1218 if (FromEnumType->getDecl()->isScoped())
1219 return false;
1220
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001221 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001222 if (ToType->isIntegerType() &&
1223 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001224 return Context.hasSameUnqualifiedType(ToType,
1225 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001226 }
John McCall56774992009-12-09 09:09:27 +00001227
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001228 // C++0x [conv.prom]p2:
1229 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1230 // to an rvalue a prvalue of the first of the following types that can
1231 // represent all the values of its underlying type: int, unsigned int,
1232 // long int, unsigned long int, long long int, or unsigned long long int.
1233 // If none of the types in that list can represent all the values of its
1234 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1235 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1236 // type.
1237 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1238 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239 // Determine whether the type we're converting from is signed or
1240 // unsigned.
1241 bool FromIsSigned;
1242 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001243
1244 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1245 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001246
1247 // The types we'll try to promote to, in the appropriate
1248 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001249 QualType PromoteTypes[6] = {
1250 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001251 Context.LongTy, Context.UnsignedLongTy ,
1252 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001253 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001254 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001255 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1256 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001257 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1259 // We found the type that we can promote to. If this is the
1260 // type we wanted, we have a promotion. Otherwise, no
1261 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001262 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001263 }
1264 }
1265 }
1266
1267 // An rvalue for an integral bit-field (9.6) can be converted to an
1268 // rvalue of type int if int can represent all the values of the
1269 // bit-field; otherwise, it can be converted to unsigned int if
1270 // unsigned int can represent all the values of the bit-field. If
1271 // the bit-field is larger yet, no integral promotion applies to
1272 // it. If the bit-field has an enumerated type, it is treated as any
1273 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001274 // FIXME: We should delay checking of bit-fields until we actually perform the
1275 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001276 using llvm::APSInt;
1277 if (From)
1278 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001279 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001280 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001281 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1282 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1283 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001284
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001285 // Are we promoting to an int from a bitfield that fits in an int?
1286 if (BitWidth < ToSize ||
1287 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1288 return To->getKind() == BuiltinType::Int;
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001291 // Are we promoting to an unsigned int from an unsigned bitfield
1292 // that fits into an unsigned int?
1293 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1294 return To->getKind() == BuiltinType::UInt;
1295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001297 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001298 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001299 }
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001301 // An rvalue of type bool can be converted to an rvalue of type int,
1302 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001303 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001305 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001306
1307 return false;
1308}
1309
1310/// IsFloatingPointPromotion - Determines whether the conversion from
1311/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1312/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001313bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001314 /// An rvalue of type float can be converted to an rvalue of type
1315 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001316 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1317 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318 if (FromBuiltin->getKind() == BuiltinType::Float &&
1319 ToBuiltin->getKind() == BuiltinType::Double)
1320 return true;
1321
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001322 // C99 6.3.1.5p1:
1323 // When a float is promoted to double or long double, or a
1324 // double is promoted to long double [...].
1325 if (!getLangOptions().CPlusPlus &&
1326 (FromBuiltin->getKind() == BuiltinType::Float ||
1327 FromBuiltin->getKind() == BuiltinType::Double) &&
1328 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1329 return true;
1330 }
1331
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001332 return false;
1333}
1334
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001335/// \brief Determine if a conversion is a complex promotion.
1336///
1337/// A complex promotion is defined as a complex -> complex conversion
1338/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001339/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001340bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001341 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001342 if (!FromComplex)
1343 return false;
1344
John McCall9dd450b2009-09-21 23:43:11 +00001345 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001346 if (!ToComplex)
1347 return false;
1348
1349 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001350 ToComplex->getElementType()) ||
1351 IsIntegralPromotion(0, FromComplex->getElementType(),
1352 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001353}
1354
Douglas Gregor237f96c2008-11-26 23:31:11 +00001355/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1356/// the pointer type FromPtr to a pointer to type ToPointee, with the
1357/// same type qualifiers as FromPtr has on its pointee type. ToType,
1358/// if non-empty, will be a pointer to ToType that may or may not have
1359/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001360static QualType
1361BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001362 QualType ToPointee, QualType ToType,
1363 ASTContext &Context) {
1364 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1365 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001366 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001367
1368 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001369 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001370 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001371 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001372 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001373
1374 // Build a pointer to ToPointee. It has the right qualifiers
1375 // already.
1376 return Context.getPointerType(ToPointee);
1377 }
1378
1379 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001380 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001381 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1382 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001383}
1384
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001385/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1386/// the FromType, which is an objective-c pointer, to ToType, which may or may
1387/// not have the right set of qualifiers.
1388static QualType
1389BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1390 QualType ToType,
1391 ASTContext &Context) {
1392 QualType CanonFromType = Context.getCanonicalType(FromType);
1393 QualType CanonToType = Context.getCanonicalType(ToType);
1394 Qualifiers Quals = CanonFromType.getQualifiers();
1395
1396 // Exact qualifier match -> return the pointer type we're converting to.
1397 if (CanonToType.getLocalQualifiers() == Quals)
1398 return ToType;
1399
1400 // Just build a canonical type that has the right qualifiers.
1401 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1402}
1403
Mike Stump11289f42009-09-09 15:08:12 +00001404static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001405 bool InOverloadResolution,
1406 ASTContext &Context) {
1407 // Handle value-dependent integral null pointer constants correctly.
1408 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1409 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001410 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001411 return !InOverloadResolution;
1412
Douglas Gregor56751b52009-09-25 04:25:58 +00001413 return Expr->isNullPointerConstant(Context,
1414 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1415 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001416}
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001418/// IsPointerConversion - Determines whether the conversion of the
1419/// expression From, which has the (possibly adjusted) type FromType,
1420/// can be converted to the type ToType via a pointer conversion (C++
1421/// 4.10). If so, returns true and places the converted type (that
1422/// might differ from ToType in its cv-qualifiers at some level) into
1423/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001424///
Douglas Gregora29dc052008-11-27 01:19:21 +00001425/// This routine also supports conversions to and from block pointers
1426/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1427/// pointers to interfaces. FIXME: Once we've determined the
1428/// appropriate overloading rules for Objective-C, we may want to
1429/// split the Objective-C checks into a different routine; however,
1430/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001431/// conversions, so for now they live here. IncompatibleObjC will be
1432/// set if the conversion is an allowed Objective-C conversion that
1433/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001434bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001435 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001436 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001437 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001438 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001439 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1440 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001441
Mike Stump11289f42009-09-09 15:08:12 +00001442 // Conversion from a null pointer constant to any Objective-C pointer type.
1443 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001444 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001445 ConvertedType = ToType;
1446 return true;
1447 }
1448
Douglas Gregor231d1c62008-11-27 00:15:41 +00001449 // Blocks: Block pointers can be converted to void*.
1450 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001451 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001452 ConvertedType = ToType;
1453 return true;
1454 }
1455 // Blocks: A null pointer constant can be converted to a block
1456 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001457 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001458 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001459 ConvertedType = ToType;
1460 return true;
1461 }
1462
Sebastian Redl576fd422009-05-10 18:38:11 +00001463 // If the left-hand-side is nullptr_t, the right side can be a null
1464 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001465 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001466 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001467 ConvertedType = ToType;
1468 return true;
1469 }
1470
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001471 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472 if (!ToTypePtr)
1473 return false;
1474
1475 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001476 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001477 ConvertedType = ToType;
1478 return true;
1479 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001480
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001481 // Beyond this point, both types need to be pointers
1482 // , including objective-c pointers.
1483 QualType ToPointeeType = ToTypePtr->getPointeeType();
1484 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1485 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1486 ToType, Context);
1487 return true;
1488
1489 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001490 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001491 if (!FromTypePtr)
1492 return false;
1493
1494 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001495
Douglas Gregorfb640862010-08-18 21:25:30 +00001496 // If the unqualified pointee types are the same, this can't be a
1497 // pointer conversion, so don't do all of the work below.
1498 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1499 return false;
1500
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 // An rvalue of type "pointer to cv T," where T is an object type,
1502 // can be converted to an rvalue of type "pointer to cv void" (C++
1503 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001504 if (FromPointeeType->isIncompleteOrObjectType() &&
1505 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001506 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001507 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001508 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001509 return true;
1510 }
1511
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001512 // When we're overloading in C, we allow a special kind of pointer
1513 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001514 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001515 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001516 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001517 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001518 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001519 return true;
1520 }
1521
Douglas Gregor5c407d92008-10-23 00:40:37 +00001522 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001523 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001524 // An rvalue of type "pointer to cv D," where D is a class type,
1525 // can be converted to an rvalue of type "pointer to cv B," where
1526 // B is a base class (clause 10) of D. If B is an inaccessible
1527 // (clause 11) or ambiguous (10.2) base class of D, a program that
1528 // necessitates this conversion is ill-formed. The result of the
1529 // conversion is a pointer to the base class sub-object of the
1530 // derived class object. The null pointer value is converted to
1531 // the null pointer value of the destination type.
1532 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001533 // Note that we do not check for ambiguity or inaccessibility
1534 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001535 if (getLangOptions().CPlusPlus &&
1536 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001537 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001538 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001540 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001541 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001542 ToType, Context);
1543 return true;
1544 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001545
Douglas Gregora119f102008-12-19 19:13:09 +00001546 return false;
1547}
1548
1549/// isObjCPointerConversion - Determines whether this is an
1550/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1551/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001552bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001553 QualType& ConvertedType,
1554 bool &IncompatibleObjC) {
1555 if (!getLangOptions().ObjC1)
1556 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001557
Steve Naroff7cae42b2009-07-10 23:34:53 +00001558 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001559 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001560 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001561 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001562
Steve Naroff7cae42b2009-07-10 23:34:53 +00001563 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001564 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001565 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001566 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001567 ConvertedType = ToType;
1568 return true;
1569 }
1570 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001571 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001572 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001573 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001574 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001575 ConvertedType = ToType;
1576 return true;
1577 }
1578 // Objective C++: We're able to convert from a pointer to an
1579 // interface to a pointer to a different interface.
1580 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001581 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1582 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1583 if (getLangOptions().CPlusPlus && LHS && RHS &&
1584 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1585 FromObjCPtr->getPointeeType()))
1586 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001587 ConvertedType = ToType;
1588 return true;
1589 }
1590
1591 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1592 // Okay: this is some kind of implicit downcast of Objective-C
1593 // interfaces, which is permitted. However, we're going to
1594 // complain about it.
1595 IncompatibleObjC = true;
1596 ConvertedType = FromType;
1597 return true;
1598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001600 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001601 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001602 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001603 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001604 else if (const BlockPointerType *ToBlockPtr =
1605 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001606 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001607 // to a block pointer type.
1608 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1609 ConvertedType = ToType;
1610 return true;
1611 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001612 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001613 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001614 else if (FromType->getAs<BlockPointerType>() &&
1615 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1616 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001617 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001618 ConvertedType = ToType;
1619 return true;
1620 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001621 else
Douglas Gregora119f102008-12-19 19:13:09 +00001622 return false;
1623
Douglas Gregor033f56d2008-12-23 00:53:59 +00001624 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001625 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001626 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001627 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001628 FromPointeeType = FromBlockPtr->getPointeeType();
1629 else
Douglas Gregora119f102008-12-19 19:13:09 +00001630 return false;
1631
Douglas Gregora119f102008-12-19 19:13:09 +00001632 // If we have pointers to pointers, recursively check whether this
1633 // is an Objective-C conversion.
1634 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1635 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1636 IncompatibleObjC)) {
1637 // We always complain about this conversion.
1638 IncompatibleObjC = true;
1639 ConvertedType = ToType;
1640 return true;
1641 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001642 // Allow conversion of pointee being objective-c pointer to another one;
1643 // as in I* to id.
1644 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1645 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1646 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1647 IncompatibleObjC)) {
1648 ConvertedType = ToType;
1649 return true;
1650 }
1651
Douglas Gregor033f56d2008-12-23 00:53:59 +00001652 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001653 // differences in the argument and result types are in Objective-C
1654 // pointer conversions. If so, we permit the conversion (but
1655 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001656 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001657 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001658 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001659 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001660 if (FromFunctionType && ToFunctionType) {
1661 // If the function types are exactly the same, this isn't an
1662 // Objective-C pointer conversion.
1663 if (Context.getCanonicalType(FromPointeeType)
1664 == Context.getCanonicalType(ToPointeeType))
1665 return false;
1666
1667 // Perform the quick checks that will tell us whether these
1668 // function types are obviously different.
1669 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1670 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1671 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1672 return false;
1673
1674 bool HasObjCConversion = false;
1675 if (Context.getCanonicalType(FromFunctionType->getResultType())
1676 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1677 // Okay, the types match exactly. Nothing to do.
1678 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1679 ToFunctionType->getResultType(),
1680 ConvertedType, IncompatibleObjC)) {
1681 // Okay, we have an Objective-C pointer conversion.
1682 HasObjCConversion = true;
1683 } else {
1684 // Function types are too different. Abort.
1685 return false;
1686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Douglas Gregora119f102008-12-19 19:13:09 +00001688 // Check argument types.
1689 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1690 ArgIdx != NumArgs; ++ArgIdx) {
1691 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1692 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1693 if (Context.getCanonicalType(FromArgType)
1694 == Context.getCanonicalType(ToArgType)) {
1695 // Okay, the types match exactly. Nothing to do.
1696 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1697 ConvertedType, IncompatibleObjC)) {
1698 // Okay, we have an Objective-C pointer conversion.
1699 HasObjCConversion = true;
1700 } else {
1701 // Argument types are too different. Abort.
1702 return false;
1703 }
1704 }
1705
1706 if (HasObjCConversion) {
1707 // We had an Objective-C conversion. Allow this pointer
1708 // conversion, but complain about it.
1709 ConvertedType = ToType;
1710 IncompatibleObjC = true;
1711 return true;
1712 }
1713 }
1714
Sebastian Redl72b597d2009-01-25 19:43:20 +00001715 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001716}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001717
1718/// FunctionArgTypesAreEqual - This routine checks two function proto types
1719/// for equlity of their argument types. Caller has already checked that
1720/// they have same number of arguments. This routine assumes that Objective-C
1721/// pointer types which only differ in their protocol qualifiers are equal.
1722bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1723 FunctionProtoType* NewType){
1724 if (!getLangOptions().ObjC1)
1725 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1726 NewType->arg_type_begin());
1727
1728 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1729 N = NewType->arg_type_begin(),
1730 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1731 QualType ToType = (*O);
1732 QualType FromType = (*N);
1733 if (ToType != FromType) {
1734 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1735 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001736 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1737 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1738 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1739 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001740 continue;
1741 }
John McCall8b07ec22010-05-15 11:32:37 +00001742 else if (const ObjCObjectPointerType *PTTo =
1743 ToType->getAs<ObjCObjectPointerType>()) {
1744 if (const ObjCObjectPointerType *PTFr =
1745 FromType->getAs<ObjCObjectPointerType>())
1746 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1747 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001748 }
1749 return false;
1750 }
1751 }
1752 return true;
1753}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001754
Douglas Gregor39c16d42008-10-24 04:54:22 +00001755/// CheckPointerConversion - Check the pointer conversion from the
1756/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001757/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001758/// conversions for which IsPointerConversion has already returned
1759/// true. It returns true and produces a diagnostic if there was an
1760/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001761bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001762 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001763 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001764 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001765 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001766 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001767
John McCall8cb679e2010-11-15 09:13:47 +00001768 Kind = CK_BitCast;
1769
Douglas Gregor4038cf42010-06-08 17:35:15 +00001770 if (CXXBoolLiteralExpr* LitBool
1771 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001772 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001773 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1774 << ToType;
1775
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001776 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1777 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001778 QualType FromPointeeType = FromPtrType->getPointeeType(),
1779 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001780
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001781 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1782 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001783 // We must have a derived-to-base conversion. Check an
1784 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001785 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1786 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001787 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001788 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001789 return true;
1790
1791 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001792 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001793 }
1794 }
Mike Stump11289f42009-09-09 15:08:12 +00001795 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001796 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001797 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001798 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001799 // Objective-C++ conversions are always okay.
1800 // FIXME: We should have a different class of conversions for the
1801 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001802 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001803 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001804 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001805 }
John McCall8cb679e2010-11-15 09:13:47 +00001806
1807 // We shouldn't fall into this case unless it's valid for other
1808 // reasons.
1809 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1810 Kind = CK_NullToPointer;
1811
Douglas Gregor39c16d42008-10-24 04:54:22 +00001812 return false;
1813}
1814
Sebastian Redl72b597d2009-01-25 19:43:20 +00001815/// IsMemberPointerConversion - Determines whether the conversion of the
1816/// expression From, which has the (possibly adjusted) type FromType, can be
1817/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1818/// If so, returns true and places the converted type (that might differ from
1819/// ToType in its cv-qualifiers at some level) into ConvertedType.
1820bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001821 QualType ToType,
1822 bool InOverloadResolution,
1823 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001824 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001825 if (!ToTypePtr)
1826 return false;
1827
1828 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001829 if (From->isNullPointerConstant(Context,
1830 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1831 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001832 ConvertedType = ToType;
1833 return true;
1834 }
1835
1836 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001837 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001838 if (!FromTypePtr)
1839 return false;
1840
1841 // A pointer to member of B can be converted to a pointer to member of D,
1842 // where D is derived from B (C++ 4.11p2).
1843 QualType FromClass(FromTypePtr->getClass(), 0);
1844 QualType ToClass(ToTypePtr->getClass(), 0);
1845 // FIXME: What happens when these are dependent? Is this function even called?
1846
1847 if (IsDerivedFrom(ToClass, FromClass)) {
1848 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1849 ToClass.getTypePtr());
1850 return true;
1851 }
1852
1853 return false;
1854}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001855
Sebastian Redl72b597d2009-01-25 19:43:20 +00001856/// CheckMemberPointerConversion - Check the member pointer conversion from the
1857/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001858/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001859/// for which IsMemberPointerConversion has already returned true. It returns
1860/// true and produces a diagnostic if there was an error, or returns false
1861/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001862bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001863 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001864 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001865 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001866 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001868 if (!FromPtrType) {
1869 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001870 assert(From->isNullPointerConstant(Context,
1871 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001872 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001873 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001874 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001875 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001876
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001877 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001878 assert(ToPtrType && "No member pointer cast has a target type "
1879 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001880
Sebastian Redled8f2002009-01-28 18:33:18 +00001881 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1882 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001883
Sebastian Redled8f2002009-01-28 18:33:18 +00001884 // FIXME: What about dependent types?
1885 assert(FromClass->isRecordType() && "Pointer into non-class.");
1886 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001887
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001888 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001889 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001890 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1891 assert(DerivationOkay &&
1892 "Should not have been called if derivation isn't OK.");
1893 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001894
Sebastian Redled8f2002009-01-28 18:33:18 +00001895 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1896 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001897 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1898 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1899 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1900 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001901 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001902
Douglas Gregor89ee6822009-02-28 01:32:25 +00001903 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001904 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1905 << FromClass << ToClass << QualType(VBase, 0)
1906 << From->getSourceRange();
1907 return true;
1908 }
1909
John McCall5b0829a2010-02-10 09:31:12 +00001910 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001911 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1912 Paths.front(),
1913 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001914
Anders Carlssond7923c62009-08-22 23:33:40 +00001915 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001916 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001917 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001918 return false;
1919}
1920
Douglas Gregor9a657932008-10-21 23:43:52 +00001921/// IsQualificationConversion - Determines whether the conversion from
1922/// an rvalue of type FromType to ToType is a qualification conversion
1923/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001924bool
1925Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001926 FromType = Context.getCanonicalType(FromType);
1927 ToType = Context.getCanonicalType(ToType);
1928
1929 // If FromType and ToType are the same type, this is not a
1930 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001931 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001932 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001933
Douglas Gregor9a657932008-10-21 23:43:52 +00001934 // (C++ 4.4p4):
1935 // A conversion can add cv-qualifiers at levels other than the first
1936 // in multi-level pointers, subject to the following rules: [...]
1937 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001938 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001939 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001940 // Within each iteration of the loop, we check the qualifiers to
1941 // determine if this still looks like a qualification
1942 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001943 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001944 // until there are no more pointers or pointers-to-members left to
1945 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001946 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001947
1948 // -- for every j > 0, if const is in cv 1,j then const is in cv
1949 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001950 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001951 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001952
Douglas Gregor9a657932008-10-21 23:43:52 +00001953 // -- if the cv 1,j and cv 2,j are different, then const is in
1954 // every cv for 0 < k < j.
1955 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001956 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001957 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001958
Douglas Gregor9a657932008-10-21 23:43:52 +00001959 // Keep track of whether all prior cv-qualifiers in the "to" type
1960 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001961 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001962 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001963 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001964
1965 // We are left with FromType and ToType being the pointee types
1966 // after unwrapping the original FromType and ToType the same number
1967 // of types. If we unwrapped any pointers, and if FromType and
1968 // ToType have the same unqualified type (since we checked
1969 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001970 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001971}
1972
Douglas Gregor576e98c2009-01-30 23:27:23 +00001973/// Determines whether there is a user-defined conversion sequence
1974/// (C++ [over.ics.user]) that converts expression From to the type
1975/// ToType. If such a conversion exists, User will contain the
1976/// user-defined conversion sequence that performs such a conversion
1977/// and this routine will return true. Otherwise, this routine returns
1978/// false and User is unspecified.
1979///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001980/// \param AllowExplicit true if the conversion should consider C++0x
1981/// "explicit" conversion functions as well as non-explicit conversion
1982/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001983static OverloadingResult
1984IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1985 UserDefinedConversionSequence& User,
1986 OverloadCandidateSet& CandidateSet,
1987 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001988 // Whether we will only visit constructors.
1989 bool ConstructorsOnly = false;
1990
1991 // If the type we are conversion to is a class type, enumerate its
1992 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001993 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001994 // C++ [over.match.ctor]p1:
1995 // When objects of class type are direct-initialized (8.5), or
1996 // copy-initialized from an expression of the same or a
1997 // derived class type (8.5), overload resolution selects the
1998 // constructor. [...] For copy-initialization, the candidate
1999 // functions are all the converting constructors (12.3.1) of
2000 // that class. The argument list is the expression-list within
2001 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002002 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002003 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002004 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002005 ConstructorsOnly = true;
2006
John McCall5c32be02010-08-24 20:38:10 +00002007 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002008 // We're not going to find any constructors.
2009 } else if (CXXRecordDecl *ToRecordDecl
2010 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002011 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002012 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002013 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002014 NamedDecl *D = *Con;
2015 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2016
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002017 // Find the constructor (which may be a template).
2018 CXXConstructorDecl *Constructor = 0;
2019 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002020 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002021 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002022 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002023 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2024 else
John McCalla0296f72010-03-19 07:35:19 +00002025 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002026
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002027 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002028 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002029 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002030 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2031 /*ExplicitArgs*/ 0,
2032 &From, 1, CandidateSet,
2033 /*SuppressUserConversions=*/
2034 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002035 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002036 // Allow one user-defined conversion when user specifies a
2037 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002038 S.AddOverloadCandidate(Constructor, FoundDecl,
2039 &From, 1, CandidateSet,
2040 /*SuppressUserConversions=*/
2041 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002042 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002043 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002044 }
2045 }
2046
Douglas Gregor5ab11652010-04-17 22:01:05 +00002047 // Enumerate conversion functions, if we're allowed to.
2048 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002049 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2050 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002051 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002052 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002053 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002054 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002055 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2056 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002057 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002058 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002059 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002060 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002061 DeclAccessPair FoundDecl = I.getPair();
2062 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002063 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2064 if (isa<UsingShadowDecl>(D))
2065 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2066
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002067 CXXConversionDecl *Conv;
2068 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002069 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2070 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002071 else
John McCallda4458e2010-03-31 01:36:47 +00002072 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002073
2074 if (AllowExplicit || !Conv->isExplicit()) {
2075 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002076 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2077 ActingContext, From, ToType,
2078 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002079 else
John McCall5c32be02010-08-24 20:38:10 +00002080 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2081 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002082 }
2083 }
2084 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002085 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002086
2087 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002088 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002089 case OR_Success:
2090 // Record the standard conversion we used and the conversion function.
2091 if (CXXConstructorDecl *Constructor
2092 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2093 // C++ [over.ics.user]p1:
2094 // If the user-defined conversion is specified by a
2095 // constructor (12.3.1), the initial standard conversion
2096 // sequence converts the source type to the type required by
2097 // the argument of the constructor.
2098 //
2099 QualType ThisType = Constructor->getThisType(S.Context);
2100 if (Best->Conversions[0].isEllipsis())
2101 User.EllipsisConversion = true;
2102 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002103 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002104 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002105 }
John McCall5c32be02010-08-24 20:38:10 +00002106 User.ConversionFunction = Constructor;
2107 User.After.setAsIdentityConversion();
2108 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2109 User.After.setAllToTypes(ToType);
2110 return OR_Success;
2111 } else if (CXXConversionDecl *Conversion
2112 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2113 // C++ [over.ics.user]p1:
2114 //
2115 // [...] If the user-defined conversion is specified by a
2116 // conversion function (12.3.2), the initial standard
2117 // conversion sequence converts the source type to the
2118 // implicit object parameter of the conversion function.
2119 User.Before = Best->Conversions[0].Standard;
2120 User.ConversionFunction = Conversion;
2121 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002122
John McCall5c32be02010-08-24 20:38:10 +00002123 // C++ [over.ics.user]p2:
2124 // The second standard conversion sequence converts the
2125 // result of the user-defined conversion to the target type
2126 // for the sequence. Since an implicit conversion sequence
2127 // is an initialization, the special rules for
2128 // initialization by user-defined conversion apply when
2129 // selecting the best user-defined conversion for a
2130 // user-defined conversion sequence (see 13.3.3 and
2131 // 13.3.3.1).
2132 User.After = Best->FinalConversion;
2133 return OR_Success;
2134 } else {
2135 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002136 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002137 }
2138
John McCall5c32be02010-08-24 20:38:10 +00002139 case OR_No_Viable_Function:
2140 return OR_No_Viable_Function;
2141 case OR_Deleted:
2142 // No conversion here! We're done.
2143 return OR_Deleted;
2144
2145 case OR_Ambiguous:
2146 return OR_Ambiguous;
2147 }
2148
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002149 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002150}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002151
2152bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002153Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002154 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002155 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002156 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002157 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002158 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002159 if (OvResult == OR_Ambiguous)
2160 Diag(From->getSourceRange().getBegin(),
2161 diag::err_typecheck_ambiguous_condition)
2162 << From->getType() << ToType << From->getSourceRange();
2163 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2164 Diag(From->getSourceRange().getBegin(),
2165 diag::err_typecheck_nonviable_condition)
2166 << From->getType() << ToType << From->getSourceRange();
2167 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002168 return false;
John McCall5c32be02010-08-24 20:38:10 +00002169 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002170 return true;
2171}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002173/// CompareImplicitConversionSequences - Compare two implicit
2174/// conversion sequences to determine whether one is better than the
2175/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002176static ImplicitConversionSequence::CompareKind
2177CompareImplicitConversionSequences(Sema &S,
2178 const ImplicitConversionSequence& ICS1,
2179 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002180{
2181 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2182 // conversion sequences (as defined in 13.3.3.1)
2183 // -- a standard conversion sequence (13.3.3.1.1) is a better
2184 // conversion sequence than a user-defined conversion sequence or
2185 // an ellipsis conversion sequence, and
2186 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2187 // conversion sequence than an ellipsis conversion sequence
2188 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002189 //
John McCall0d1da222010-01-12 00:44:57 +00002190 // C++0x [over.best.ics]p10:
2191 // For the purpose of ranking implicit conversion sequences as
2192 // described in 13.3.3.2, the ambiguous conversion sequence is
2193 // treated as a user-defined sequence that is indistinguishable
2194 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002195 if (ICS1.getKindRank() < ICS2.getKindRank())
2196 return ImplicitConversionSequence::Better;
2197 else if (ICS2.getKindRank() < ICS1.getKindRank())
2198 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002199
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002200 // The following checks require both conversion sequences to be of
2201 // the same kind.
2202 if (ICS1.getKind() != ICS2.getKind())
2203 return ImplicitConversionSequence::Indistinguishable;
2204
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002205 // Two implicit conversion sequences of the same form are
2206 // indistinguishable conversion sequences unless one of the
2207 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002208 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002209 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002210 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211 // User-defined conversion sequence U1 is a better conversion
2212 // sequence than another user-defined conversion sequence U2 if
2213 // they contain the same user-defined conversion function or
2214 // constructor and if the second standard conversion sequence of
2215 // U1 is better than the second standard conversion sequence of
2216 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002217 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002218 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002219 return CompareStandardConversionSequences(S,
2220 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002221 ICS2.UserDefined.After);
2222 }
2223
2224 return ImplicitConversionSequence::Indistinguishable;
2225}
2226
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002227static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2228 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2229 Qualifiers Quals;
2230 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2231 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2232 }
2233
2234 return Context.hasSameUnqualifiedType(T1, T2);
2235}
2236
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002237// Per 13.3.3.2p3, compare the given standard conversion sequences to
2238// determine if one is a proper subset of the other.
2239static ImplicitConversionSequence::CompareKind
2240compareStandardConversionSubsets(ASTContext &Context,
2241 const StandardConversionSequence& SCS1,
2242 const StandardConversionSequence& SCS2) {
2243 ImplicitConversionSequence::CompareKind Result
2244 = ImplicitConversionSequence::Indistinguishable;
2245
Douglas Gregore87561a2010-05-23 22:10:15 +00002246 // the identity conversion sequence is considered to be a subsequence of
2247 // any non-identity conversion sequence
2248 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2249 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2250 return ImplicitConversionSequence::Better;
2251 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2252 return ImplicitConversionSequence::Worse;
2253 }
2254
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002255 if (SCS1.Second != SCS2.Second) {
2256 if (SCS1.Second == ICK_Identity)
2257 Result = ImplicitConversionSequence::Better;
2258 else if (SCS2.Second == ICK_Identity)
2259 Result = ImplicitConversionSequence::Worse;
2260 else
2261 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002262 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002263 return ImplicitConversionSequence::Indistinguishable;
2264
2265 if (SCS1.Third == SCS2.Third) {
2266 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2267 : ImplicitConversionSequence::Indistinguishable;
2268 }
2269
2270 if (SCS1.Third == ICK_Identity)
2271 return Result == ImplicitConversionSequence::Worse
2272 ? ImplicitConversionSequence::Indistinguishable
2273 : ImplicitConversionSequence::Better;
2274
2275 if (SCS2.Third == ICK_Identity)
2276 return Result == ImplicitConversionSequence::Better
2277 ? ImplicitConversionSequence::Indistinguishable
2278 : ImplicitConversionSequence::Worse;
2279
2280 return ImplicitConversionSequence::Indistinguishable;
2281}
2282
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002283/// CompareStandardConversionSequences - Compare two standard
2284/// conversion sequences to determine whether one is better than the
2285/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002286static ImplicitConversionSequence::CompareKind
2287CompareStandardConversionSequences(Sema &S,
2288 const StandardConversionSequence& SCS1,
2289 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002290{
2291 // Standard conversion sequence S1 is a better conversion sequence
2292 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2293
2294 // -- S1 is a proper subsequence of S2 (comparing the conversion
2295 // sequences in the canonical form defined by 13.3.3.1.1,
2296 // excluding any Lvalue Transformation; the identity conversion
2297 // sequence is considered to be a subsequence of any
2298 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002299 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002300 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002301 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002302
2303 // -- the rank of S1 is better than the rank of S2 (by the rules
2304 // defined below), or, if not that,
2305 ImplicitConversionRank Rank1 = SCS1.getRank();
2306 ImplicitConversionRank Rank2 = SCS2.getRank();
2307 if (Rank1 < Rank2)
2308 return ImplicitConversionSequence::Better;
2309 else if (Rank2 < Rank1)
2310 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002311
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002312 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2313 // are indistinguishable unless one of the following rules
2314 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002315
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002316 // A conversion that is not a conversion of a pointer, or
2317 // pointer to member, to bool is better than another conversion
2318 // that is such a conversion.
2319 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2320 return SCS2.isPointerConversionToBool()
2321 ? ImplicitConversionSequence::Better
2322 : ImplicitConversionSequence::Worse;
2323
Douglas Gregor5c407d92008-10-23 00:40:37 +00002324 // C++ [over.ics.rank]p4b2:
2325 //
2326 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002327 // conversion of B* to A* is better than conversion of B* to
2328 // void*, and conversion of A* to void* is better than conversion
2329 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002330 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002331 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002332 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002333 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002334 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2335 // Exactly one of the conversion sequences is a conversion to
2336 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002337 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2338 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002339 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2340 // Neither conversion sequence converts to a void pointer; compare
2341 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002342 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002343 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002344 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002345 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2346 // Both conversion sequences are conversions to void
2347 // pointers. Compare the source types to determine if there's an
2348 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002349 QualType FromType1 = SCS1.getFromType();
2350 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002351
2352 // Adjust the types we're converting from via the array-to-pointer
2353 // conversion, if we need to.
2354 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002355 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002356 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002357 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002358
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002359 QualType FromPointee1
2360 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2361 QualType FromPointee2
2362 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002363
John McCall5c32be02010-08-24 20:38:10 +00002364 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002365 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002366 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002367 return ImplicitConversionSequence::Worse;
2368
2369 // Objective-C++: If one interface is more specific than the
2370 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002371 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2372 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002373 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002374 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002375 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002376 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002377 return ImplicitConversionSequence::Worse;
2378 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002379 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002380
2381 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2382 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002383 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002384 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002385 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002386
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002387 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002388 // C++0x [over.ics.rank]p3b4:
2389 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2390 // implicit object parameter of a non-static member function declared
2391 // without a ref-qualifier, and S1 binds an rvalue reference to an
2392 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002393 // FIXME: We don't know if we're dealing with the implicit object parameter,
2394 // or if the member function in this case has a ref qualifier.
2395 // (Of course, we don't have ref qualifiers yet.)
2396 if (SCS1.RRefBinding != SCS2.RRefBinding)
2397 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2398 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002399
2400 // C++ [over.ics.rank]p3b4:
2401 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2402 // which the references refer are the same type except for
2403 // top-level cv-qualifiers, and the type to which the reference
2404 // initialized by S2 refers is more cv-qualified than the type
2405 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002406 QualType T1 = SCS1.getToType(2);
2407 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002408 T1 = S.Context.getCanonicalType(T1);
2409 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002410 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002411 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2412 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002413 if (UnqualT1 == UnqualT2) {
2414 // If the type is an array type, promote the element qualifiers to the type
2415 // for comparison.
2416 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002417 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002418 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002419 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002420 if (T2.isMoreQualifiedThan(T1))
2421 return ImplicitConversionSequence::Better;
2422 else if (T1.isMoreQualifiedThan(T2))
2423 return ImplicitConversionSequence::Worse;
2424 }
2425 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002426
2427 return ImplicitConversionSequence::Indistinguishable;
2428}
2429
2430/// CompareQualificationConversions - Compares two standard conversion
2431/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002432/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2433ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002434CompareQualificationConversions(Sema &S,
2435 const StandardConversionSequence& SCS1,
2436 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002437 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002438 // -- S1 and S2 differ only in their qualification conversion and
2439 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2440 // cv-qualification signature of type T1 is a proper subset of
2441 // the cv-qualification signature of type T2, and S1 is not the
2442 // deprecated string literal array-to-pointer conversion (4.2).
2443 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2444 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2445 return ImplicitConversionSequence::Indistinguishable;
2446
2447 // FIXME: the example in the standard doesn't use a qualification
2448 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002449 QualType T1 = SCS1.getToType(2);
2450 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002451 T1 = S.Context.getCanonicalType(T1);
2452 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002453 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002454 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2455 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002456
2457 // If the types are the same, we won't learn anything by unwrapped
2458 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002459 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002460 return ImplicitConversionSequence::Indistinguishable;
2461
Chandler Carruth607f38e2009-12-29 07:16:59 +00002462 // If the type is an array type, promote the element qualifiers to the type
2463 // for comparison.
2464 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002465 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002466 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002467 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002468
Mike Stump11289f42009-09-09 15:08:12 +00002469 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002470 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002471 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002472 // Within each iteration of the loop, we check the qualifiers to
2473 // determine if this still looks like a qualification
2474 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002475 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002476 // until there are no more pointers or pointers-to-members left
2477 // to unwrap. This essentially mimics what
2478 // IsQualificationConversion does, but here we're checking for a
2479 // strict subset of qualifiers.
2480 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2481 // The qualifiers are the same, so this doesn't tell us anything
2482 // about how the sequences rank.
2483 ;
2484 else if (T2.isMoreQualifiedThan(T1)) {
2485 // T1 has fewer qualifiers, so it could be the better sequence.
2486 if (Result == ImplicitConversionSequence::Worse)
2487 // Neither has qualifiers that are a subset of the other's
2488 // qualifiers.
2489 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002490
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002491 Result = ImplicitConversionSequence::Better;
2492 } else if (T1.isMoreQualifiedThan(T2)) {
2493 // T2 has fewer qualifiers, so it could be the better sequence.
2494 if (Result == ImplicitConversionSequence::Better)
2495 // Neither has qualifiers that are a subset of the other's
2496 // qualifiers.
2497 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002498
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002499 Result = ImplicitConversionSequence::Worse;
2500 } else {
2501 // Qualifiers are disjoint.
2502 return ImplicitConversionSequence::Indistinguishable;
2503 }
2504
2505 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002506 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002507 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002508 }
2509
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002510 // Check that the winning standard conversion sequence isn't using
2511 // the deprecated string literal array to pointer conversion.
2512 switch (Result) {
2513 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002514 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002515 Result = ImplicitConversionSequence::Indistinguishable;
2516 break;
2517
2518 case ImplicitConversionSequence::Indistinguishable:
2519 break;
2520
2521 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002522 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002523 Result = ImplicitConversionSequence::Indistinguishable;
2524 break;
2525 }
2526
2527 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002528}
2529
Douglas Gregor5c407d92008-10-23 00:40:37 +00002530/// CompareDerivedToBaseConversions - Compares two standard conversion
2531/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002532/// various kinds of derived-to-base conversions (C++
2533/// [over.ics.rank]p4b3). As part of these checks, we also look at
2534/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002535ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002536CompareDerivedToBaseConversions(Sema &S,
2537 const StandardConversionSequence& SCS1,
2538 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002539 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002540 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002541 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002542 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002543
2544 // Adjust the types we're converting from via the array-to-pointer
2545 // conversion, if we need to.
2546 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002547 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002548 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002549 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002550
2551 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002552 FromType1 = S.Context.getCanonicalType(FromType1);
2553 ToType1 = S.Context.getCanonicalType(ToType1);
2554 FromType2 = S.Context.getCanonicalType(FromType2);
2555 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002556
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002557 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002558 //
2559 // If class B is derived directly or indirectly from class A and
2560 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002561 //
2562 // For Objective-C, we let A, B, and C also be Objective-C
2563 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002564
2565 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002566 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002567 SCS2.Second == ICK_Pointer_Conversion &&
2568 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2569 FromType1->isPointerType() && FromType2->isPointerType() &&
2570 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002571 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002572 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002573 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002574 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002575 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002576 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002577 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002578 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002579
John McCall8b07ec22010-05-15 11:32:37 +00002580 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2581 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2582 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2583 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002584
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002585 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002586 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002587 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002588 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002589 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002590 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002591
2592 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002593 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002594 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002595 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002596 return ImplicitConversionSequence::Worse;
2597 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002598 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002599
2600 // -- conversion of B* to A* is better than conversion of C* to A*,
2601 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002602 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002603 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002604 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002605 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002606
Douglas Gregor237f96c2008-11-26 23:31:11 +00002607 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002608 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002609 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002610 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002611 return ImplicitConversionSequence::Worse;
2612 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002613 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002614 }
2615
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002616 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002617 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2618 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2619 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2620 const MemberPointerType * FromMemPointer1 =
2621 FromType1->getAs<MemberPointerType>();
2622 const MemberPointerType * ToMemPointer1 =
2623 ToType1->getAs<MemberPointerType>();
2624 const MemberPointerType * FromMemPointer2 =
2625 FromType2->getAs<MemberPointerType>();
2626 const MemberPointerType * ToMemPointer2 =
2627 ToType2->getAs<MemberPointerType>();
2628 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2629 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2630 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2631 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2632 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2633 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2634 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2635 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002636 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002637 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002638 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002639 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002640 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002641 return ImplicitConversionSequence::Better;
2642 }
2643 // conversion of B::* to C::* is better than conversion of A::* to C::*
2644 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002645 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002646 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002647 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002648 return ImplicitConversionSequence::Worse;
2649 }
2650 }
2651
Douglas Gregor5ab11652010-04-17 22:01:05 +00002652 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002653 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002654 // -- binding of an expression of type C to a reference of type
2655 // B& is better than binding an expression of type C to a
2656 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002657 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2658 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2659 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002660 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002661 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002662 return ImplicitConversionSequence::Worse;
2663 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002664
Douglas Gregor2fe98832008-11-03 19:09:14 +00002665 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002666 // -- binding of an expression of type B to a reference of type
2667 // A& is better than binding an expression of type C to a
2668 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002669 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2670 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2671 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002672 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002673 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002674 return ImplicitConversionSequence::Worse;
2675 }
2676 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002677
Douglas Gregor5c407d92008-10-23 00:40:37 +00002678 return ImplicitConversionSequence::Indistinguishable;
2679}
2680
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002681/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2682/// determine whether they are reference-related,
2683/// reference-compatible, reference-compatible with added
2684/// qualification, or incompatible, for use in C++ initialization by
2685/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2686/// type, and the first type (T1) is the pointee type of the reference
2687/// type being initialized.
2688Sema::ReferenceCompareResult
2689Sema::CompareReferenceRelationship(SourceLocation Loc,
2690 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002691 bool &DerivedToBase,
2692 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002693 assert(!OrigT1->isReferenceType() &&
2694 "T1 must be the pointee type of the reference type");
2695 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2696
2697 QualType T1 = Context.getCanonicalType(OrigT1);
2698 QualType T2 = Context.getCanonicalType(OrigT2);
2699 Qualifiers T1Quals, T2Quals;
2700 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2701 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2702
2703 // C++ [dcl.init.ref]p4:
2704 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2705 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2706 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002707 DerivedToBase = false;
2708 ObjCConversion = false;
2709 if (UnqualT1 == UnqualT2) {
2710 // Nothing to do.
2711 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002712 IsDerivedFrom(UnqualT2, UnqualT1))
2713 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002714 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2715 UnqualT2->isObjCObjectOrInterfaceType() &&
2716 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2717 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002718 else
2719 return Ref_Incompatible;
2720
2721 // At this point, we know that T1 and T2 are reference-related (at
2722 // least).
2723
2724 // If the type is an array type, promote the element qualifiers to the type
2725 // for comparison.
2726 if (isa<ArrayType>(T1) && T1Quals)
2727 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2728 if (isa<ArrayType>(T2) && T2Quals)
2729 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2730
2731 // C++ [dcl.init.ref]p4:
2732 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2733 // reference-related to T2 and cv1 is the same cv-qualification
2734 // as, or greater cv-qualification than, cv2. For purposes of
2735 // overload resolution, cases for which cv1 is greater
2736 // cv-qualification than cv2 are identified as
2737 // reference-compatible with added qualification (see 13.3.3.2).
2738 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2739 return Ref_Compatible;
2740 else if (T1.isMoreQualifiedThan(T2))
2741 return Ref_Compatible_With_Added_Qualification;
2742 else
2743 return Ref_Related;
2744}
2745
Douglas Gregor836a7e82010-08-11 02:15:33 +00002746/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002747/// with DeclType. Return true if something definite is found.
2748static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002749FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2750 QualType DeclType, SourceLocation DeclLoc,
2751 Expr *Init, QualType T2, bool AllowRvalues,
2752 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002753 assert(T2->isRecordType() && "Can only find conversions of record types.");
2754 CXXRecordDecl *T2RecordDecl
2755 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2756
Douglas Gregor836a7e82010-08-11 02:15:33 +00002757 QualType ToType
2758 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2759 : DeclType;
2760
Sebastian Redld92badf2010-06-30 18:13:39 +00002761 OverloadCandidateSet CandidateSet(DeclLoc);
2762 const UnresolvedSetImpl *Conversions
2763 = T2RecordDecl->getVisibleConversionFunctions();
2764 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2765 E = Conversions->end(); I != E; ++I) {
2766 NamedDecl *D = *I;
2767 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2768 if (isa<UsingShadowDecl>(D))
2769 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2770
2771 FunctionTemplateDecl *ConvTemplate
2772 = dyn_cast<FunctionTemplateDecl>(D);
2773 CXXConversionDecl *Conv;
2774 if (ConvTemplate)
2775 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2776 else
2777 Conv = cast<CXXConversionDecl>(D);
2778
Douglas Gregor836a7e82010-08-11 02:15:33 +00002779 // If this is an explicit conversion, and we're not allowed to consider
2780 // explicit conversions, skip it.
2781 if (!AllowExplicit && Conv->isExplicit())
2782 continue;
2783
2784 if (AllowRvalues) {
2785 bool DerivedToBase = false;
2786 bool ObjCConversion = false;
2787 if (!ConvTemplate &&
2788 S.CompareReferenceRelationship(DeclLoc,
2789 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2790 DeclType.getNonReferenceType().getUnqualifiedType(),
2791 DerivedToBase, ObjCConversion)
2792 == Sema::Ref_Incompatible)
2793 continue;
2794 } else {
2795 // If the conversion function doesn't return a reference type,
2796 // it can't be considered for this conversion. An rvalue reference
2797 // is only acceptable if its referencee is a function type.
2798
2799 const ReferenceType *RefType =
2800 Conv->getConversionType()->getAs<ReferenceType>();
2801 if (!RefType ||
2802 (!RefType->isLValueReferenceType() &&
2803 !RefType->getPointeeType()->isFunctionType()))
2804 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002805 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002806
2807 if (ConvTemplate)
2808 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2809 Init, ToType, CandidateSet);
2810 else
2811 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2812 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002813 }
2814
2815 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002816 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002817 case OR_Success:
2818 // C++ [over.ics.ref]p1:
2819 //
2820 // [...] If the parameter binds directly to the result of
2821 // applying a conversion function to the argument
2822 // expression, the implicit conversion sequence is a
2823 // user-defined conversion sequence (13.3.3.1.2), with the
2824 // second standard conversion sequence either an identity
2825 // conversion or, if the conversion function returns an
2826 // entity of a type that is a derived class of the parameter
2827 // type, a derived-to-base Conversion.
2828 if (!Best->FinalConversion.DirectBinding)
2829 return false;
2830
2831 ICS.setUserDefined();
2832 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2833 ICS.UserDefined.After = Best->FinalConversion;
2834 ICS.UserDefined.ConversionFunction = Best->Function;
2835 ICS.UserDefined.EllipsisConversion = false;
2836 assert(ICS.UserDefined.After.ReferenceBinding &&
2837 ICS.UserDefined.After.DirectBinding &&
2838 "Expected a direct reference binding!");
2839 return true;
2840
2841 case OR_Ambiguous:
2842 ICS.setAmbiguous();
2843 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2844 Cand != CandidateSet.end(); ++Cand)
2845 if (Cand->Viable)
2846 ICS.Ambiguous.addConversion(Cand->Function);
2847 return true;
2848
2849 case OR_No_Viable_Function:
2850 case OR_Deleted:
2851 // There was no suitable conversion, or we found a deleted
2852 // conversion; continue with other checks.
2853 return false;
2854 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002855
2856 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002857}
2858
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002859/// \brief Compute an implicit conversion sequence for reference
2860/// initialization.
2861static ImplicitConversionSequence
2862TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2863 SourceLocation DeclLoc,
2864 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002865 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002866 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2867
2868 // Most paths end in a failed conversion.
2869 ImplicitConversionSequence ICS;
2870 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2871
2872 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2873 QualType T2 = Init->getType();
2874
2875 // If the initializer is the address of an overloaded function, try
2876 // to resolve the overloaded function. If all goes well, T2 is the
2877 // type of the resulting function.
2878 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2879 DeclAccessPair Found;
2880 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2881 false, Found))
2882 T2 = Fn->getType();
2883 }
2884
2885 // Compute some basic properties of the types and the initializer.
2886 bool isRValRef = DeclType->isRValueReferenceType();
2887 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002888 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002889 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002890 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002891 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2892 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002893
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002894
Sebastian Redld92badf2010-06-30 18:13:39 +00002895 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002896 // A reference to type "cv1 T1" is initialized by an expression
2897 // of type "cv2 T2" as follows:
2898
Sebastian Redld92badf2010-06-30 18:13:39 +00002899 // -- If reference is an lvalue reference and the initializer expression
2900 // The next bullet point (T1 is a function) is pretty much equivalent to this
2901 // one, so it's handled here.
2902 if (!isRValRef || T1->isFunctionType()) {
2903 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2904 // reference-compatible with "cv2 T2," or
2905 //
2906 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2907 if (InitCategory.isLValue() &&
2908 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002909 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002910 // When a parameter of reference type binds directly (8.5.3)
2911 // to an argument expression, the implicit conversion sequence
2912 // is the identity conversion, unless the argument expression
2913 // has a type that is a derived class of the parameter type,
2914 // in which case the implicit conversion sequence is a
2915 // derived-to-base Conversion (13.3.3.1).
2916 ICS.setStandard();
2917 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002918 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2919 : ObjCConversion? ICK_Compatible_Conversion
2920 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002921 ICS.Standard.Third = ICK_Identity;
2922 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2923 ICS.Standard.setToType(0, T2);
2924 ICS.Standard.setToType(1, T1);
2925 ICS.Standard.setToType(2, T1);
2926 ICS.Standard.ReferenceBinding = true;
2927 ICS.Standard.DirectBinding = true;
2928 ICS.Standard.RRefBinding = isRValRef;
2929 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002930
Sebastian Redld92badf2010-06-30 18:13:39 +00002931 // Nothing more to do: the inaccessibility/ambiguity check for
2932 // derived-to-base conversions is suppressed when we're
2933 // computing the implicit conversion sequence (C++
2934 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002935 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002936 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002937
Sebastian Redld92badf2010-06-30 18:13:39 +00002938 // -- has a class type (i.e., T2 is a class type), where T1 is
2939 // not reference-related to T2, and can be implicitly
2940 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2941 // is reference-compatible with "cv3 T3" 92) (this
2942 // conversion is selected by enumerating the applicable
2943 // conversion functions (13.3.1.6) and choosing the best
2944 // one through overload resolution (13.3)),
2945 if (!SuppressUserConversions && T2->isRecordType() &&
2946 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2947 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002948 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2949 Init, T2, /*AllowRvalues=*/false,
2950 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002951 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002952 }
2953 }
2954
Sebastian Redld92badf2010-06-30 18:13:39 +00002955 // -- Otherwise, the reference shall be an lvalue reference to a
2956 // non-volatile const type (i.e., cv1 shall be const), or the reference
2957 // shall be an rvalue reference and the initializer expression shall be
2958 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002959 //
2960 // We actually handle one oddity of C++ [over.ics.ref] at this
2961 // point, which is that, due to p2 (which short-circuits reference
2962 // binding by only attempting a simple conversion for non-direct
2963 // bindings) and p3's strange wording, we allow a const volatile
2964 // reference to bind to an rvalue. Hence the check for the presence
2965 // of "const" rather than checking for "const" being the only
2966 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002967 // This is also the point where rvalue references and lvalue inits no longer
2968 // go together.
2969 if ((!isRValRef && !T1.isConstQualified()) ||
2970 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002971 return ICS;
2972
Sebastian Redld92badf2010-06-30 18:13:39 +00002973 // -- If T1 is a function type, then
2974 // -- if T2 is the same type as T1, the reference is bound to the
2975 // initializer expression lvalue;
2976 // -- if T2 is a class type and the initializer expression can be
2977 // implicitly converted to an lvalue of type T1 [...], the
2978 // reference is bound to the function lvalue that is the result
2979 // of the conversion;
2980 // This is the same as for the lvalue case above, so it was handled there.
2981 // -- otherwise, the program is ill-formed.
2982 // This is the one difference to the lvalue case.
2983 if (T1->isFunctionType())
2984 return ICS;
2985
2986 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002987 // -- the initializer expression is an rvalue and "cv1 T1"
2988 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002989 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002990 // -- T1 is not reference-related to T2 and the initializer
2991 // expression can be implicitly converted to an rvalue
2992 // of type "cv3 T3" (this conversion is selected by
2993 // enumerating the applicable conversion functions
2994 // (13.3.1.6) and choosing the best one through overload
2995 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002996 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002997 // then the reference is bound to the initializer
2998 // expression rvalue in the first case and to the object
2999 // that is the result of the conversion in the second case
3000 // (or, in either case, to the appropriate base class
3001 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00003002 if (T2->isRecordType()) {
3003 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3004 // direct binding in C++0x but not in C++03.
3005 if (InitCategory.isRValue() &&
3006 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3007 ICS.setStandard();
3008 ICS.Standard.First = ICK_Identity;
3009 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3010 : ObjCConversion? ICK_Compatible_Conversion
3011 : ICK_Identity;
3012 ICS.Standard.Third = ICK_Identity;
3013 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3014 ICS.Standard.setToType(0, T2);
3015 ICS.Standard.setToType(1, T1);
3016 ICS.Standard.setToType(2, T1);
3017 ICS.Standard.ReferenceBinding = true;
3018 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3019 ICS.Standard.RRefBinding = isRValRef;
3020 ICS.Standard.CopyConstructor = 0;
3021 return ICS;
3022 }
3023
3024 // Second case: not reference-related.
3025 if (RefRelationship == Sema::Ref_Incompatible &&
3026 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3027 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3028 Init, T2, /*AllowRvalues=*/true,
3029 AllowExplicit))
3030 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003031 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003032
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003033 // -- Otherwise, a temporary of type "cv1 T1" is created and
3034 // initialized from the initializer expression using the
3035 // rules for a non-reference copy initialization (8.5). The
3036 // reference is then bound to the temporary. If T1 is
3037 // reference-related to T2, cv1 must be the same
3038 // cv-qualification as, or greater cv-qualification than,
3039 // cv2; otherwise, the program is ill-formed.
3040 if (RefRelationship == Sema::Ref_Related) {
3041 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3042 // we would be reference-compatible or reference-compatible with
3043 // added qualification. But that wasn't the case, so the reference
3044 // initialization fails.
3045 return ICS;
3046 }
3047
3048 // If at least one of the types is a class type, the types are not
3049 // related, and we aren't allowed any user conversions, the
3050 // reference binding fails. This case is important for breaking
3051 // recursion, since TryImplicitConversion below will attempt to
3052 // create a temporary through the use of a copy constructor.
3053 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3054 (T1->isRecordType() || T2->isRecordType()))
3055 return ICS;
3056
3057 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003058 // When a parameter of reference type is not bound directly to
3059 // an argument expression, the conversion sequence is the one
3060 // required to convert the argument expression to the
3061 // underlying type of the reference according to
3062 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3063 // to copy-initializing a temporary of the underlying type with
3064 // the argument expression. Any difference in top-level
3065 // cv-qualification is subsumed by the initialization itself
3066 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003067 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3068 /*AllowExplicit=*/false,
3069 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003070
3071 // Of course, that's still a reference binding.
3072 if (ICS.isStandard()) {
3073 ICS.Standard.ReferenceBinding = true;
3074 ICS.Standard.RRefBinding = isRValRef;
3075 } else if (ICS.isUserDefined()) {
3076 ICS.UserDefined.After.ReferenceBinding = true;
3077 ICS.UserDefined.After.RRefBinding = isRValRef;
3078 }
3079 return ICS;
3080}
3081
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003082/// TryCopyInitialization - Try to copy-initialize a value of type
3083/// ToType from the expression From. Return the implicit conversion
3084/// sequence required to pass this argument, which may be a bad
3085/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003086/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003087/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003088static ImplicitConversionSequence
3089TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003090 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003091 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003092 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003093 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003094 /*FIXME:*/From->getLocStart(),
3095 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003096 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003097
John McCall5c32be02010-08-24 20:38:10 +00003098 return TryImplicitConversion(S, From, ToType,
3099 SuppressUserConversions,
3100 /*AllowExplicit=*/false,
3101 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003102}
3103
Douglas Gregor436424c2008-11-18 23:14:02 +00003104/// TryObjectArgumentInitialization - Try to initialize the object
3105/// parameter of the given member function (@c Method) from the
3106/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003107static ImplicitConversionSequence
3108TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3109 CXXMethodDecl *Method,
3110 CXXRecordDecl *ActingContext) {
3111 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003112 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3113 // const volatile object.
3114 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3115 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003116 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003117
3118 // Set up the conversion sequence as a "bad" conversion, to allow us
3119 // to exit early.
3120 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003121
3122 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003123 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003124 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003125 FromType = PT->getPointeeType();
3126
3127 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003128
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003129 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003130 // where X is the class of which the function is a member
3131 // (C++ [over.match.funcs]p4). However, when finding an implicit
3132 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003133 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003134 // (C++ [over.match.funcs]p5). We perform a simplified version of
3135 // reference binding here, that allows class rvalues to bind to
3136 // non-constant references.
3137
3138 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3139 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003140 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003141 if (ImplicitParamType.getCVRQualifiers()
3142 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003143 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003144 ICS.setBad(BadConversionSequence::bad_qualifiers,
3145 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003146 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003147 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003148
3149 // Check that we have either the same type or a derived type. It
3150 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003151 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003152 ImplicitConversionKind SecondKind;
3153 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3154 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003155 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003156 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003157 else {
John McCall65eb8792010-02-25 01:37:24 +00003158 ICS.setBad(BadConversionSequence::unrelated_class,
3159 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003160 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003161 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003162
3163 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003164 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003165 ICS.Standard.setAsIdentityConversion();
3166 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003167 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003168 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003169 ICS.Standard.ReferenceBinding = true;
3170 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003171 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003172 return ICS;
3173}
3174
3175/// PerformObjectArgumentInitialization - Perform initialization of
3176/// the implicit object parameter for the given Method with the given
3177/// expression.
3178bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003179Sema::PerformObjectArgumentInitialization(Expr *&From,
3180 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003181 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003182 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003183 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003184 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003185 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003186
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003187 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003188 FromRecordType = PT->getPointeeType();
3189 DestType = Method->getThisType(Context);
3190 } else {
3191 FromRecordType = From->getType();
3192 DestType = ImplicitParamRecordType;
3193 }
3194
John McCall6e9f8f62009-12-03 04:06:58 +00003195 // Note that we always use the true parent context when performing
3196 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003197 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003198 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003199 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003200 if (ICS.isBad()) {
3201 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3202 Qualifiers FromQs = FromRecordType.getQualifiers();
3203 Qualifiers ToQs = DestType.getQualifiers();
3204 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3205 if (CVR) {
3206 Diag(From->getSourceRange().getBegin(),
3207 diag::err_member_function_call_bad_cvr)
3208 << Method->getDeclName() << FromRecordType << (CVR - 1)
3209 << From->getSourceRange();
3210 Diag(Method->getLocation(), diag::note_previous_decl)
3211 << Method->getDeclName();
3212 return true;
3213 }
3214 }
3215
Douglas Gregor436424c2008-11-18 23:14:02 +00003216 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003217 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003218 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003219 }
Mike Stump11289f42009-09-09 15:08:12 +00003220
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003221 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003222 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003223
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003224 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003225 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003226 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003227 return false;
3228}
3229
Douglas Gregor5fb53972009-01-14 15:45:31 +00003230/// TryContextuallyConvertToBool - Attempt to contextually convert the
3231/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003232static ImplicitConversionSequence
3233TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003234 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003235 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003236 // FIXME: Are these flags correct?
3237 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003238 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003239 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003240}
3241
3242/// PerformContextuallyConvertToBool - Perform a contextual conversion
3243/// of the expression From to bool (C++0x [conv]p3).
3244bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003245 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003246 if (!ICS.isBad())
3247 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003248
Fariborz Jahanian76197412009-11-18 18:26:29 +00003249 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003250 return Diag(From->getSourceRange().getBegin(),
3251 diag::err_typecheck_bool_condition)
3252 << From->getType() << From->getSourceRange();
3253 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003254}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003255
3256/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3257/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003258static ImplicitConversionSequence
3259TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3260 QualType Ty = S.Context.getObjCIdType();
3261 return TryImplicitConversion(S, From, Ty,
3262 // FIXME: Are these flags correct?
3263 /*SuppressUserConversions=*/false,
3264 /*AllowExplicit=*/true,
3265 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003266}
John McCall5c32be02010-08-24 20:38:10 +00003267
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003268/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3269/// of the expression From to 'id'.
3270bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003271 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003272 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003273 if (!ICS.isBad())
3274 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3275 return true;
3276}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003277
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003278/// \brief Attempt to convert the given expression to an integral or
3279/// enumeration type.
3280///
3281/// This routine will attempt to convert an expression of class type to an
3282/// integral or enumeration type, if that class type only has a single
3283/// conversion to an integral or enumeration type.
3284///
Douglas Gregor4799d032010-06-30 00:20:43 +00003285/// \param Loc The source location of the construct that requires the
3286/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003287///
Douglas Gregor4799d032010-06-30 00:20:43 +00003288/// \param FromE The expression we're converting from.
3289///
3290/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3291/// have integral or enumeration type.
3292///
3293/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3294/// incomplete class type.
3295///
3296/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3297/// explicit conversion function (because no implicit conversion functions
3298/// were available). This is a recovery mode.
3299///
3300/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3301/// showing which conversion was picked.
3302///
3303/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3304/// conversion function that could convert to integral or enumeration type.
3305///
3306/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3307/// usable conversion function.
3308///
3309/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3310/// function, which may be an extension in this case.
3311///
3312/// \returns The expression, converted to an integral or enumeration type if
3313/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003314ExprResult
John McCallb268a282010-08-23 23:25:46 +00003315Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003316 const PartialDiagnostic &NotIntDiag,
3317 const PartialDiagnostic &IncompleteDiag,
3318 const PartialDiagnostic &ExplicitConvDiag,
3319 const PartialDiagnostic &ExplicitConvNote,
3320 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003321 const PartialDiagnostic &AmbigNote,
3322 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003323 // We can't perform any more checking for type-dependent expressions.
3324 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003325 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003326
3327 // If the expression already has integral or enumeration type, we're golden.
3328 QualType T = From->getType();
3329 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003330 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003331
3332 // FIXME: Check for missing '()' if T is a function type?
3333
3334 // If we don't have a class type in C++, there's no way we can get an
3335 // expression of integral or enumeration type.
3336 const RecordType *RecordTy = T->getAs<RecordType>();
3337 if (!RecordTy || !getLangOptions().CPlusPlus) {
3338 Diag(Loc, NotIntDiag)
3339 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003340 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003341 }
3342
3343 // We must have a complete class type.
3344 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003345 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003346
3347 // Look for a conversion to an integral or enumeration type.
3348 UnresolvedSet<4> ViableConversions;
3349 UnresolvedSet<4> ExplicitConversions;
3350 const UnresolvedSetImpl *Conversions
3351 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3352
3353 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3354 E = Conversions->end();
3355 I != E;
3356 ++I) {
3357 if (CXXConversionDecl *Conversion
3358 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3359 if (Conversion->getConversionType().getNonReferenceType()
3360 ->isIntegralOrEnumerationType()) {
3361 if (Conversion->isExplicit())
3362 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3363 else
3364 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3365 }
3366 }
3367
3368 switch (ViableConversions.size()) {
3369 case 0:
3370 if (ExplicitConversions.size() == 1) {
3371 DeclAccessPair Found = ExplicitConversions[0];
3372 CXXConversionDecl *Conversion
3373 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3374
3375 // The user probably meant to invoke the given explicit
3376 // conversion; use it.
3377 QualType ConvTy
3378 = Conversion->getConversionType().getNonReferenceType();
3379 std::string TypeStr;
3380 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3381
3382 Diag(Loc, ExplicitConvDiag)
3383 << T << ConvTy
3384 << FixItHint::CreateInsertion(From->getLocStart(),
3385 "static_cast<" + TypeStr + ">(")
3386 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3387 ")");
3388 Diag(Conversion->getLocation(), ExplicitConvNote)
3389 << ConvTy->isEnumeralType() << ConvTy;
3390
3391 // If we aren't in a SFINAE context, build a call to the
3392 // explicit conversion function.
3393 if (isSFINAEContext())
3394 return ExprError();
3395
3396 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003397 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003398 }
3399
3400 // We'll complain below about a non-integral condition type.
3401 break;
3402
3403 case 1: {
3404 // Apply this conversion.
3405 DeclAccessPair Found = ViableConversions[0];
3406 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003407
3408 CXXConversionDecl *Conversion
3409 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3410 QualType ConvTy
3411 = Conversion->getConversionType().getNonReferenceType();
3412 if (ConvDiag.getDiagID()) {
3413 if (isSFINAEContext())
3414 return ExprError();
3415
3416 Diag(Loc, ConvDiag)
3417 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3418 }
3419
John McCallb268a282010-08-23 23:25:46 +00003420 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003421 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003422 break;
3423 }
3424
3425 default:
3426 Diag(Loc, AmbigDiag)
3427 << T << From->getSourceRange();
3428 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3429 CXXConversionDecl *Conv
3430 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3431 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3432 Diag(Conv->getLocation(), AmbigNote)
3433 << ConvTy->isEnumeralType() << ConvTy;
3434 }
John McCallb268a282010-08-23 23:25:46 +00003435 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003436 }
3437
Douglas Gregor5823da32010-06-29 23:25:20 +00003438 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003439 Diag(Loc, NotIntDiag)
3440 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003441
John McCallb268a282010-08-23 23:25:46 +00003442 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003443}
3444
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003445/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003446/// candidate functions, using the given function call arguments. If
3447/// @p SuppressUserConversions, then don't allow user-defined
3448/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003449///
3450/// \para PartialOverloading true if we are performing "partial" overloading
3451/// based on an incomplete set of function arguments. This feature is used by
3452/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003453void
3454Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003455 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003456 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003457 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003458 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003459 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003460 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003461 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003462 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003463 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003464 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003466 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003467 if (!isa<CXXConstructorDecl>(Method)) {
3468 // If we get here, it's because we're calling a member function
3469 // that is named without a member access expression (e.g.,
3470 // "this->f") that was either written explicitly or created
3471 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003472 // function, e.g., X::f(). We use an empty type for the implied
3473 // object argument (C++ [over.call.func]p3), and the acting context
3474 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003475 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003476 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003477 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003478 return;
3479 }
3480 // We treat a constructor like a non-member function, since its object
3481 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003482 }
3483
Douglas Gregorff7028a2009-11-13 23:59:09 +00003484 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003485 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003486
Douglas Gregor27381f32009-11-23 12:27:39 +00003487 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003488 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003489
Douglas Gregorffe14e32009-11-14 01:20:54 +00003490 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3491 // C++ [class.copy]p3:
3492 // A member function template is never instantiated to perform the copy
3493 // of a class object to an object of its class type.
3494 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3495 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003496 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003497 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3498 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003499 return;
3500 }
3501
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003502 // Add this candidate
3503 CandidateSet.push_back(OverloadCandidate());
3504 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003505 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003506 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003507 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003508 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003509 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003510
3511 unsigned NumArgsInProto = Proto->getNumArgs();
3512
3513 // (C++ 13.3.2p2): A candidate function having fewer than m
3514 // parameters is viable only if it has an ellipsis in its parameter
3515 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003516 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3517 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003518 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003519 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003520 return;
3521 }
3522
3523 // (C++ 13.3.2p2): A candidate function having more than m parameters
3524 // is viable only if the (m+1)st parameter has a default argument
3525 // (8.3.6). For the purposes of overload resolution, the
3526 // parameter list is truncated on the right, so that there are
3527 // exactly m parameters.
3528 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003529 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003530 // Not enough arguments.
3531 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003532 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003533 return;
3534 }
3535
3536 // Determine the implicit conversion sequences for each of the
3537 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003538 Candidate.Conversions.resize(NumArgs);
3539 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3540 if (ArgIdx < NumArgsInProto) {
3541 // (C++ 13.3.2p3): for F to be a viable function, there shall
3542 // exist for each argument an implicit conversion sequence
3543 // (13.3.3.1) that converts that argument to the corresponding
3544 // parameter of F.
3545 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003546 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003547 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003548 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003549 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003550 if (Candidate.Conversions[ArgIdx].isBad()) {
3551 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003552 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003553 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003554 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003555 } else {
3556 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3557 // argument for which there is no corresponding parameter is
3558 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003559 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003560 }
3561 }
3562}
3563
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003564/// \brief Add all of the function declarations in the given function set to
3565/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003566void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003567 Expr **Args, unsigned NumArgs,
3568 OverloadCandidateSet& CandidateSet,
3569 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003570 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003571 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3572 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003573 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003574 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003575 cast<CXXMethodDecl>(FD)->getParent(),
3576 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003577 CandidateSet, SuppressUserConversions);
3578 else
John McCalla0296f72010-03-19 07:35:19 +00003579 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003580 SuppressUserConversions);
3581 } else {
John McCalla0296f72010-03-19 07:35:19 +00003582 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003583 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3584 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003585 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003586 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003587 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003588 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003589 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003590 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003591 else
John McCalla0296f72010-03-19 07:35:19 +00003592 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003593 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003594 Args, NumArgs, CandidateSet,
3595 SuppressUserConversions);
3596 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003597 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003598}
3599
John McCallf0f1cf02009-11-17 07:50:12 +00003600/// AddMethodCandidate - Adds a named decl (which is some kind of
3601/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003602void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003603 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003604 Expr **Args, unsigned NumArgs,
3605 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003606 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003607 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003608 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003609
3610 if (isa<UsingShadowDecl>(Decl))
3611 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3612
3613 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3614 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3615 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003616 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3617 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003618 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003619 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003620 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003621 } else {
John McCalla0296f72010-03-19 07:35:19 +00003622 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003623 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003624 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003625 }
3626}
3627
Douglas Gregor436424c2008-11-18 23:14:02 +00003628/// AddMethodCandidate - Adds the given C++ member function to the set
3629/// of candidate functions, using the given function call arguments
3630/// and the object argument (@c Object). For example, in a call
3631/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3632/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3633/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003634/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003635void
John McCalla0296f72010-03-19 07:35:19 +00003636Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003637 CXXRecordDecl *ActingContext, QualType ObjectType,
3638 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003639 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003640 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003641 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003642 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003643 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003644 assert(!isa<CXXConstructorDecl>(Method) &&
3645 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003646
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003647 if (!CandidateSet.isNewCandidate(Method))
3648 return;
3649
Douglas Gregor27381f32009-11-23 12:27:39 +00003650 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003651 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003652
Douglas Gregor436424c2008-11-18 23:14:02 +00003653 // Add this candidate
3654 CandidateSet.push_back(OverloadCandidate());
3655 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003656 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003657 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003658 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003659 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003660
3661 unsigned NumArgsInProto = Proto->getNumArgs();
3662
3663 // (C++ 13.3.2p2): A candidate function having fewer than m
3664 // parameters is viable only if it has an ellipsis in its parameter
3665 // list (8.3.5).
3666 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3667 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003668 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003669 return;
3670 }
3671
3672 // (C++ 13.3.2p2): A candidate function having more than m parameters
3673 // is viable only if the (m+1)st parameter has a default argument
3674 // (8.3.6). For the purposes of overload resolution, the
3675 // parameter list is truncated on the right, so that there are
3676 // exactly m parameters.
3677 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3678 if (NumArgs < MinRequiredArgs) {
3679 // Not enough arguments.
3680 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003681 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003682 return;
3683 }
3684
3685 Candidate.Viable = true;
3686 Candidate.Conversions.resize(NumArgs + 1);
3687
John McCall6e9f8f62009-12-03 04:06:58 +00003688 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003689 // The implicit object argument is ignored.
3690 Candidate.IgnoreObjectArgument = true;
3691 else {
3692 // Determine the implicit conversion sequence for the object
3693 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003694 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003695 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3696 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003697 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003698 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003699 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003700 return;
3701 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003702 }
3703
3704 // Determine the implicit conversion sequences for each of the
3705 // arguments.
3706 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3707 if (ArgIdx < NumArgsInProto) {
3708 // (C++ 13.3.2p3): for F to be a viable function, there shall
3709 // exist for each argument an implicit conversion sequence
3710 // (13.3.3.1) that converts that argument to the corresponding
3711 // parameter of F.
3712 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003713 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003714 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003715 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003716 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003717 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003718 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003719 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003720 break;
3721 }
3722 } else {
3723 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3724 // argument for which there is no corresponding parameter is
3725 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003726 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003727 }
3728 }
3729}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003730
Douglas Gregor97628d62009-08-21 00:16:32 +00003731/// \brief Add a C++ member function template as a candidate to the candidate
3732/// set, using template argument deduction to produce an appropriate member
3733/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003734void
Douglas Gregor97628d62009-08-21 00:16:32 +00003735Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003736 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003737 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003738 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003739 QualType ObjectType,
3740 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003741 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003742 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003743 if (!CandidateSet.isNewCandidate(MethodTmpl))
3744 return;
3745
Douglas Gregor97628d62009-08-21 00:16:32 +00003746 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003747 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003748 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003749 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003750 // candidate functions in the usual way.113) A given name can refer to one
3751 // or more function templates and also to a set of overloaded non-template
3752 // functions. In such a case, the candidate functions generated from each
3753 // function template are combined with the set of non-template candidate
3754 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003755 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003756 FunctionDecl *Specialization = 0;
3757 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003758 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003759 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003760 CandidateSet.push_back(OverloadCandidate());
3761 OverloadCandidate &Candidate = CandidateSet.back();
3762 Candidate.FoundDecl = FoundDecl;
3763 Candidate.Function = MethodTmpl->getTemplatedDecl();
3764 Candidate.Viable = false;
3765 Candidate.FailureKind = ovl_fail_bad_deduction;
3766 Candidate.IsSurrogate = false;
3767 Candidate.IgnoreObjectArgument = false;
3768 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3769 Info);
3770 return;
3771 }
Mike Stump11289f42009-09-09 15:08:12 +00003772
Douglas Gregor97628d62009-08-21 00:16:32 +00003773 // Add the function template specialization produced by template argument
3774 // deduction as a candidate.
3775 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003776 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003777 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003778 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003779 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003780 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003781}
3782
Douglas Gregor05155d82009-08-21 23:19:43 +00003783/// \brief Add a C++ function template specialization as a candidate
3784/// in the candidate set, using template argument deduction to produce
3785/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003786void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003787Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003788 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003789 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003790 Expr **Args, unsigned NumArgs,
3791 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003792 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003793 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3794 return;
3795
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003796 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003797 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003798 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003799 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003800 // candidate functions in the usual way.113) A given name can refer to one
3801 // or more function templates and also to a set of overloaded non-template
3802 // functions. In such a case, the candidate functions generated from each
3803 // function template are combined with the set of non-template candidate
3804 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003805 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003806 FunctionDecl *Specialization = 0;
3807 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003808 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003809 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003810 CandidateSet.push_back(OverloadCandidate());
3811 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003812 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003813 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3814 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003815 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003816 Candidate.IsSurrogate = false;
3817 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003818 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3819 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003820 return;
3821 }
Mike Stump11289f42009-09-09 15:08:12 +00003822
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003823 // Add the function template specialization produced by template argument
3824 // deduction as a candidate.
3825 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003826 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003827 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003828}
Mike Stump11289f42009-09-09 15:08:12 +00003829
Douglas Gregora1f013e2008-11-07 22:36:19 +00003830/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003831/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003832/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003833/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003834/// (which may or may not be the same type as the type that the
3835/// conversion function produces).
3836void
3837Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003838 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003839 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003840 Expr *From, QualType ToType,
3841 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003842 assert(!Conversion->getDescribedFunctionTemplate() &&
3843 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003844 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003845 if (!CandidateSet.isNewCandidate(Conversion))
3846 return;
3847
Douglas Gregor27381f32009-11-23 12:27:39 +00003848 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003849 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003850
Douglas Gregora1f013e2008-11-07 22:36:19 +00003851 // Add this candidate
3852 CandidateSet.push_back(OverloadCandidate());
3853 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003854 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003855 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003856 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003857 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003858 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003859 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003860 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003861 Candidate.Viable = true;
3862 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003863
Douglas Gregor6affc782010-08-19 15:37:02 +00003864 // C++ [over.match.funcs]p4:
3865 // For conversion functions, the function is considered to be a member of
3866 // the class of the implicit implied object argument for the purpose of
3867 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003868 //
3869 // Determine the implicit conversion sequence for the implicit
3870 // object parameter.
3871 QualType ImplicitParamType = From->getType();
3872 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3873 ImplicitParamType = FromPtrType->getPointeeType();
3874 CXXRecordDecl *ConversionContext
3875 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3876
3877 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003878 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003879 ConversionContext);
3880
John McCall0d1da222010-01-12 00:44:57 +00003881 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003882 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003883 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003884 return;
3885 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003886
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003887 // We won't go through a user-define type conversion function to convert a
3888 // derived to base as such conversions are given Conversion Rank. They only
3889 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3890 QualType FromCanon
3891 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3892 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3893 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3894 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003895 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003896 return;
3897 }
3898
Douglas Gregora1f013e2008-11-07 22:36:19 +00003899 // To determine what the conversion from the result of calling the
3900 // conversion function to the type we're eventually trying to
3901 // convert to (ToType), we need to synthesize a call to the
3902 // conversion function and attempt copy initialization from it. This
3903 // makes sure that we get the right semantics with respect to
3904 // lvalues/rvalues and the type. Fortunately, we can allocate this
3905 // call on the stack and we don't need its arguments to be
3906 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003907 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003908 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003909 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3910 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003911 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003912 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003913
Douglas Gregor72ebdab2010-11-13 19:36:57 +00003914 QualType CallResultType
3915 = Conversion->getConversionType().getNonLValueExprType(Context);
3916 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3917 Candidate.Viable = false;
3918 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3919 return;
3920 }
3921
John McCall7decc9e2010-11-18 06:31:45 +00003922 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3923
Mike Stump11289f42009-09-09 15:08:12 +00003924 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003925 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3926 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00003927 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00003928 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003929 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003930 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003931 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003932 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003933
John McCall0d1da222010-01-12 00:44:57 +00003934 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003935 case ImplicitConversionSequence::StandardConversion:
3936 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003937
3938 // C++ [over.ics.user]p3:
3939 // If the user-defined conversion is specified by a specialization of a
3940 // conversion function template, the second standard conversion sequence
3941 // shall have exact match rank.
3942 if (Conversion->getPrimaryTemplate() &&
3943 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3944 Candidate.Viable = false;
3945 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3946 }
3947
Douglas Gregora1f013e2008-11-07 22:36:19 +00003948 break;
3949
3950 case ImplicitConversionSequence::BadConversion:
3951 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003952 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003953 break;
3954
3955 default:
Mike Stump11289f42009-09-09 15:08:12 +00003956 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003957 "Can only end up with a standard conversion sequence or failure");
3958 }
3959}
3960
Douglas Gregor05155d82009-08-21 23:19:43 +00003961/// \brief Adds a conversion function template specialization
3962/// candidate to the overload set, using template argument deduction
3963/// to deduce the template arguments of the conversion function
3964/// template from the type that we are converting to (C++
3965/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003966void
Douglas Gregor05155d82009-08-21 23:19:43 +00003967Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003968 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003969 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003970 Expr *From, QualType ToType,
3971 OverloadCandidateSet &CandidateSet) {
3972 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3973 "Only conversion function templates permitted here");
3974
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003975 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3976 return;
3977
John McCallbc077cf2010-02-08 23:07:23 +00003978 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003979 CXXConversionDecl *Specialization = 0;
3980 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003981 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003982 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003983 CandidateSet.push_back(OverloadCandidate());
3984 OverloadCandidate &Candidate = CandidateSet.back();
3985 Candidate.FoundDecl = FoundDecl;
3986 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3987 Candidate.Viable = false;
3988 Candidate.FailureKind = ovl_fail_bad_deduction;
3989 Candidate.IsSurrogate = false;
3990 Candidate.IgnoreObjectArgument = false;
3991 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3992 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003993 return;
3994 }
Mike Stump11289f42009-09-09 15:08:12 +00003995
Douglas Gregor05155d82009-08-21 23:19:43 +00003996 // Add the conversion function template specialization produced by
3997 // template argument deduction as a candidate.
3998 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003999 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004000 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004001}
4002
Douglas Gregorab7897a2008-11-19 22:57:39 +00004003/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4004/// converts the given @c Object to a function pointer via the
4005/// conversion function @c Conversion, and then attempts to call it
4006/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4007/// the type of function that we'll eventually be calling.
4008void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004009 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004010 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004011 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00004012 QualType ObjectType,
4013 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004014 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004015 if (!CandidateSet.isNewCandidate(Conversion))
4016 return;
4017
Douglas Gregor27381f32009-11-23 12:27:39 +00004018 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004019 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004020
Douglas Gregorab7897a2008-11-19 22:57:39 +00004021 CandidateSet.push_back(OverloadCandidate());
4022 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004023 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004024 Candidate.Function = 0;
4025 Candidate.Surrogate = Conversion;
4026 Candidate.Viable = true;
4027 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004028 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004029 Candidate.Conversions.resize(NumArgs + 1);
4030
4031 // Determine the implicit conversion sequence for the implicit
4032 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004033 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004034 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4035 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004036 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004037 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004038 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004039 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004040 return;
4041 }
4042
4043 // The first conversion is actually a user-defined conversion whose
4044 // first conversion is ObjectInit's standard conversion (which is
4045 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004046 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004047 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004048 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004049 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00004050 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004051 = Candidate.Conversions[0].UserDefined.Before;
4052 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4053
Mike Stump11289f42009-09-09 15:08:12 +00004054 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004055 unsigned NumArgsInProto = Proto->getNumArgs();
4056
4057 // (C++ 13.3.2p2): A candidate function having fewer than m
4058 // parameters is viable only if it has an ellipsis in its parameter
4059 // list (8.3.5).
4060 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4061 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004062 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004063 return;
4064 }
4065
4066 // Function types don't have any default arguments, so just check if
4067 // we have enough arguments.
4068 if (NumArgs < NumArgsInProto) {
4069 // Not enough arguments.
4070 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004071 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004072 return;
4073 }
4074
4075 // Determine the implicit conversion sequences for each of the
4076 // arguments.
4077 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4078 if (ArgIdx < NumArgsInProto) {
4079 // (C++ 13.3.2p3): for F to be a viable function, there shall
4080 // exist for each argument an implicit conversion sequence
4081 // (13.3.3.1) that converts that argument to the corresponding
4082 // parameter of F.
4083 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004084 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004085 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004086 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004087 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004088 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004089 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004090 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004091 break;
4092 }
4093 } else {
4094 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4095 // argument for which there is no corresponding parameter is
4096 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004097 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004098 }
4099 }
4100}
4101
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004102/// \brief Add overload candidates for overloaded operators that are
4103/// member functions.
4104///
4105/// Add the overloaded operator candidates that are member functions
4106/// for the operator Op that was used in an operator expression such
4107/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4108/// CandidateSet will store the added overload candidates. (C++
4109/// [over.match.oper]).
4110void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4111 SourceLocation OpLoc,
4112 Expr **Args, unsigned NumArgs,
4113 OverloadCandidateSet& CandidateSet,
4114 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004115 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4116
4117 // C++ [over.match.oper]p3:
4118 // For a unary operator @ with an operand of a type whose
4119 // cv-unqualified version is T1, and for a binary operator @ with
4120 // a left operand of a type whose cv-unqualified version is T1 and
4121 // a right operand of a type whose cv-unqualified version is T2,
4122 // three sets of candidate functions, designated member
4123 // candidates, non-member candidates and built-in candidates, are
4124 // constructed as follows:
4125 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004126
4127 // -- If T1 is a class type, the set of member candidates is the
4128 // result of the qualified lookup of T1::operator@
4129 // (13.3.1.1.1); otherwise, the set of member candidates is
4130 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004131 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004132 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004133 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004134 return;
Mike Stump11289f42009-09-09 15:08:12 +00004135
John McCall27b18f82009-11-17 02:14:36 +00004136 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4137 LookupQualifiedName(Operators, T1Rec->getDecl());
4138 Operators.suppressDiagnostics();
4139
Mike Stump11289f42009-09-09 15:08:12 +00004140 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004141 OperEnd = Operators.end();
4142 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004143 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004144 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004145 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004146 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004147 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004148}
4149
Douglas Gregora11693b2008-11-12 17:17:38 +00004150/// AddBuiltinCandidate - Add a candidate for a built-in
4151/// operator. ResultTy and ParamTys are the result and parameter types
4152/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004153/// arguments being passed to the candidate. IsAssignmentOperator
4154/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004155/// operator. NumContextualBoolArguments is the number of arguments
4156/// (at the beginning of the argument list) that will be contextually
4157/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004158void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004159 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004160 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004161 bool IsAssignmentOperator,
4162 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004163 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004164 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004165
Douglas Gregora11693b2008-11-12 17:17:38 +00004166 // Add this candidate
4167 CandidateSet.push_back(OverloadCandidate());
4168 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004169 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004170 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004171 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004172 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004173 Candidate.BuiltinTypes.ResultTy = ResultTy;
4174 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4175 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4176
4177 // Determine the implicit conversion sequences for each of the
4178 // arguments.
4179 Candidate.Viable = true;
4180 Candidate.Conversions.resize(NumArgs);
4181 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004182 // C++ [over.match.oper]p4:
4183 // For the built-in assignment operators, conversions of the
4184 // left operand are restricted as follows:
4185 // -- no temporaries are introduced to hold the left operand, and
4186 // -- no user-defined conversions are applied to the left
4187 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004188 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004189 //
4190 // We block these conversions by turning off user-defined
4191 // conversions, since that is the only way that initialization of
4192 // a reference to a non-class type can occur from something that
4193 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004194 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004195 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004196 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004197 Candidate.Conversions[ArgIdx]
4198 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004199 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004200 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004201 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004202 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004203 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004204 }
John McCall0d1da222010-01-12 00:44:57 +00004205 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004206 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004207 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004208 break;
4209 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004210 }
4211}
4212
4213/// BuiltinCandidateTypeSet - A set of types that will be used for the
4214/// candidate operator functions for built-in operators (C++
4215/// [over.built]). The types are separated into pointer types and
4216/// enumeration types.
4217class BuiltinCandidateTypeSet {
4218 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004219 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004220
4221 /// PointerTypes - The set of pointer types that will be used in the
4222 /// built-in candidates.
4223 TypeSet PointerTypes;
4224
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004225 /// MemberPointerTypes - The set of member pointer types that will be
4226 /// used in the built-in candidates.
4227 TypeSet MemberPointerTypes;
4228
Douglas Gregora11693b2008-11-12 17:17:38 +00004229 /// EnumerationTypes - The set of enumeration types that will be
4230 /// used in the built-in candidates.
4231 TypeSet EnumerationTypes;
4232
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004233 /// \brief The set of vector types that will be used in the built-in
4234 /// candidates.
4235 TypeSet VectorTypes;
4236
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004237 /// Sema - The semantic analysis instance where we are building the
4238 /// candidate type set.
4239 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004240
Douglas Gregora11693b2008-11-12 17:17:38 +00004241 /// Context - The AST context in which we will build the type sets.
4242 ASTContext &Context;
4243
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004244 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4245 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004246 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004247
4248public:
4249 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004250 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004251
Mike Stump11289f42009-09-09 15:08:12 +00004252 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004253 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004254
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004255 void AddTypesConvertedFrom(QualType Ty,
4256 SourceLocation Loc,
4257 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004258 bool AllowExplicitConversions,
4259 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004260
4261 /// pointer_begin - First pointer type found;
4262 iterator pointer_begin() { return PointerTypes.begin(); }
4263
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004264 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004265 iterator pointer_end() { return PointerTypes.end(); }
4266
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004267 /// member_pointer_begin - First member pointer type found;
4268 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4269
4270 /// member_pointer_end - Past the last member pointer type found;
4271 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4272
Douglas Gregora11693b2008-11-12 17:17:38 +00004273 /// enumeration_begin - First enumeration type found;
4274 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4275
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004276 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004277 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004278
4279 iterator vector_begin() { return VectorTypes.begin(); }
4280 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004281};
4282
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004283/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004284/// the set of pointer types along with any more-qualified variants of
4285/// that type. For example, if @p Ty is "int const *", this routine
4286/// will add "int const *", "int const volatile *", "int const
4287/// restrict *", and "int const volatile restrict *" to the set of
4288/// pointer types. Returns true if the add of @p Ty itself succeeded,
4289/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004290///
4291/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004292bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004293BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4294 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004295
Douglas Gregora11693b2008-11-12 17:17:38 +00004296 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004297 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004298 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004299
4300 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004301 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004302 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004303 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004304 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004305 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004306 buildObjCPtr = true;
4307 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004308 else
4309 assert(false && "type was not a pointer type!");
4310 }
4311 else
4312 PointeeTy = PointerTy->getPointeeType();
4313
Sebastian Redl4990a632009-11-18 20:39:26 +00004314 // Don't add qualified variants of arrays. For one, they're not allowed
4315 // (the qualifier would sink to the element type), and for another, the
4316 // only overload situation where it matters is subscript or pointer +- int,
4317 // and those shouldn't have qualifier variants anyway.
4318 if (PointeeTy->isArrayType())
4319 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004320 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004321 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004322 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004323 bool hasVolatile = VisibleQuals.hasVolatile();
4324 bool hasRestrict = VisibleQuals.hasRestrict();
4325
John McCall8ccfcb52009-09-24 19:53:00 +00004326 // Iterate through all strict supersets of BaseCVR.
4327 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4328 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004329 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4330 // in the types.
4331 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4332 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004333 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004334 if (!buildObjCPtr)
4335 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4336 else
4337 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004338 }
4339
4340 return true;
4341}
4342
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004343/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4344/// to the set of pointer types along with any more-qualified variants of
4345/// that type. For example, if @p Ty is "int const *", this routine
4346/// will add "int const *", "int const volatile *", "int const
4347/// restrict *", and "int const volatile restrict *" to the set of
4348/// pointer types. Returns true if the add of @p Ty itself succeeded,
4349/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004350///
4351/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004352bool
4353BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4354 QualType Ty) {
4355 // Insert this type.
4356 if (!MemberPointerTypes.insert(Ty))
4357 return false;
4358
John McCall8ccfcb52009-09-24 19:53:00 +00004359 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4360 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004361
John McCall8ccfcb52009-09-24 19:53:00 +00004362 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004363 // Don't add qualified variants of arrays. For one, they're not allowed
4364 // (the qualifier would sink to the element type), and for another, the
4365 // only overload situation where it matters is subscript or pointer +- int,
4366 // and those shouldn't have qualifier variants anyway.
4367 if (PointeeTy->isArrayType())
4368 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004369 const Type *ClassTy = PointerTy->getClass();
4370
4371 // Iterate through all strict supersets of the pointee type's CVR
4372 // qualifiers.
4373 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4374 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4375 if ((CVR | BaseCVR) != CVR) continue;
4376
4377 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4378 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004379 }
4380
4381 return true;
4382}
4383
Douglas Gregora11693b2008-11-12 17:17:38 +00004384/// AddTypesConvertedFrom - Add each of the types to which the type @p
4385/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004386/// primarily interested in pointer types and enumeration types. We also
4387/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004388/// AllowUserConversions is true if we should look at the conversion
4389/// functions of a class type, and AllowExplicitConversions if we
4390/// should also include the explicit conversion functions of a class
4391/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004392void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004393BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004394 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004395 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004396 bool AllowExplicitConversions,
4397 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004398 // Only deal with canonical types.
4399 Ty = Context.getCanonicalType(Ty);
4400
4401 // Look through reference types; they aren't part of the type of an
4402 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004403 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004404 Ty = RefTy->getPointeeType();
4405
4406 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004407 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004408
Sebastian Redl65ae2002009-11-05 16:36:20 +00004409 // If we're dealing with an array type, decay to the pointer.
4410 if (Ty->isArrayType())
4411 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004412 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4413 PointerTypes.insert(Ty);
4414 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004415 // Insert our type, and its more-qualified variants, into the set
4416 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004417 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004418 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004419 } else if (Ty->isMemberPointerType()) {
4420 // Member pointers are far easier, since the pointee can't be converted.
4421 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4422 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004423 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004424 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004425 } else if (Ty->isVectorType()) {
4426 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004427 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004428 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004429 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004430 // No conversion functions in incomplete types.
4431 return;
4432 }
Mike Stump11289f42009-09-09 15:08:12 +00004433
Douglas Gregora11693b2008-11-12 17:17:38 +00004434 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004435 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004436 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004437 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004438 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004439 NamedDecl *D = I.getDecl();
4440 if (isa<UsingShadowDecl>(D))
4441 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004442
Mike Stump11289f42009-09-09 15:08:12 +00004443 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004444 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004445 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004446 continue;
4447
John McCallda4458e2010-03-31 01:36:47 +00004448 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004449 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004450 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004451 VisibleQuals);
4452 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004453 }
4454 }
4455 }
4456}
4457
Douglas Gregor84605ae2009-08-24 13:43:27 +00004458/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4459/// the volatile- and non-volatile-qualified assignment operators for the
4460/// given type to the candidate set.
4461static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4462 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004463 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004464 unsigned NumArgs,
4465 OverloadCandidateSet &CandidateSet) {
4466 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004467
Douglas Gregor84605ae2009-08-24 13:43:27 +00004468 // T& operator=(T&, T)
4469 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4470 ParamTypes[1] = T;
4471 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4472 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004473
Douglas Gregor84605ae2009-08-24 13:43:27 +00004474 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4475 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004476 ParamTypes[0]
4477 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004478 ParamTypes[1] = T;
4479 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004480 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004481 }
4482}
Mike Stump11289f42009-09-09 15:08:12 +00004483
Sebastian Redl1054fae2009-10-25 17:03:50 +00004484/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4485/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004486static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4487 Qualifiers VRQuals;
4488 const RecordType *TyRec;
4489 if (const MemberPointerType *RHSMPType =
4490 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004491 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004492 else
4493 TyRec = ArgExpr->getType()->getAs<RecordType>();
4494 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004495 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004496 VRQuals.addVolatile();
4497 VRQuals.addRestrict();
4498 return VRQuals;
4499 }
4500
4501 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004502 if (!ClassDecl->hasDefinition())
4503 return VRQuals;
4504
John McCallad371252010-01-20 00:46:10 +00004505 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004506 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004507
John McCallad371252010-01-20 00:46:10 +00004508 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004509 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004510 NamedDecl *D = I.getDecl();
4511 if (isa<UsingShadowDecl>(D))
4512 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4513 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004514 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4515 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4516 CanTy = ResTypeRef->getPointeeType();
4517 // Need to go down the pointer/mempointer chain and add qualifiers
4518 // as see them.
4519 bool done = false;
4520 while (!done) {
4521 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4522 CanTy = ResTypePtr->getPointeeType();
4523 else if (const MemberPointerType *ResTypeMPtr =
4524 CanTy->getAs<MemberPointerType>())
4525 CanTy = ResTypeMPtr->getPointeeType();
4526 else
4527 done = true;
4528 if (CanTy.isVolatileQualified())
4529 VRQuals.addVolatile();
4530 if (CanTy.isRestrictQualified())
4531 VRQuals.addRestrict();
4532 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4533 return VRQuals;
4534 }
4535 }
4536 }
4537 return VRQuals;
4538}
John McCall52872982010-11-13 05:51:15 +00004539
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004540
Douglas Gregord08452f2008-11-19 15:42:04 +00004541/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4542/// operator overloads to the candidate set (C++ [over.built]), based
4543/// on the operator @p Op and the arguments given. For example, if the
4544/// operator is a binary '+', this routine might add "int
4545/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004546void
Mike Stump11289f42009-09-09 15:08:12 +00004547Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004548 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004549 Expr **Args, unsigned NumArgs,
4550 OverloadCandidateSet& CandidateSet) {
John McCall52872982010-11-13 05:51:15 +00004551 // Information about arithmetic types useful to builtin-type
4552 // calculations.
4553
4554 // The "promoted arithmetic types" are the arithmetic
4555 // types are that preserved by promotion (C++ [over.built]p2).
4556
4557 static const unsigned FirstIntegralType = 3;
4558 static const unsigned LastIntegralType = 18;
4559 static const unsigned FirstPromotedIntegralType = 3,
4560 LastPromotedIntegralType = 9;
4561 static const unsigned FirstPromotedArithmeticType = 0,
4562 LastPromotedArithmeticType = 9;
4563 static const unsigned NumArithmeticTypes = 18;
4564
John McCall988ffb72010-11-13 02:01:09 +00004565 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall52872982010-11-13 05:51:15 +00004566 // Start of promoted types.
4567 &ASTContext::FloatTy,
4568 &ASTContext::DoubleTy,
4569 &ASTContext::LongDoubleTy,
4570
4571 // Start of integral types.
4572 &ASTContext::IntTy,
4573 &ASTContext::LongTy,
4574 &ASTContext::LongLongTy,
4575 &ASTContext::UnsignedIntTy,
4576 &ASTContext::UnsignedLongTy,
4577 &ASTContext::UnsignedLongLongTy,
4578 // End of promoted types.
4579
John McCall988ffb72010-11-13 02:01:09 +00004580 &ASTContext::BoolTy,
4581 &ASTContext::CharTy,
4582 &ASTContext::WCharTy,
4583 &ASTContext::Char16Ty,
4584 &ASTContext::Char32Ty,
4585 &ASTContext::SignedCharTy,
4586 &ASTContext::ShortTy,
4587 &ASTContext::UnsignedCharTy,
John McCall52872982010-11-13 05:51:15 +00004588 &ASTContext::UnsignedShortTy
4589 // End of integral types.
Douglas Gregora11693b2008-11-12 17:17:38 +00004590 };
John McCall52872982010-11-13 05:51:15 +00004591 // FIXME: What about complex?
John McCall988ffb72010-11-13 02:01:09 +00004592 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004593 "Invalid first promoted integral type");
4594 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall988ffb72010-11-13 02:01:09 +00004595 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004596 "Invalid last promoted integral type");
John McCall52872982010-11-13 05:51:15 +00004597 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004598 "Invalid first promoted arithmetic type");
4599 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall52872982010-11-13 05:51:15 +00004600 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004601 "Invalid last promoted arithmetic type");
John McCall52872982010-11-13 05:51:15 +00004602
4603 // Accelerator table for performing the usual arithmetic conversions.
4604 // The rules are basically:
4605 // - if either is floating-point, use the wider floating-point
4606 // - if same signedness, use the higher rank
4607 // - if same size, use unsigned of the higher rank
4608 // - use the larger type
4609 // These rules, together with the axiom that higher ranks are
4610 // never smaller, are sufficient to precompute all of these results
4611 // *except* when dealing with signed types of higher rank.
4612 // (we could precompute SLL x UI for all known platforms, but it's
4613 // better not to make any assumptions).
4614 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4615 static PromT UsualArithmeticConversionsTypes
4616 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4617 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4618 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4619 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4620 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4621 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4622 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4623 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4624 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4625 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4626 };
4627 struct UsualArithmeticConversionsType {
4628 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4629 assert(L < LastPromotedArithmeticType);
4630 assert(R < LastPromotedArithmeticType);
4631 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4632
4633 // Fast path: the table gives us a concrete answer.
4634 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4635
4636 // Slow path: we need to compare widths.
4637 // An invariant is that the signed type has higher rank.
4638 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4639 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4640
4641 // If they're different widths, use the signed type.
4642 if (LW > RW) return LT;
4643 else if (LW > RW) return RT;
4644
4645 // Otherwise, use the unsigned type of the signed type's rank.
4646 if (L == SL || R == SL) return C.UnsignedLongTy;
4647 assert(L == SLL || R == SLL);
4648 return C.UnsignedLongLongTy;
4649 }
4650 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004651
Douglas Gregora11693b2008-11-12 17:17:38 +00004652 // Find all of the types that the arguments can convert to, but only
4653 // if the operator we're looking at has built-in operator candidates
4654 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004655 Qualifiers VisibleTypeConversionsQuals;
4656 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004657 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4658 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4659
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004660 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4661 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4662 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4663 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4664 OpLoc,
4665 true,
4666 (Op == OO_Exclaim ||
4667 Op == OO_AmpAmp ||
4668 Op == OO_PipePipe),
4669 VisibleTypeConversionsQuals);
4670 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004671
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004672 // C++ [over.built]p1:
4673 // If there is a user-written candidate with the same name and parameter
4674 // types as a built-in candidate operator function, the built-in operator
4675 // function is hidden and is not included in the set of candidate functions.
4676 //
4677 // The text is actually in a note, but if we don't implement it then we end
4678 // up with ambiguities when the user provides an overloaded operator for
4679 // an enumeration type. Note that only enumeration types have this problem,
4680 // so we track which enumeration types we've seen operators for.
4681 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4682 UserDefinedBinaryOperators;
4683
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004684 /// Set of (canonical) types that we've already handled.
4685 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4686
4687 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4688 if (CandidateTypes[ArgIdx].enumeration_begin()
4689 != CandidateTypes[ArgIdx].enumeration_end()) {
4690 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4691 CEnd = CandidateSet.end();
4692 C != CEnd; ++C) {
4693 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4694 continue;
4695
4696 // Check if the first parameter is of enumeration type.
4697 QualType FirstParamType
4698 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4699 if (!FirstParamType->isEnumeralType())
4700 continue;
4701
4702 // Check if the second parameter is of enumeration type.
4703 QualType SecondParamType
4704 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4705 if (!SecondParamType->isEnumeralType())
4706 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004707
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004708 // Add this operator to the set of known user-defined operators.
4709 UserDefinedBinaryOperators.insert(
4710 std::make_pair(Context.getCanonicalType(FirstParamType),
4711 Context.getCanonicalType(SecondParamType)));
4712 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004713 }
4714 }
4715
Douglas Gregora11693b2008-11-12 17:17:38 +00004716 bool isComparison = false;
4717 switch (Op) {
4718 case OO_None:
4719 case NUM_OVERLOADED_OPERATORS:
4720 assert(false && "Expected an overloaded operator");
4721 break;
4722
Douglas Gregord08452f2008-11-19 15:42:04 +00004723 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004724 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004725 goto UnaryStar;
4726 else
4727 goto BinaryStar;
4728 break;
4729
4730 case OO_Plus: // '+' is either unary or binary
4731 if (NumArgs == 1)
4732 goto UnaryPlus;
4733 else
4734 goto BinaryPlus;
4735 break;
4736
4737 case OO_Minus: // '-' is either unary or binary
4738 if (NumArgs == 1)
4739 goto UnaryMinus;
4740 else
4741 goto BinaryMinus;
4742 break;
4743
4744 case OO_Amp: // '&' is either unary or binary
4745 if (NumArgs == 1)
4746 goto UnaryAmp;
4747 else
4748 goto BinaryAmp;
4749
4750 case OO_PlusPlus:
4751 case OO_MinusMinus:
4752 // C++ [over.built]p3:
4753 //
4754 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4755 // is either volatile or empty, there exist candidate operator
4756 // functions of the form
4757 //
4758 // VQ T& operator++(VQ T&);
4759 // T operator++(VQ T&, int);
4760 //
4761 // C++ [over.built]p4:
4762 //
4763 // For every pair (T, VQ), where T is an arithmetic type other
4764 // than bool, and VQ is either volatile or empty, there exist
4765 // candidate operator functions of the form
4766 //
4767 // VQ T& operator--(VQ T&);
4768 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004769 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004770 Arith < NumArithmeticTypes; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004771 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004772 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004773 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004774
4775 // Non-volatile version.
4776 if (NumArgs == 1)
4777 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4778 else
4779 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004780 // heuristic to reduce number of builtin candidates in the set.
4781 // Add volatile version only if there are conversions to a volatile type.
4782 if (VisibleTypeConversionsQuals.hasVolatile()) {
4783 // Volatile version
4784 ParamTypes[0]
4785 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4786 if (NumArgs == 1)
4787 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4788 else
4789 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4790 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004791 }
4792
4793 // C++ [over.built]p5:
4794 //
4795 // For every pair (T, VQ), where T is a cv-qualified or
4796 // cv-unqualified object type, and VQ is either volatile or
4797 // empty, there exist candidate operator functions of the form
4798 //
4799 // T*VQ& operator++(T*VQ&);
4800 // T*VQ& operator--(T*VQ&);
4801 // T* operator++(T*VQ&, int);
4802 // T* operator--(T*VQ&, int);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004803 for (BuiltinCandidateTypeSet::iterator
4804 Ptr = CandidateTypes[0].pointer_begin(),
4805 PtrEnd = CandidateTypes[0].pointer_end();
4806 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004807 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004808 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004809 continue;
4810
Mike Stump11289f42009-09-09 15:08:12 +00004811 QualType ParamTypes[2] = {
4812 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004813 };
Mike Stump11289f42009-09-09 15:08:12 +00004814
Douglas Gregord08452f2008-11-19 15:42:04 +00004815 // Without volatile
4816 if (NumArgs == 1)
4817 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4818 else
4819 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4820
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004821 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4822 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004823 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004824 ParamTypes[0]
4825 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004826 if (NumArgs == 1)
4827 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4828 else
4829 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4830 }
4831 }
4832 break;
4833
4834 UnaryStar:
4835 // C++ [over.built]p6:
4836 // For every cv-qualified or cv-unqualified object type T, there
4837 // exist candidate operator functions of the form
4838 //
4839 // T& operator*(T*);
4840 //
4841 // C++ [over.built]p7:
4842 // For every function type T, there exist candidate operator
4843 // functions of the form
4844 // T& operator*(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004845 for (BuiltinCandidateTypeSet::iterator
4846 Ptr = CandidateTypes[0].pointer_begin(),
4847 PtrEnd = CandidateTypes[0].pointer_end();
4848 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004849 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004850 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004851 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004852 &ParamTy, Args, 1, CandidateSet);
4853 }
4854 break;
4855
4856 UnaryPlus:
4857 // C++ [over.built]p8:
4858 // For every type T, there exist candidate operator functions of
4859 // the form
4860 //
4861 // T* operator+(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004862 for (BuiltinCandidateTypeSet::iterator
4863 Ptr = CandidateTypes[0].pointer_begin(),
4864 PtrEnd = CandidateTypes[0].pointer_end();
4865 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004866 QualType ParamTy = *Ptr;
4867 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4868 }
Mike Stump11289f42009-09-09 15:08:12 +00004869
Douglas Gregord08452f2008-11-19 15:42:04 +00004870 // Fall through
4871
4872 UnaryMinus:
4873 // C++ [over.built]p9:
4874 // For every promoted arithmetic type T, there exist candidate
4875 // operator functions of the form
4876 //
4877 // T operator+(T);
4878 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004879 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004880 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004881 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregord08452f2008-11-19 15:42:04 +00004882 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4883 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004884
4885 // Extension: We also add these operators for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004886 for (BuiltinCandidateTypeSet::iterator
4887 Vec = CandidateTypes[0].vector_begin(),
4888 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004889 Vec != VecEnd; ++Vec) {
4890 QualType VecTy = *Vec;
4891 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4892 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004893 break;
4894
4895 case OO_Tilde:
4896 // C++ [over.built]p10:
4897 // For every promoted integral type T, there exist candidate
4898 // operator functions of the form
4899 //
4900 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004901 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004902 Int < LastPromotedIntegralType; ++Int) {
John McCall988ffb72010-11-13 02:01:09 +00004903 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregord08452f2008-11-19 15:42:04 +00004904 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4905 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004906
4907 // Extension: We also add this operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004908 for (BuiltinCandidateTypeSet::iterator
4909 Vec = CandidateTypes[0].vector_begin(),
4910 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004911 Vec != VecEnd; ++Vec) {
4912 QualType VecTy = *Vec;
4913 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4914 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004915 break;
4916
Douglas Gregora11693b2008-11-12 17:17:38 +00004917 case OO_New:
4918 case OO_Delete:
4919 case OO_Array_New:
4920 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004921 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004922 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004923 break;
4924
4925 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004926 UnaryAmp:
4927 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004928 // C++ [over.match.oper]p3:
4929 // -- For the operator ',', the unary operator '&', or the
4930 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004931 break;
4932
Douglas Gregor84605ae2009-08-24 13:43:27 +00004933 case OO_EqualEqual:
4934 case OO_ExclaimEqual:
4935 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004936 // For every pointer to member type T, there exist candidate operator
4937 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004938 //
4939 // bool operator==(T,T);
4940 // bool operator!=(T,T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004941 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4942 for (BuiltinCandidateTypeSet::iterator
4943 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4944 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4945 MemPtr != MemPtrEnd;
4946 ++MemPtr) {
4947 // Don't add the same builtin candidate twice.
4948 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4949 continue;
4950
4951 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4952 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4953 }
Douglas Gregor84605ae2009-08-24 13:43:27 +00004954 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004955 AddedTypes.clear();
4956
Douglas Gregor84605ae2009-08-24 13:43:27 +00004957 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004958
Douglas Gregora11693b2008-11-12 17:17:38 +00004959 case OO_Less:
4960 case OO_Greater:
4961 case OO_LessEqual:
4962 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004963 // C++ [over.built]p15:
4964 //
4965 // For every pointer or enumeration type T, there exist
4966 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004967 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004968 // bool operator<(T, T);
4969 // bool operator>(T, T);
4970 // bool operator<=(T, T);
4971 // bool operator>=(T, T);
4972 // bool operator==(T, T);
4973 // bool operator!=(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004974 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4975 for (BuiltinCandidateTypeSet::iterator
4976 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4977 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4978 Ptr != PtrEnd; ++Ptr) {
4979 // Don't add the same builtin candidate twice.
4980 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4981 continue;
4982
4983 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004984 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004985 }
4986 for (BuiltinCandidateTypeSet::iterator
4987 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4988 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4989 Enum != EnumEnd; ++Enum) {
4990 // Don't add the same builtin candidate twice.
4991 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4992 continue;
4993
4994 QualType ParamTypes[2] = { *Enum, *Enum };
4995 CanQualType CanonType = Context.getCanonicalType(*Enum);
4996 if (!UserDefinedBinaryOperators.count(
4997 std::make_pair(CanonType, CanonType)))
4998 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4999 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005000 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005001 AddedTypes.clear();
5002
Douglas Gregora11693b2008-11-12 17:17:38 +00005003 // Fall through.
5004 isComparison = true;
5005
Douglas Gregord08452f2008-11-19 15:42:04 +00005006 BinaryPlus:
5007 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00005008 if (!isComparison) {
5009 // We didn't fall through, so we must have OO_Plus or OO_Minus.
5010
5011 // C++ [over.built]p13:
5012 //
5013 // For every cv-qualified or cv-unqualified object type T
5014 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005015 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005016 // T* operator+(T*, ptrdiff_t);
5017 // T& operator[](T*, ptrdiff_t); [BELOW]
5018 // T* operator-(T*, ptrdiff_t);
5019 // T* operator+(ptrdiff_t, T*);
5020 // T& operator[](ptrdiff_t, T*); [BELOW]
5021 //
5022 // C++ [over.built]p14:
5023 //
5024 // For every T, where T is a pointer to object type, there
5025 // exist candidate operator functions of the form
5026 //
5027 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005028 for (BuiltinCandidateTypeSet::iterator
5029 Ptr = CandidateTypes[0].pointer_begin(),
5030 PtrEnd = CandidateTypes[0].pointer_end();
5031 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005032 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
5033
5034 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5035 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5036
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005037 if (Op == OO_Minus) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005038 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005039 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5040 continue;
5041
Douglas Gregora11693b2008-11-12 17:17:38 +00005042 ParamTypes[1] = *Ptr;
5043 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5044 Args, 2, CandidateSet);
5045 }
5046 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005047
5048 for (BuiltinCandidateTypeSet::iterator
5049 Ptr = CandidateTypes[1].pointer_begin(),
5050 PtrEnd = CandidateTypes[1].pointer_end();
5051 Ptr != PtrEnd; ++Ptr) {
5052 if (Op == OO_Plus) {
5053 // T* operator+(ptrdiff_t, T*);
5054 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5055 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5056 } else {
5057 // ptrdiff_t operator-(T, T);
5058 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5059 continue;
5060
5061 QualType ParamTypes[2] = { *Ptr, *Ptr };
5062 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5063 Args, 2, CandidateSet);
5064 }
5065 }
5066
5067 AddedTypes.clear();
Douglas Gregora11693b2008-11-12 17:17:38 +00005068 }
5069 // Fall through
5070
Douglas Gregora11693b2008-11-12 17:17:38 +00005071 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00005072 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00005073 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00005074 // C++ [over.built]p12:
5075 //
5076 // For every pair of promoted arithmetic types L and R, there
5077 // exist candidate operator functions of the form
5078 //
5079 // LR operator*(L, R);
5080 // LR operator/(L, R);
5081 // LR operator+(L, R);
5082 // LR operator-(L, R);
5083 // bool operator<(L, R);
5084 // bool operator>(L, R);
5085 // bool operator<=(L, R);
5086 // bool operator>=(L, R);
5087 // bool operator==(L, R);
5088 // bool operator!=(L, R);
5089 //
5090 // where LR is the result of the usual arithmetic conversions
5091 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005092 //
5093 // C++ [over.built]p24:
5094 //
5095 // For every pair of promoted arithmetic types L and R, there exist
5096 // candidate operator functions of the form
5097 //
5098 // LR operator?(bool, L, R);
5099 //
5100 // where LR is the result of the usual arithmetic conversions
5101 // between types L and R.
5102 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005103 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005104 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005105 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005106 Right < LastPromotedArithmeticType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005107 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5108 Context.*ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005109 QualType Result
5110 = isComparison
5111 ? Context.BoolTy
John McCall52872982010-11-13 05:51:15 +00005112 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005113 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5114 }
5115 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005116
5117 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5118 // conditional operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005119 for (BuiltinCandidateTypeSet::iterator
5120 Vec1 = CandidateTypes[0].vector_begin(),
5121 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005122 Vec1 != Vec1End; ++Vec1)
5123 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005124 Vec2 = CandidateTypes[1].vector_begin(),
5125 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005126 Vec2 != Vec2End; ++Vec2) {
5127 QualType LandR[2] = { *Vec1, *Vec2 };
5128 QualType Result;
5129 if (isComparison)
5130 Result = Context.BoolTy;
5131 else {
5132 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5133 Result = *Vec1;
5134 else
5135 Result = *Vec2;
5136 }
5137
5138 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5139 }
5140
Douglas Gregora11693b2008-11-12 17:17:38 +00005141 break;
5142
5143 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005144 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005145 case OO_Caret:
5146 case OO_Pipe:
5147 case OO_LessLess:
5148 case OO_GreaterGreater:
5149 // C++ [over.built]p17:
5150 //
5151 // For every pair of promoted integral types L and R, there
5152 // exist candidate operator functions of the form
5153 //
5154 // LR operator%(L, R);
5155 // LR operator&(L, R);
5156 // LR operator^(L, R);
5157 // LR operator|(L, R);
5158 // L operator<<(L, R);
5159 // L operator>>(L, R);
5160 //
5161 // where LR is the result of the usual arithmetic conversions
5162 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00005163 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005164 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005165 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005166 Right < LastPromotedIntegralType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005167 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5168 Context.*ArithmeticTypes[Right] };
Douglas Gregora11693b2008-11-12 17:17:38 +00005169 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5170 ? LandR[0]
John McCall52872982010-11-13 05:51:15 +00005171 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005172 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5173 }
5174 }
5175 break;
5176
5177 case OO_Equal:
5178 // C++ [over.built]p20:
5179 //
5180 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00005181 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00005182 // empty, there exist candidate operator functions of the form
5183 //
5184 // VQ T& operator=(VQ T&, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005185 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5186 for (BuiltinCandidateTypeSet::iterator
5187 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5188 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5189 Enum != EnumEnd; ++Enum) {
5190 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5191 continue;
5192
5193 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5194 CandidateSet);
5195 }
5196
5197 for (BuiltinCandidateTypeSet::iterator
5198 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5199 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5200 MemPtr != MemPtrEnd; ++MemPtr) {
5201 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5202 continue;
5203
5204 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5205 CandidateSet);
5206 }
5207 }
5208 AddedTypes.clear();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005209
5210 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005211
5212 case OO_PlusEqual:
5213 case OO_MinusEqual:
5214 // C++ [over.built]p19:
5215 //
5216 // For every pair (T, VQ), where T is any type and VQ is either
5217 // volatile or empty, there exist candidate operator functions
5218 // of the form
5219 //
5220 // T*VQ& operator=(T*VQ&, T*);
5221 //
5222 // C++ [over.built]p21:
5223 //
5224 // For every pair (T, VQ), where T is a cv-qualified or
5225 // cv-unqualified object type and VQ is either volatile or
5226 // empty, there exist candidate operator functions of the form
5227 //
5228 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5229 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005230 for (BuiltinCandidateTypeSet::iterator
5231 Ptr = CandidateTypes[0].pointer_begin(),
5232 PtrEnd = CandidateTypes[0].pointer_end();
5233 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005234 QualType ParamTypes[2];
5235 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5236
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005237 // If this is operator=, keep track of the builtin candidates we added.
5238 if (Op == OO_Equal)
5239 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5240
Douglas Gregora11693b2008-11-12 17:17:38 +00005241 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005242 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005243 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5244 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005245
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005246 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5247 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005248 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005249 ParamTypes[0]
5250 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005251 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5252 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005253 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005254 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005255
5256 if (Op == OO_Equal) {
5257 for (BuiltinCandidateTypeSet::iterator
5258 Ptr = CandidateTypes[1].pointer_begin(),
5259 PtrEnd = CandidateTypes[1].pointer_end();
5260 Ptr != PtrEnd; ++Ptr) {
5261 // Make sure we don't add the same candidate twice.
5262 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5263 continue;
5264
5265 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5266
5267 // non-volatile version
5268 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5269 /*IsAssigmentOperator=*/true);
5270
5271 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5272 VisibleTypeConversionsQuals.hasVolatile()) {
5273 // volatile version
5274 ParamTypes[0]
5275 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5276 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5277 /*IsAssigmentOperator=*/true);
5278 }
5279 }
5280 AddedTypes.clear();
5281 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005282 // Fall through.
5283
5284 case OO_StarEqual:
5285 case OO_SlashEqual:
5286 // C++ [over.built]p18:
5287 //
5288 // For every triple (L, VQ, R), where L is an arithmetic type,
5289 // VQ is either volatile or empty, and R is a promoted
5290 // arithmetic type, there exist candidate operator functions of
5291 // the form
5292 //
5293 // VQ L& operator=(VQ L&, R);
5294 // VQ L& operator*=(VQ L&, R);
5295 // VQ L& operator/=(VQ L&, R);
5296 // VQ L& operator+=(VQ L&, R);
5297 // VQ L& operator-=(VQ L&, R);
5298 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005299 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005300 Right < LastPromotedArithmeticType; ++Right) {
5301 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005302 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005303
5304 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005305 ParamTypes[0] =
5306 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005307 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5308 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005309
5310 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005311 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall988ffb72010-11-13 02:01:09 +00005312 ParamTypes[0] =
5313 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005314 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5315 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5316 /*IsAssigmentOperator=*/Op == OO_Equal);
5317 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005318 }
5319 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005320
5321 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005322 for (BuiltinCandidateTypeSet::iterator
5323 Vec1 = CandidateTypes[0].vector_begin(),
5324 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005325 Vec1 != Vec1End; ++Vec1)
5326 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005327 Vec2 = CandidateTypes[1].vector_begin(),
5328 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005329 Vec2 != Vec2End; ++Vec2) {
5330 QualType ParamTypes[2];
5331 ParamTypes[1] = *Vec2;
5332 // Add this built-in operator as a candidate (VQ is empty).
5333 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5334 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5335 /*IsAssigmentOperator=*/Op == OO_Equal);
5336
5337 // Add this built-in operator as a candidate (VQ is 'volatile').
5338 if (VisibleTypeConversionsQuals.hasVolatile()) {
5339 ParamTypes[0] = Context.getVolatileType(*Vec1);
5340 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5341 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5342 /*IsAssigmentOperator=*/Op == OO_Equal);
5343 }
5344 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005345 break;
5346
5347 case OO_PercentEqual:
5348 case OO_LessLessEqual:
5349 case OO_GreaterGreaterEqual:
5350 case OO_AmpEqual:
5351 case OO_CaretEqual:
5352 case OO_PipeEqual:
5353 // C++ [over.built]p22:
5354 //
5355 // For every triple (L, VQ, R), where L is an integral type, VQ
5356 // is either volatile or empty, and R is a promoted integral
5357 // type, there exist candidate operator functions of the form
5358 //
5359 // VQ L& operator%=(VQ L&, R);
5360 // VQ L& operator<<=(VQ L&, R);
5361 // VQ L& operator>>=(VQ L&, R);
5362 // VQ L& operator&=(VQ L&, R);
5363 // VQ L& operator^=(VQ L&, R);
5364 // VQ L& operator|=(VQ L&, R);
5365 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005366 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005367 Right < LastPromotedIntegralType; ++Right) {
5368 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005369 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005370
5371 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005372 ParamTypes[0] =
5373 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005374 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005375 if (VisibleTypeConversionsQuals.hasVolatile()) {
5376 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall988ffb72010-11-13 02:01:09 +00005377 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005378 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5379 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5380 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5381 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005382 }
5383 }
5384 break;
5385
Douglas Gregord08452f2008-11-19 15:42:04 +00005386 case OO_Exclaim: {
5387 // C++ [over.operator]p23:
5388 //
5389 // There also exist candidate operator functions of the form
5390 //
Mike Stump11289f42009-09-09 15:08:12 +00005391 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005392 // bool operator&&(bool, bool); [BELOW]
5393 // bool operator||(bool, bool); [BELOW]
5394 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005395 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5396 /*IsAssignmentOperator=*/false,
5397 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005398 break;
5399 }
5400
Douglas Gregora11693b2008-11-12 17:17:38 +00005401 case OO_AmpAmp:
5402 case OO_PipePipe: {
5403 // C++ [over.operator]p23:
5404 //
5405 // There also exist candidate operator functions of the form
5406 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005407 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005408 // bool operator&&(bool, bool);
5409 // bool operator||(bool, bool);
5410 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005411 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5412 /*IsAssignmentOperator=*/false,
5413 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005414 break;
5415 }
5416
5417 case OO_Subscript:
5418 // C++ [over.built]p13:
5419 //
5420 // For every cv-qualified or cv-unqualified object type T there
5421 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005422 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005423 // T* operator+(T*, ptrdiff_t); [ABOVE]
5424 // T& operator[](T*, ptrdiff_t);
5425 // T* operator-(T*, ptrdiff_t); [ABOVE]
5426 // T* operator+(ptrdiff_t, T*); [ABOVE]
5427 // T& operator[](ptrdiff_t, T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005428 for (BuiltinCandidateTypeSet::iterator
5429 Ptr = CandidateTypes[0].pointer_begin(),
5430 PtrEnd = CandidateTypes[0].pointer_end();
5431 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005432 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005433 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005434 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005435
5436 // T& operator[](T*, ptrdiff_t)
5437 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005438 }
5439
5440 for (BuiltinCandidateTypeSet::iterator
5441 Ptr = CandidateTypes[1].pointer_begin(),
5442 PtrEnd = CandidateTypes[1].pointer_end();
5443 Ptr != PtrEnd; ++Ptr) {
5444 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5445 QualType PointeeType = (*Ptr)->getPointeeType();
5446 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5447
5448 // T& operator[](ptrdiff_t, T*)
Douglas Gregora11693b2008-11-12 17:17:38 +00005449 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005450 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005451 break;
5452
5453 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005454 // C++ [over.built]p11:
5455 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5456 // C1 is the same type as C2 or is a derived class of C2, T is an object
5457 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5458 // there exist candidate operator functions of the form
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005459 //
5460 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5461 //
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005462 // where CV12 is the union of CV1 and CV2.
5463 {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005464 for (BuiltinCandidateTypeSet::iterator
5465 Ptr = CandidateTypes[0].pointer_begin(),
5466 PtrEnd = CandidateTypes[0].pointer_end();
5467 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005468 QualType C1Ty = (*Ptr);
5469 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005470 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005471 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5472 if (!isa<RecordType>(C1))
5473 continue;
5474 // heuristic to reduce number of builtin candidates in the set.
5475 // Add volatile/restrict version only if there are conversions to a
5476 // volatile/restrict type.
5477 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5478 continue;
5479 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5480 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005481 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005482 MemPtr = CandidateTypes[1].member_pointer_begin(),
5483 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005484 MemPtr != MemPtrEnd; ++MemPtr) {
5485 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5486 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005487 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005488 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5489 break;
5490 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5491 // build CV12 T&
5492 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005493 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5494 T.isVolatileQualified())
5495 continue;
5496 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5497 T.isRestrictQualified())
5498 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005499 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005500 QualType ResultTy = Context.getLValueReferenceType(T);
5501 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5502 }
5503 }
5504 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005505 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005506
5507 case OO_Conditional:
5508 // Note that we don't consider the first argument, since it has been
5509 // contextually converted to bool long ago. The candidates below are
5510 // therefore added as binary.
5511 //
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005512 // C++ [over.built]p25:
5513 // For every type T, where T is a pointer, pointer-to-member, or scoped
5514 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl1a99f442009-04-16 17:51:27 +00005515 //
5516 // T operator?(bool, T, T);
5517 //
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005518 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5519 for (BuiltinCandidateTypeSet::iterator
5520 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5521 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5522 Ptr != PtrEnd; ++Ptr) {
5523 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5524 continue;
5525
5526 QualType ParamTypes[2] = { *Ptr, *Ptr };
5527 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5528 }
5529
5530 for (BuiltinCandidateTypeSet::iterator
5531 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5532 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5533 MemPtr != MemPtrEnd; ++MemPtr) {
5534 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5535 continue;
5536
5537 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5538 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5539 }
5540
5541 if (getLangOptions().CPlusPlus0x) {
5542 for (BuiltinCandidateTypeSet::iterator
5543 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5544 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5545 Enum != EnumEnd; ++Enum) {
5546 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5547 continue;
5548
5549 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5550 continue;
5551
5552 QualType ParamTypes[2] = { *Enum, *Enum };
5553 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5554 }
5555 }
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005556 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005557 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005558 }
5559}
5560
Douglas Gregore254f902009-02-04 00:32:51 +00005561/// \brief Add function candidates found via argument-dependent lookup
5562/// to the set of overloading candidates.
5563///
5564/// This routine performs argument-dependent name lookup based on the
5565/// given function name (which may also be an operator name) and adds
5566/// all of the overload candidates found by ADL to the overload
5567/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005568void
Douglas Gregore254f902009-02-04 00:32:51 +00005569Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005570 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005571 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005572 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005573 OverloadCandidateSet& CandidateSet,
5574 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005575 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005576
John McCall91f61fc2010-01-26 06:04:06 +00005577 // FIXME: This approach for uniquing ADL results (and removing
5578 // redundant candidates from the set) relies on pointer-equality,
5579 // which means we need to key off the canonical decl. However,
5580 // always going back to the canonical decl might not get us the
5581 // right set of default arguments. What default arguments are
5582 // we supposed to consider on ADL candidates, anyway?
5583
Douglas Gregorcabea402009-09-22 15:41:20 +00005584 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005585 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005586
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005587 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005588 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5589 CandEnd = CandidateSet.end();
5590 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005591 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005592 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005593 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005594 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005595 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005596
5597 // For each of the ADL candidates we found, add it to the overload
5598 // set.
John McCall8fe68082010-01-26 07:16:45 +00005599 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005600 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005601 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005602 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005603 continue;
5604
John McCalla0296f72010-03-19 07:35:19 +00005605 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005606 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005607 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005608 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005609 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005610 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005611 }
Douglas Gregore254f902009-02-04 00:32:51 +00005612}
5613
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005614/// isBetterOverloadCandidate - Determines whether the first overload
5615/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005616bool
John McCall5c32be02010-08-24 20:38:10 +00005617isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005618 const OverloadCandidate &Cand1,
5619 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005620 SourceLocation Loc,
5621 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005622 // Define viable functions to be better candidates than non-viable
5623 // functions.
5624 if (!Cand2.Viable)
5625 return Cand1.Viable;
5626 else if (!Cand1.Viable)
5627 return false;
5628
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005629 // C++ [over.match.best]p1:
5630 //
5631 // -- if F is a static member function, ICS1(F) is defined such
5632 // that ICS1(F) is neither better nor worse than ICS1(G) for
5633 // any function G, and, symmetrically, ICS1(G) is neither
5634 // better nor worse than ICS1(F).
5635 unsigned StartArg = 0;
5636 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5637 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005638
Douglas Gregord3cb3562009-07-07 23:38:56 +00005639 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005640 // A viable function F1 is defined to be a better function than another
5641 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005642 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005643 unsigned NumArgs = Cand1.Conversions.size();
5644 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5645 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005646 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005647 switch (CompareImplicitConversionSequences(S,
5648 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005649 Cand2.Conversions[ArgIdx])) {
5650 case ImplicitConversionSequence::Better:
5651 // Cand1 has a better conversion sequence.
5652 HasBetterConversion = true;
5653 break;
5654
5655 case ImplicitConversionSequence::Worse:
5656 // Cand1 can't be better than Cand2.
5657 return false;
5658
5659 case ImplicitConversionSequence::Indistinguishable:
5660 // Do nothing.
5661 break;
5662 }
5663 }
5664
Mike Stump11289f42009-09-09 15:08:12 +00005665 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005666 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005667 if (HasBetterConversion)
5668 return true;
5669
Mike Stump11289f42009-09-09 15:08:12 +00005670 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005671 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005672 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005673 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5674 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005675
5676 // -- F1 and F2 are function template specializations, and the function
5677 // template for F1 is more specialized than the template for F2
5678 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005679 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005680 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5681 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005682 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005683 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5684 Cand2.Function->getPrimaryTemplate(),
5685 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005686 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5687 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005688 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005689
Douglas Gregora1f013e2008-11-07 22:36:19 +00005690 // -- the context is an initialization by user-defined conversion
5691 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5692 // from the return type of F1 to the destination type (i.e.,
5693 // the type of the entity being initialized) is a better
5694 // conversion sequence than the standard conversion sequence
5695 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005696 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005697 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005698 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005699 switch (CompareStandardConversionSequences(S,
5700 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005701 Cand2.FinalConversion)) {
5702 case ImplicitConversionSequence::Better:
5703 // Cand1 has a better conversion sequence.
5704 return true;
5705
5706 case ImplicitConversionSequence::Worse:
5707 // Cand1 can't be better than Cand2.
5708 return false;
5709
5710 case ImplicitConversionSequence::Indistinguishable:
5711 // Do nothing
5712 break;
5713 }
5714 }
5715
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005716 return false;
5717}
5718
Mike Stump11289f42009-09-09 15:08:12 +00005719/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005720/// within an overload candidate set.
5721///
5722/// \param CandidateSet the set of candidate functions.
5723///
5724/// \param Loc the location of the function name (or operator symbol) for
5725/// which overload resolution occurs.
5726///
Mike Stump11289f42009-09-09 15:08:12 +00005727/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005728/// function, Best points to the candidate function found.
5729///
5730/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005731OverloadingResult
5732OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005733 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005734 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005735 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005736 Best = end();
5737 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5738 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005739 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5740 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005741 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005742 }
5743
5744 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005745 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005746 return OR_No_Viable_Function;
5747
5748 // Make sure that this function is better than every other viable
5749 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005750 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005751 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005752 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005753 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5754 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005755 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005756 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005757 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005758 }
Mike Stump11289f42009-09-09 15:08:12 +00005759
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005760 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005761 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005762 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005763 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005764 return OR_Deleted;
5765
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005766 // C++ [basic.def.odr]p2:
5767 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005768 // when referred to from a potentially-evaluated expression. [Note: this
5769 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005770 // (clause 13), user-defined conversions (12.3.2), allocation function for
5771 // placement new (5.3.4), as well as non-default initialization (8.5).
5772 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005773 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005774
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005775 return OR_Success;
5776}
5777
John McCall53262c92010-01-12 02:15:36 +00005778namespace {
5779
5780enum OverloadCandidateKind {
5781 oc_function,
5782 oc_method,
5783 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005784 oc_function_template,
5785 oc_method_template,
5786 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005787 oc_implicit_default_constructor,
5788 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005789 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005790};
5791
John McCalle1ac8d12010-01-13 00:25:19 +00005792OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5793 FunctionDecl *Fn,
5794 std::string &Description) {
5795 bool isTemplate = false;
5796
5797 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5798 isTemplate = true;
5799 Description = S.getTemplateArgumentBindingsText(
5800 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5801 }
John McCallfd0b2f82010-01-06 09:43:14 +00005802
5803 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005804 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005805 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005806
John McCall53262c92010-01-12 02:15:36 +00005807 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5808 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005809 }
5810
5811 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5812 // This actually gets spelled 'candidate function' for now, but
5813 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005814 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005815 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005816
Douglas Gregorec3bec02010-09-27 22:37:28 +00005817 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005818 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005819 return oc_implicit_copy_assignment;
5820 }
5821
John McCalle1ac8d12010-01-13 00:25:19 +00005822 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005823}
5824
5825} // end anonymous namespace
5826
5827// Notes the location of an overload candidate.
5828void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005829 std::string FnDesc;
5830 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5831 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5832 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005833}
5834
John McCall0d1da222010-01-12 00:44:57 +00005835/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5836/// "lead" diagnostic; it will be given two arguments, the source and
5837/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005838void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5839 Sema &S,
5840 SourceLocation CaretLoc,
5841 const PartialDiagnostic &PDiag) const {
5842 S.Diag(CaretLoc, PDiag)
5843 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005844 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005845 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5846 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005847 }
John McCall12f97bc2010-01-08 04:41:39 +00005848}
5849
John McCall0d1da222010-01-12 00:44:57 +00005850namespace {
5851
John McCall6a61b522010-01-13 09:16:55 +00005852void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5853 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5854 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005855 assert(Cand->Function && "for now, candidate must be a function");
5856 FunctionDecl *Fn = Cand->Function;
5857
5858 // There's a conversion slot for the object argument if this is a
5859 // non-constructor method. Note that 'I' corresponds the
5860 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005861 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005862 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005863 if (I == 0)
5864 isObjectArgument = true;
5865 else
5866 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005867 }
5868
John McCalle1ac8d12010-01-13 00:25:19 +00005869 std::string FnDesc;
5870 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5871
John McCall6a61b522010-01-13 09:16:55 +00005872 Expr *FromExpr = Conv.Bad.FromExpr;
5873 QualType FromTy = Conv.Bad.getFromType();
5874 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005875
John McCallfb7ad0f2010-02-02 02:42:52 +00005876 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005877 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005878 Expr *E = FromExpr->IgnoreParens();
5879 if (isa<UnaryOperator>(E))
5880 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005881 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005882
5883 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5884 << (unsigned) FnKind << FnDesc
5885 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5886 << ToTy << Name << I+1;
5887 return;
5888 }
5889
John McCall6d174642010-01-23 08:10:49 +00005890 // Do some hand-waving analysis to see if the non-viability is due
5891 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005892 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5893 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5894 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5895 CToTy = RT->getPointeeType();
5896 else {
5897 // TODO: detect and diagnose the full richness of const mismatches.
5898 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5899 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5900 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5901 }
5902
5903 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5904 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5905 // It is dumb that we have to do this here.
5906 while (isa<ArrayType>(CFromTy))
5907 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5908 while (isa<ArrayType>(CToTy))
5909 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5910
5911 Qualifiers FromQs = CFromTy.getQualifiers();
5912 Qualifiers ToQs = CToTy.getQualifiers();
5913
5914 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5916 << (unsigned) FnKind << FnDesc
5917 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5918 << FromTy
5919 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5920 << (unsigned) isObjectArgument << I+1;
5921 return;
5922 }
5923
5924 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5925 assert(CVR && "unexpected qualifiers mismatch");
5926
5927 if (isObjectArgument) {
5928 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5929 << (unsigned) FnKind << FnDesc
5930 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5931 << FromTy << (CVR - 1);
5932 } else {
5933 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5934 << (unsigned) FnKind << FnDesc
5935 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5936 << FromTy << (CVR - 1) << I+1;
5937 }
5938 return;
5939 }
5940
John McCall6d174642010-01-23 08:10:49 +00005941 // Diagnose references or pointers to incomplete types differently,
5942 // since it's far from impossible that the incompleteness triggered
5943 // the failure.
5944 QualType TempFromTy = FromTy.getNonReferenceType();
5945 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5946 TempFromTy = PTy->getPointeeType();
5947 if (TempFromTy->isIncompleteType()) {
5948 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5949 << (unsigned) FnKind << FnDesc
5950 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5951 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5952 return;
5953 }
5954
Douglas Gregor56f2e342010-06-30 23:01:39 +00005955 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005956 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005957 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5958 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5959 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5960 FromPtrTy->getPointeeType()) &&
5961 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5962 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5963 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5964 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005965 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005966 }
5967 } else if (const ObjCObjectPointerType *FromPtrTy
5968 = FromTy->getAs<ObjCObjectPointerType>()) {
5969 if (const ObjCObjectPointerType *ToPtrTy
5970 = ToTy->getAs<ObjCObjectPointerType>())
5971 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5972 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5973 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5974 FromPtrTy->getPointeeType()) &&
5975 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005976 BaseToDerivedConversion = 2;
5977 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5978 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5979 !FromTy->isIncompleteType() &&
5980 !ToRefTy->getPointeeType()->isIncompleteType() &&
5981 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5982 BaseToDerivedConversion = 3;
5983 }
5984
5985 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005986 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005987 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005988 << (unsigned) FnKind << FnDesc
5989 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005990 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005991 << FromTy << ToTy << I+1;
5992 return;
5993 }
5994
John McCall47000992010-01-14 03:28:57 +00005995 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005996 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5997 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005998 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005999 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006000}
6001
6002void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6003 unsigned NumFormalArgs) {
6004 // TODO: treat calls to a missing default constructor as a special case
6005
6006 FunctionDecl *Fn = Cand->Function;
6007 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6008
6009 unsigned MinParams = Fn->getMinRequiredArguments();
6010
6011 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00006012 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00006013 unsigned mode, modeCount;
6014 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006015 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6016 (Cand->FailureKind == ovl_fail_bad_deduction &&
6017 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00006018 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6019 mode = 0; // "at least"
6020 else
6021 mode = 2; // "exactly"
6022 modeCount = MinParams;
6023 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006024 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6025 (Cand->FailureKind == ovl_fail_bad_deduction &&
6026 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006027 if (MinParams != FnTy->getNumArgs())
6028 mode = 1; // "at most"
6029 else
6030 mode = 2; // "exactly"
6031 modeCount = FnTy->getNumArgs();
6032 }
6033
6034 std::string Description;
6035 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6036
6037 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006038 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6039 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006040}
6041
John McCall8b9ed552010-02-01 18:53:26 +00006042/// Diagnose a failed template-argument deduction.
6043void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6044 Expr **Args, unsigned NumArgs) {
6045 FunctionDecl *Fn = Cand->Function; // pattern
6046
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006047 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006048 NamedDecl *ParamD;
6049 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6050 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6051 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006052 switch (Cand->DeductionFailure.Result) {
6053 case Sema::TDK_Success:
6054 llvm_unreachable("TDK_success while diagnosing bad deduction");
6055
6056 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006057 assert(ParamD && "no parameter found for incomplete deduction result");
6058 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6059 << ParamD->getDeclName();
6060 return;
6061 }
6062
John McCall42d7d192010-08-05 09:05:08 +00006063 case Sema::TDK_Underqualified: {
6064 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6065 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6066
6067 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6068
6069 // Param will have been canonicalized, but it should just be a
6070 // qualified version of ParamD, so move the qualifiers to that.
6071 QualifierCollector Qs(S.Context);
6072 Qs.strip(Param);
6073 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6074 assert(S.Context.hasSameType(Param, NonCanonParam));
6075
6076 // Arg has also been canonicalized, but there's nothing we can do
6077 // about that. It also doesn't matter as much, because it won't
6078 // have any template parameters in it (because deduction isn't
6079 // done on dependent types).
6080 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6081
6082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6083 << ParamD->getDeclName() << Arg << NonCanonParam;
6084 return;
6085 }
6086
6087 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006088 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006089 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006090 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006091 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006092 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006093 which = 1;
6094 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006095 which = 2;
6096 }
6097
6098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6099 << which << ParamD->getDeclName()
6100 << *Cand->DeductionFailure.getFirstArg()
6101 << *Cand->DeductionFailure.getSecondArg();
6102 return;
6103 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006104
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006105 case Sema::TDK_InvalidExplicitArguments:
6106 assert(ParamD && "no parameter found for invalid explicit arguments");
6107 if (ParamD->getDeclName())
6108 S.Diag(Fn->getLocation(),
6109 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6110 << ParamD->getDeclName();
6111 else {
6112 int index = 0;
6113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6114 index = TTP->getIndex();
6115 else if (NonTypeTemplateParmDecl *NTTP
6116 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6117 index = NTTP->getIndex();
6118 else
6119 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6120 S.Diag(Fn->getLocation(),
6121 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6122 << (index + 1);
6123 }
6124 return;
6125
Douglas Gregor02eb4832010-05-08 18:13:28 +00006126 case Sema::TDK_TooManyArguments:
6127 case Sema::TDK_TooFewArguments:
6128 DiagnoseArityMismatch(S, Cand, NumArgs);
6129 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006130
6131 case Sema::TDK_InstantiationDepth:
6132 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6133 return;
6134
6135 case Sema::TDK_SubstitutionFailure: {
6136 std::string ArgString;
6137 if (TemplateArgumentList *Args
6138 = Cand->DeductionFailure.getTemplateArgumentList())
6139 ArgString = S.getTemplateArgumentBindingsText(
6140 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6141 *Args);
6142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6143 << ArgString;
6144 return;
6145 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006146
John McCall8b9ed552010-02-01 18:53:26 +00006147 // TODO: diagnose these individually, then kill off
6148 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006149 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006150 case Sema::TDK_FailedOverloadResolution:
6151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6152 return;
6153 }
6154}
6155
6156/// Generates a 'note' diagnostic for an overload candidate. We've
6157/// already generated a primary error at the call site.
6158///
6159/// It really does need to be a single diagnostic with its caret
6160/// pointed at the candidate declaration. Yes, this creates some
6161/// major challenges of technical writing. Yes, this makes pointing
6162/// out problems with specific arguments quite awkward. It's still
6163/// better than generating twenty screens of text for every failed
6164/// overload.
6165///
6166/// It would be great to be able to express per-candidate problems
6167/// more richly for those diagnostic clients that cared, but we'd
6168/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006169void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6170 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006171 FunctionDecl *Fn = Cand->Function;
6172
John McCall12f97bc2010-01-08 04:41:39 +00006173 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006174 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006175 std::string FnDesc;
6176 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006177
6178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006179 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006180 return;
John McCall12f97bc2010-01-08 04:41:39 +00006181 }
6182
John McCalle1ac8d12010-01-13 00:25:19 +00006183 // We don't really have anything else to say about viable candidates.
6184 if (Cand->Viable) {
6185 S.NoteOverloadCandidate(Fn);
6186 return;
6187 }
John McCall0d1da222010-01-12 00:44:57 +00006188
John McCall6a61b522010-01-13 09:16:55 +00006189 switch (Cand->FailureKind) {
6190 case ovl_fail_too_many_arguments:
6191 case ovl_fail_too_few_arguments:
6192 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006193
John McCall6a61b522010-01-13 09:16:55 +00006194 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006195 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6196
John McCallfe796dd2010-01-23 05:17:32 +00006197 case ovl_fail_trivial_conversion:
6198 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006199 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006200 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006201
John McCall65eb8792010-02-25 01:37:24 +00006202 case ovl_fail_bad_conversion: {
6203 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6204 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006205 if (Cand->Conversions[I].isBad())
6206 return DiagnoseBadConversion(S, Cand, I);
6207
6208 // FIXME: this currently happens when we're called from SemaInit
6209 // when user-conversion overload fails. Figure out how to handle
6210 // those conditions and diagnose them well.
6211 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006212 }
John McCall65eb8792010-02-25 01:37:24 +00006213 }
John McCalld3224162010-01-08 00:58:21 +00006214}
6215
6216void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6217 // Desugar the type of the surrogate down to a function type,
6218 // retaining as many typedefs as possible while still showing
6219 // the function type (and, therefore, its parameter types).
6220 QualType FnType = Cand->Surrogate->getConversionType();
6221 bool isLValueReference = false;
6222 bool isRValueReference = false;
6223 bool isPointer = false;
6224 if (const LValueReferenceType *FnTypeRef =
6225 FnType->getAs<LValueReferenceType>()) {
6226 FnType = FnTypeRef->getPointeeType();
6227 isLValueReference = true;
6228 } else if (const RValueReferenceType *FnTypeRef =
6229 FnType->getAs<RValueReferenceType>()) {
6230 FnType = FnTypeRef->getPointeeType();
6231 isRValueReference = true;
6232 }
6233 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6234 FnType = FnTypePtr->getPointeeType();
6235 isPointer = true;
6236 }
6237 // Desugar down to a function type.
6238 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6239 // Reconstruct the pointer/reference as appropriate.
6240 if (isPointer) FnType = S.Context.getPointerType(FnType);
6241 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6242 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6243
6244 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6245 << FnType;
6246}
6247
6248void NoteBuiltinOperatorCandidate(Sema &S,
6249 const char *Opc,
6250 SourceLocation OpLoc,
6251 OverloadCandidate *Cand) {
6252 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6253 std::string TypeStr("operator");
6254 TypeStr += Opc;
6255 TypeStr += "(";
6256 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6257 if (Cand->Conversions.size() == 1) {
6258 TypeStr += ")";
6259 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6260 } else {
6261 TypeStr += ", ";
6262 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6263 TypeStr += ")";
6264 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6265 }
6266}
6267
6268void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6269 OverloadCandidate *Cand) {
6270 unsigned NoOperands = Cand->Conversions.size();
6271 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6272 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006273 if (ICS.isBad()) break; // all meaningless after first invalid
6274 if (!ICS.isAmbiguous()) continue;
6275
John McCall5c32be02010-08-24 20:38:10 +00006276 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006277 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006278 }
6279}
6280
John McCall3712d9e2010-01-15 23:32:50 +00006281SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6282 if (Cand->Function)
6283 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006284 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006285 return Cand->Surrogate->getLocation();
6286 return SourceLocation();
6287}
6288
John McCallad2587a2010-01-12 00:48:53 +00006289struct CompareOverloadCandidatesForDisplay {
6290 Sema &S;
6291 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006292
6293 bool operator()(const OverloadCandidate *L,
6294 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006295 // Fast-path this check.
6296 if (L == R) return false;
6297
John McCall12f97bc2010-01-08 04:41:39 +00006298 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006299 if (L->Viable) {
6300 if (!R->Viable) return true;
6301
6302 // TODO: introduce a tri-valued comparison for overload
6303 // candidates. Would be more worthwhile if we had a sort
6304 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006305 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6306 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006307 } else if (R->Viable)
6308 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006309
John McCall3712d9e2010-01-15 23:32:50 +00006310 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006311
John McCall3712d9e2010-01-15 23:32:50 +00006312 // Criteria by which we can sort non-viable candidates:
6313 if (!L->Viable) {
6314 // 1. Arity mismatches come after other candidates.
6315 if (L->FailureKind == ovl_fail_too_many_arguments ||
6316 L->FailureKind == ovl_fail_too_few_arguments)
6317 return false;
6318 if (R->FailureKind == ovl_fail_too_many_arguments ||
6319 R->FailureKind == ovl_fail_too_few_arguments)
6320 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006321
John McCallfe796dd2010-01-23 05:17:32 +00006322 // 2. Bad conversions come first and are ordered by the number
6323 // of bad conversions and quality of good conversions.
6324 if (L->FailureKind == ovl_fail_bad_conversion) {
6325 if (R->FailureKind != ovl_fail_bad_conversion)
6326 return true;
6327
6328 // If there's any ordering between the defined conversions...
6329 // FIXME: this might not be transitive.
6330 assert(L->Conversions.size() == R->Conversions.size());
6331
6332 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006333 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6334 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006335 switch (CompareImplicitConversionSequences(S,
6336 L->Conversions[I],
6337 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006338 case ImplicitConversionSequence::Better:
6339 leftBetter++;
6340 break;
6341
6342 case ImplicitConversionSequence::Worse:
6343 leftBetter--;
6344 break;
6345
6346 case ImplicitConversionSequence::Indistinguishable:
6347 break;
6348 }
6349 }
6350 if (leftBetter > 0) return true;
6351 if (leftBetter < 0) return false;
6352
6353 } else if (R->FailureKind == ovl_fail_bad_conversion)
6354 return false;
6355
John McCall3712d9e2010-01-15 23:32:50 +00006356 // TODO: others?
6357 }
6358
6359 // Sort everything else by location.
6360 SourceLocation LLoc = GetLocationForCandidate(L);
6361 SourceLocation RLoc = GetLocationForCandidate(R);
6362
6363 // Put candidates without locations (e.g. builtins) at the end.
6364 if (LLoc.isInvalid()) return false;
6365 if (RLoc.isInvalid()) return true;
6366
6367 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006368 }
6369};
6370
John McCallfe796dd2010-01-23 05:17:32 +00006371/// CompleteNonViableCandidate - Normally, overload resolution only
6372/// computes up to the first
6373void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6374 Expr **Args, unsigned NumArgs) {
6375 assert(!Cand->Viable);
6376
6377 // Don't do anything on failures other than bad conversion.
6378 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6379
6380 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006381 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006382 unsigned ConvCount = Cand->Conversions.size();
6383 while (true) {
6384 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6385 ConvIdx++;
6386 if (Cand->Conversions[ConvIdx - 1].isBad())
6387 break;
6388 }
6389
6390 if (ConvIdx == ConvCount)
6391 return;
6392
John McCall65eb8792010-02-25 01:37:24 +00006393 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6394 "remaining conversion is initialized?");
6395
Douglas Gregoradc7a702010-04-16 17:45:54 +00006396 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006397 // operation somehow.
6398 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006399
6400 const FunctionProtoType* Proto;
6401 unsigned ArgIdx = ConvIdx;
6402
6403 if (Cand->IsSurrogate) {
6404 QualType ConvType
6405 = Cand->Surrogate->getConversionType().getNonReferenceType();
6406 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6407 ConvType = ConvPtrType->getPointeeType();
6408 Proto = ConvType->getAs<FunctionProtoType>();
6409 ArgIdx--;
6410 } else if (Cand->Function) {
6411 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6412 if (isa<CXXMethodDecl>(Cand->Function) &&
6413 !isa<CXXConstructorDecl>(Cand->Function))
6414 ArgIdx--;
6415 } else {
6416 // Builtin binary operator with a bad first conversion.
6417 assert(ConvCount <= 3);
6418 for (; ConvIdx != ConvCount; ++ConvIdx)
6419 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006420 = TryCopyInitialization(S, Args[ConvIdx],
6421 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6422 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006423 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006424 return;
6425 }
6426
6427 // Fill in the rest of the conversions.
6428 unsigned NumArgsInProto = Proto->getNumArgs();
6429 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6430 if (ArgIdx < NumArgsInProto)
6431 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006432 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6433 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006434 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006435 else
6436 Cand->Conversions[ConvIdx].setEllipsis();
6437 }
6438}
6439
John McCalld3224162010-01-08 00:58:21 +00006440} // end anonymous namespace
6441
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006442/// PrintOverloadCandidates - When overload resolution fails, prints
6443/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006444/// set.
John McCall5c32be02010-08-24 20:38:10 +00006445void OverloadCandidateSet::NoteCandidates(Sema &S,
6446 OverloadCandidateDisplayKind OCD,
6447 Expr **Args, unsigned NumArgs,
6448 const char *Opc,
6449 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006450 // Sort the candidates by viability and position. Sorting directly would
6451 // be prohibitive, so we make a set of pointers and sort those.
6452 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006453 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6454 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006455 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006456 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006457 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006458 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006459 if (Cand->Function || Cand->IsSurrogate)
6460 Cands.push_back(Cand);
6461 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6462 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006463 }
6464 }
6465
John McCallad2587a2010-01-12 00:48:53 +00006466 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006467 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006468
John McCall0d1da222010-01-12 00:44:57 +00006469 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006470
John McCall12f97bc2010-01-08 04:41:39 +00006471 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006472 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006473 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006474 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6475 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006476
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006477 // Set an arbitrary limit on the number of candidate functions we'll spam
6478 // the user with. FIXME: This limit should depend on details of the
6479 // candidate list.
6480 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6481 break;
6482 }
6483 ++CandsShown;
6484
John McCalld3224162010-01-08 00:58:21 +00006485 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006486 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006487 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006488 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006489 else {
6490 assert(Cand->Viable &&
6491 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006492 // Generally we only see ambiguities including viable builtin
6493 // operators if overload resolution got screwed up by an
6494 // ambiguous user-defined conversion.
6495 //
6496 // FIXME: It's quite possible for different conversions to see
6497 // different ambiguities, though.
6498 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006499 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006500 ReportedAmbiguousConversions = true;
6501 }
John McCalld3224162010-01-08 00:58:21 +00006502
John McCall0d1da222010-01-12 00:44:57 +00006503 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006504 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006505 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006506 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006507
6508 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006509 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006510}
6511
John McCalla0296f72010-03-19 07:35:19 +00006512static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006513 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006514 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006515
John McCalla0296f72010-03-19 07:35:19 +00006516 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006517}
6518
Douglas Gregorcd695e52008-11-10 20:40:00 +00006519/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6520/// an overloaded function (C++ [over.over]), where @p From is an
6521/// expression with overloaded function type and @p ToType is the type
6522/// we're trying to resolve to. For example:
6523///
6524/// @code
6525/// int f(double);
6526/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006527///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006528/// int (*pfd)(double) = f; // selects f(double)
6529/// @endcode
6530///
6531/// This routine returns the resulting FunctionDecl if it could be
6532/// resolved, and NULL otherwise. When @p Complain is true, this
6533/// routine will emit diagnostics if there is an error.
6534FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006535Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006536 bool Complain,
6537 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006538 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006539 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006540 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006541 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006542 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006543 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006544 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006545 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006546 FunctionType = MemTypePtr->getPointeeType();
6547 IsMember = true;
6548 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006549
Douglas Gregorcd695e52008-11-10 20:40:00 +00006550 // C++ [over.over]p1:
6551 // [...] [Note: any redundant set of parentheses surrounding the
6552 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006553 // C++ [over.over]p1:
6554 // [...] The overloaded function name can be preceded by the &
6555 // operator.
John McCall7d460512010-08-24 23:26:21 +00006556 // However, remember whether the expression has member-pointer form:
6557 // C++ [expr.unary.op]p4:
6558 // A pointer to member is only formed when an explicit & is used
6559 // and its operand is a qualified-id not enclosed in
6560 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006561 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6562 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006563
Douglas Gregor064fdb22010-04-14 23:11:21 +00006564 // We expect a pointer or reference to function, or a function pointer.
6565 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6566 if (!FunctionType->isFunctionType()) {
6567 if (Complain)
6568 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6569 << OvlExpr->getName() << ToType;
6570
6571 return 0;
6572 }
6573
John McCall24d18942010-08-24 22:52:39 +00006574 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006575 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006576 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006577 if (!Complain) return 0;
6578
6579 // TODO: Should we condition this on whether any functions might
6580 // have matched, or is it more appropriate to do that in callers?
6581 // TODO: a fixit wouldn't hurt.
6582 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6583 << ToType << OvlExpr->getSourceRange();
6584 return 0;
6585 }
6586
6587 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6588 if (OvlExpr->hasExplicitTemplateArgs()) {
6589 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6590 ExplicitTemplateArgs = &ETABuffer;
6591 }
6592
Douglas Gregor064fdb22010-04-14 23:11:21 +00006593 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006594
Douglas Gregorcd695e52008-11-10 20:40:00 +00006595 // Look through all of the overloaded functions, searching for one
6596 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006597 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006598 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006599
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006600 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006601 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6602 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006603 // Look through any using declarations to find the underlying function.
6604 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6605
Douglas Gregorcd695e52008-11-10 20:40:00 +00006606 // C++ [over.over]p3:
6607 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006608 // targets of type "pointer-to-function" or "reference-to-function."
6609 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006610 // type "pointer-to-member-function."
6611 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006612
Mike Stump11289f42009-09-09 15:08:12 +00006613 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006614 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006615 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006616 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006617 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006618 // static when converting to member pointer.
6619 if (Method->isStatic() == IsMember)
6620 continue;
6621 } else if (IsMember)
6622 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006623
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006624 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006625 // If the name is a function template, template argument deduction is
6626 // done (14.8.2.2), and if the argument deduction succeeds, the
6627 // resulting template argument list is used to generate a single
6628 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006629 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006630 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006631 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006632 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006633 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006634 FunctionType, Specialization, Info)) {
6635 // FIXME: make a note of the failed deduction for diagnostics.
6636 (void)Result;
6637 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006638 // Template argument deduction ensures that we have an exact match.
6639 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006640 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006641 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006642 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006643 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006644 }
John McCalld14a8642009-11-21 08:51:07 +00006645
6646 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006647 }
Mike Stump11289f42009-09-09 15:08:12 +00006648
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006649 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006650 // Skip non-static functions when converting to pointer, and static
6651 // when converting to member pointer.
6652 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006653 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006654
6655 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006656 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006657 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006658 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006659 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006660
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006661 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006662 QualType ResultTy;
6663 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6664 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6665 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006666 Matches.push_back(std::make_pair(I.getPair(),
6667 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006668 FoundNonTemplateFunction = true;
6669 }
Mike Stump11289f42009-09-09 15:08:12 +00006670 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006671 }
6672
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006673 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006674 if (Matches.empty()) {
6675 if (Complain) {
6676 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6677 << OvlExpr->getName() << FunctionType;
6678 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6679 E = OvlExpr->decls_end();
6680 I != E; ++I)
6681 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6682 NoteOverloadCandidate(F);
6683 }
6684
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006685 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006686 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006687 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006688 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006689 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006690 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006691 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006692 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006693 return Result;
6694 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006695
6696 // C++ [over.over]p4:
6697 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006698 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006699 // [...] and any given function template specialization F1 is
6700 // eliminated if the set contains a second function template
6701 // specialization whose function template is more specialized
6702 // than the function template of F1 according to the partial
6703 // ordering rules of 14.5.5.2.
6704
6705 // The algorithm specified above is quadratic. We instead use a
6706 // two-pass algorithm (similar to the one used to identify the
6707 // best viable function in an overload set) that identifies the
6708 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006709
6710 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6711 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6712 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006713
6714 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006715 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006716 TPOC_Other, From->getLocStart(),
6717 PDiag(),
6718 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006719 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006720 PDiag(diag::note_ovl_candidate)
6721 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006722 if (Result == MatchesCopy.end())
6723 return 0;
6724
John McCall58cc69d2010-01-27 01:50:18 +00006725 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006726 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006727 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006728 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006729 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006730 }
Mike Stump11289f42009-09-09 15:08:12 +00006731
Douglas Gregorfae1d712009-09-26 03:56:17 +00006732 // [...] any function template specializations in the set are
6733 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006734 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006735 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006736 ++I;
6737 else {
John McCalla0296f72010-03-19 07:35:19 +00006738 Matches[I] = Matches[--N];
6739 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006740 }
6741 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006742
Mike Stump11289f42009-09-09 15:08:12 +00006743 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006744 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006745 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006746 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006747 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006748 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006749 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6750 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006751 }
Mike Stump11289f42009-09-09 15:08:12 +00006752
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006753 // FIXME: We should probably return the same thing that BestViableFunction
6754 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006755 if (Complain) {
6756 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6757 << Matches[0].second->getDeclName();
6758 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6759 NoteOverloadCandidate(Matches[I].second);
6760 }
6761
Douglas Gregorcd695e52008-11-10 20:40:00 +00006762 return 0;
6763}
6764
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006765/// \brief Given an expression that refers to an overloaded function, try to
6766/// resolve that overloaded function expression down to a single function.
6767///
6768/// This routine can only resolve template-ids that refer to a single function
6769/// template, where that template-id refers to a single template whose template
6770/// arguments are either provided by the template-id or have defaults,
6771/// as described in C++0x [temp.arg.explicit]p3.
6772FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6773 // C++ [over.over]p1:
6774 // [...] [Note: any redundant set of parentheses surrounding the
6775 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006776 // C++ [over.over]p1:
6777 // [...] The overloaded function name can be preceded by the &
6778 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006779
6780 if (From->getType() != Context.OverloadTy)
6781 return 0;
6782
John McCall8d08b9b2010-08-27 09:08:28 +00006783 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006784
6785 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006786 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006787 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006788
6789 TemplateArgumentListInfo ExplicitTemplateArgs;
6790 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006791
6792 // Look through all of the overloaded functions, searching for one
6793 // whose type matches exactly.
6794 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006795 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6796 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006797 // C++0x [temp.arg.explicit]p3:
6798 // [...] In contexts where deduction is done and fails, or in contexts
6799 // where deduction is not done, if a template argument list is
6800 // specified and it, along with any default template arguments,
6801 // identifies a single function template specialization, then the
6802 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006803 FunctionTemplateDecl *FunctionTemplate
6804 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006805
6806 // C++ [over.over]p2:
6807 // If the name is a function template, template argument deduction is
6808 // done (14.8.2.2), and if the argument deduction succeeds, the
6809 // resulting template argument list is used to generate a single
6810 // function template specialization, which is added to the set of
6811 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006812 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006813 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006814 if (TemplateDeductionResult Result
6815 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6816 Specialization, Info)) {
6817 // FIXME: make a note of the failed deduction for diagnostics.
6818 (void)Result;
6819 continue;
6820 }
6821
6822 // Multiple matches; we can't resolve to a single declaration.
6823 if (Matched)
6824 return 0;
6825
6826 Matched = Specialization;
6827 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006828
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006829 return Matched;
6830}
6831
Douglas Gregorcabea402009-09-22 15:41:20 +00006832/// \brief Add a single candidate to the overload set.
6833static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006834 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006835 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006836 Expr **Args, unsigned NumArgs,
6837 OverloadCandidateSet &CandidateSet,
6838 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006839 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006840 if (isa<UsingShadowDecl>(Callee))
6841 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6842
Douglas Gregorcabea402009-09-22 15:41:20 +00006843 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006844 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006845 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006846 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006847 return;
John McCalld14a8642009-11-21 08:51:07 +00006848 }
6849
6850 if (FunctionTemplateDecl *FuncTemplate
6851 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006852 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6853 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006854 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006855 return;
6856 }
6857
6858 assert(false && "unhandled case in overloaded call candidate");
6859
6860 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006861}
6862
6863/// \brief Add the overload candidates named by callee and/or found by argument
6864/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006865void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006866 Expr **Args, unsigned NumArgs,
6867 OverloadCandidateSet &CandidateSet,
6868 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006869
6870#ifndef NDEBUG
6871 // Verify that ArgumentDependentLookup is consistent with the rules
6872 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006873 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006874 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6875 // and let Y be the lookup set produced by argument dependent
6876 // lookup (defined as follows). If X contains
6877 //
6878 // -- a declaration of a class member, or
6879 //
6880 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006881 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006882 //
6883 // -- a declaration that is neither a function or a function
6884 // template
6885 //
6886 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006887
John McCall57500772009-12-16 12:17:52 +00006888 if (ULE->requiresADL()) {
6889 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6890 E = ULE->decls_end(); I != E; ++I) {
6891 assert(!(*I)->getDeclContext()->isRecord());
6892 assert(isa<UsingShadowDecl>(*I) ||
6893 !(*I)->getDeclContext()->isFunctionOrMethod());
6894 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006895 }
6896 }
6897#endif
6898
John McCall57500772009-12-16 12:17:52 +00006899 // It would be nice to avoid this copy.
6900 TemplateArgumentListInfo TABuffer;
6901 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6902 if (ULE->hasExplicitTemplateArgs()) {
6903 ULE->copyTemplateArgumentsInto(TABuffer);
6904 ExplicitTemplateArgs = &TABuffer;
6905 }
6906
6907 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6908 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006909 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006910 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006911 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006912
John McCall57500772009-12-16 12:17:52 +00006913 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006914 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6915 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006916 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006917 CandidateSet,
6918 PartialOverloading);
6919}
John McCalld681c392009-12-16 08:11:27 +00006920
6921/// Attempts to recover from a call where no functions were found.
6922///
6923/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006924static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006925BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006926 UnresolvedLookupExpr *ULE,
6927 SourceLocation LParenLoc,
6928 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006929 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006930
6931 CXXScopeSpec SS;
6932 if (ULE->getQualifier()) {
6933 SS.setScopeRep(ULE->getQualifier());
6934 SS.setRange(ULE->getQualifierRange());
6935 }
6936
John McCall57500772009-12-16 12:17:52 +00006937 TemplateArgumentListInfo TABuffer;
6938 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6939 if (ULE->hasExplicitTemplateArgs()) {
6940 ULE->copyTemplateArgumentsInto(TABuffer);
6941 ExplicitTemplateArgs = &TABuffer;
6942 }
6943
John McCalld681c392009-12-16 08:11:27 +00006944 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6945 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006946 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006947 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006948
John McCall57500772009-12-16 12:17:52 +00006949 assert(!R.empty() && "lookup results empty despite recovery");
6950
6951 // Build an implicit member call if appropriate. Just drop the
6952 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006953 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006954 if ((*R.begin())->isCXXClassMember())
6955 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6956 else if (ExplicitTemplateArgs)
6957 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6958 else
6959 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6960
6961 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006962 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006963
6964 // This shouldn't cause an infinite loop because we're giving it
6965 // an expression with non-empty lookup results, which should never
6966 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006967 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006968 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006969}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006970
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006971/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006972/// (which eventually refers to the declaration Func) and the call
6973/// arguments Args/NumArgs, attempt to resolve the function call down
6974/// to a specific function. If overload resolution succeeds, returns
6975/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006976/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006977/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006978ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006979Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006980 SourceLocation LParenLoc,
6981 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006982 SourceLocation RParenLoc) {
6983#ifndef NDEBUG
6984 if (ULE->requiresADL()) {
6985 // To do ADL, we must have found an unqualified name.
6986 assert(!ULE->getQualifier() && "qualified name with ADL");
6987
6988 // We don't perform ADL for implicit declarations of builtins.
6989 // Verify that this was correctly set up.
6990 FunctionDecl *F;
6991 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6992 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6993 F->getBuiltinID() && F->isImplicit())
6994 assert(0 && "performing ADL for builtin");
6995
6996 // We don't perform ADL in C.
6997 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6998 }
6999#endif
7000
John McCallbc077cf2010-02-08 23:07:23 +00007001 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007002
John McCall57500772009-12-16 12:17:52 +00007003 // Add the functions denoted by the callee to the set of candidate
7004 // functions, including those from argument-dependent lookup.
7005 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007006
7007 // If we found nothing, try to recover.
7008 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7009 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007010 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007011 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007012 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007013
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007014 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007015 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007016 case OR_Success: {
7017 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007018 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00007019 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007020 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00007021 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
7022 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007023
7024 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007025 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007026 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007027 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007028 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007029 break;
7030
7031 case OR_Ambiguous:
7032 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007033 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007034 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007035 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007036
7037 case OR_Deleted:
7038 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7039 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007040 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007041 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007042 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007043 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007044 }
7045
Douglas Gregorb412e172010-07-25 18:17:45 +00007046 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007047 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007048}
7049
John McCall4c4c1df2010-01-26 03:27:55 +00007050static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007051 return Functions.size() > 1 ||
7052 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7053}
7054
Douglas Gregor084d8552009-03-13 23:49:33 +00007055/// \brief Create a unary operation that may resolve to an overloaded
7056/// operator.
7057///
7058/// \param OpLoc The location of the operator itself (e.g., '*').
7059///
7060/// \param OpcIn The UnaryOperator::Opcode that describes this
7061/// operator.
7062///
7063/// \param Functions The set of non-member functions that will be
7064/// considered by overload resolution. The caller needs to build this
7065/// set based on the context using, e.g.,
7066/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7067/// set should not contain any member functions; those will be added
7068/// by CreateOverloadedUnaryOp().
7069///
7070/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007071ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007072Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7073 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007074 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007075 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007076
7077 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7078 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7079 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007080 // TODO: provide better source location info.
7081 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007082
7083 Expr *Args[2] = { Input, 0 };
7084 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007085
Douglas Gregor084d8552009-03-13 23:49:33 +00007086 // For post-increment and post-decrement, add the implicit '0' as
7087 // the second argument, so that we know this is a post-increment or
7088 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007089 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007090 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007091 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7092 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007093 NumArgs = 2;
7094 }
7095
7096 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007097 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007098 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007099 Opc,
7100 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007101 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007102 OpLoc));
7103
John McCall58cc69d2010-01-27 01:50:18 +00007104 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007105 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007106 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007107 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007108 /*ADL*/ true, IsOverloaded(Fns),
7109 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007110 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7111 &Args[0], NumArgs,
7112 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007113 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007114 OpLoc));
7115 }
7116
7117 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007118 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007119
7120 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007121 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007122
7123 // Add operator candidates that are member functions.
7124 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7125
John McCall4c4c1df2010-01-26 03:27:55 +00007126 // Add candidates from ADL.
7127 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007128 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007129 /*ExplicitTemplateArgs*/ 0,
7130 CandidateSet);
7131
Douglas Gregor084d8552009-03-13 23:49:33 +00007132 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007133 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007134
7135 // Perform overload resolution.
7136 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007137 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007138 case OR_Success: {
7139 // We found a built-in operator or an overloaded operator.
7140 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007141
Douglas Gregor084d8552009-03-13 23:49:33 +00007142 if (FnDecl) {
7143 // We matched an overloaded operator. Build a call to that
7144 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007145
Douglas Gregor084d8552009-03-13 23:49:33 +00007146 // Convert the arguments.
7147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007148 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007149
John McCall16df1e52010-03-30 21:47:33 +00007150 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7151 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007152 return ExprError();
7153 } else {
7154 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007155 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007156 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007157 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007158 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007159 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007160 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007161 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007162 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007163 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007164 }
7165
John McCall4fa0d5f2010-05-06 18:15:07 +00007166 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7167
John McCall7decc9e2010-11-18 06:31:45 +00007168 // Determine the result type.
7169 QualType ResultTy = FnDecl->getResultType();
7170 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7171 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007172
Douglas Gregor084d8552009-03-13 23:49:33 +00007173 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007174 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007175
Eli Friedman030eee42009-11-18 03:58:17 +00007176 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007177 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007178 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007179 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007180
John McCallb268a282010-08-23 23:25:46 +00007181 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007182 FnDecl))
7183 return ExprError();
7184
John McCallb268a282010-08-23 23:25:46 +00007185 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007186 } else {
7187 // We matched a built-in operator. Convert the arguments, then
7188 // break out so that we will build the appropriate built-in
7189 // operator node.
7190 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007191 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007192 return ExprError();
7193
7194 break;
7195 }
7196 }
7197
7198 case OR_No_Viable_Function:
7199 // No viable function; fall through to handling this as a
7200 // built-in operator, which will produce an error message for us.
7201 break;
7202
7203 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007204 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007205 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007206 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007207 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007208 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7209 Args, NumArgs,
7210 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007211 return ExprError();
7212
7213 case OR_Deleted:
7214 Diag(OpLoc, diag::err_ovl_deleted_oper)
7215 << Best->Function->isDeleted()
7216 << UnaryOperator::getOpcodeStr(Opc)
7217 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007219 return ExprError();
7220 }
7221
7222 // Either we found no viable overloaded operator or we matched a
7223 // built-in operator. In either case, fall through to trying to
7224 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007225 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007226}
7227
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007228/// \brief Create a binary operation that may resolve to an overloaded
7229/// operator.
7230///
7231/// \param OpLoc The location of the operator itself (e.g., '+').
7232///
7233/// \param OpcIn The BinaryOperator::Opcode that describes this
7234/// operator.
7235///
7236/// \param Functions The set of non-member functions that will be
7237/// considered by overload resolution. The caller needs to build this
7238/// set based on the context using, e.g.,
7239/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7240/// set should not contain any member functions; those will be added
7241/// by CreateOverloadedBinOp().
7242///
7243/// \param LHS Left-hand argument.
7244/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007245ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007246Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007247 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007248 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007249 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007250 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007251 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007252
7253 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7254 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7255 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7256
7257 // If either side is type-dependent, create an appropriate dependent
7258 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007259 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007260 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007261 // If there are no functions to store, just build a dependent
7262 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007263 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007264 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007265 Context.DependentTy,
7266 VK_RValue, OK_Ordinary,
7267 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007268
7269 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7270 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007271 VK_LValue,
7272 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007273 Context.DependentTy,
7274 Context.DependentTy,
7275 OpLoc));
7276 }
John McCall4c4c1df2010-01-26 03:27:55 +00007277
7278 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007279 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007280 // TODO: provide better source location info in DNLoc component.
7281 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007282 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007283 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007284 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007285 /*ADL*/ true, IsOverloaded(Fns),
7286 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007287 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007288 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007289 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007290 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007291 OpLoc));
7292 }
7293
7294 // If this is the .* operator, which is not overloadable, just
7295 // create a built-in binary operator.
John McCalle3027922010-08-25 11:45:40 +00007296 if (Opc == BO_PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00007297 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007298
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007299 // If this is the assignment operator, we only perform overload resolution
7300 // if the left-hand side is a class or enumeration type. This is actually
7301 // a hack. The standard requires that we do overload resolution between the
7302 // various built-in candidates, but as DR507 points out, this can lead to
7303 // problems. So we do it this way, which pretty much follows what GCC does.
7304 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007305 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007306 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007307
Douglas Gregor084d8552009-03-13 23:49:33 +00007308 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007309 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007310
7311 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007312 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007313
7314 // Add operator candidates that are member functions.
7315 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7316
John McCall4c4c1df2010-01-26 03:27:55 +00007317 // Add candidates from ADL.
7318 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7319 Args, 2,
7320 /*ExplicitTemplateArgs*/ 0,
7321 CandidateSet);
7322
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007323 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007324 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007325
7326 // Perform overload resolution.
7327 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007328 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007329 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007330 // We found a built-in operator or an overloaded operator.
7331 FunctionDecl *FnDecl = Best->Function;
7332
7333 if (FnDecl) {
7334 // We matched an overloaded operator. Build a call to that
7335 // operator.
7336
7337 // Convert the arguments.
7338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007339 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007340 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007341
John McCalldadc5752010-08-24 06:29:42 +00007342 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007343 = PerformCopyInitialization(
7344 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007345 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007346 FnDecl->getParamDecl(0)),
7347 SourceLocation(),
7348 Owned(Args[1]));
7349 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007350 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007351
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007352 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007353 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007354 return ExprError();
7355
7356 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007357 } else {
7358 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007359 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007360 = PerformCopyInitialization(
7361 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007362 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007363 FnDecl->getParamDecl(0)),
7364 SourceLocation(),
7365 Owned(Args[0]));
7366 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007367 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007368
John McCalldadc5752010-08-24 06:29:42 +00007369 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007370 = PerformCopyInitialization(
7371 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007372 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007373 FnDecl->getParamDecl(1)),
7374 SourceLocation(),
7375 Owned(Args[1]));
7376 if (Arg1.isInvalid())
7377 return ExprError();
7378 Args[0] = LHS = Arg0.takeAs<Expr>();
7379 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007380 }
7381
John McCall4fa0d5f2010-05-06 18:15:07 +00007382 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7383
John McCall7decc9e2010-11-18 06:31:45 +00007384 // Determine the result type.
7385 QualType ResultTy = FnDecl->getResultType();
7386 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7387 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007388
7389 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007390 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007391
John McCallb268a282010-08-23 23:25:46 +00007392 CXXOperatorCallExpr *TheCall =
7393 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007394 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007395
John McCallb268a282010-08-23 23:25:46 +00007396 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007397 FnDecl))
7398 return ExprError();
7399
John McCallb268a282010-08-23 23:25:46 +00007400 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007401 } else {
7402 // We matched a built-in operator. Convert the arguments, then
7403 // break out so that we will build the appropriate built-in
7404 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007405 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007406 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007407 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007408 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007409 return ExprError();
7410
7411 break;
7412 }
7413 }
7414
Douglas Gregor66950a32009-09-30 21:46:01 +00007415 case OR_No_Viable_Function: {
7416 // C++ [over.match.oper]p9:
7417 // If the operator is the operator , [...] and there are no
7418 // viable functions, then the operator is assumed to be the
7419 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007420 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007421 break;
7422
Sebastian Redl027de2a2009-05-21 11:50:50 +00007423 // For class as left operand for assignment or compound assigment operator
7424 // do not fall through to handling in built-in, but report that no overloaded
7425 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007426 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007427 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007428 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007429 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7430 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007431 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007432 } else {
7433 // No viable function; try to create a built-in operation, which will
7434 // produce an error. Then, show the non-viable candidates.
7435 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007436 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007437 assert(Result.isInvalid() &&
7438 "C++ binary operator overloading is missing candidates!");
7439 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007440 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7441 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007442 return move(Result);
7443 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007444
7445 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007446 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007447 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007448 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007449 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007450 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7451 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007452 return ExprError();
7453
7454 case OR_Deleted:
7455 Diag(OpLoc, diag::err_ovl_deleted_oper)
7456 << Best->Function->isDeleted()
7457 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007458 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007459 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007460 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007461 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007462
Douglas Gregor66950a32009-09-30 21:46:01 +00007463 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007464 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007465}
7466
John McCalldadc5752010-08-24 06:29:42 +00007467ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007468Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7469 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007470 Expr *Base, Expr *Idx) {
7471 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007472 DeclarationName OpName =
7473 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7474
7475 // If either side is type-dependent, create an appropriate dependent
7476 // expression.
7477 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7478
John McCall58cc69d2010-01-27 01:50:18 +00007479 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007480 // CHECKME: no 'operator' keyword?
7481 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7482 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007483 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007484 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007485 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007486 /*ADL*/ true, /*Overloaded*/ false,
7487 UnresolvedSetIterator(),
7488 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007489 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007490
Sebastian Redladba46e2009-10-29 20:17:01 +00007491 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7492 Args, 2,
7493 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007494 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007495 RLoc));
7496 }
7497
7498 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007499 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007500
7501 // Subscript can only be overloaded as a member function.
7502
7503 // Add operator candidates that are member functions.
7504 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7505
7506 // Add builtin operator candidates.
7507 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7508
7509 // Perform overload resolution.
7510 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007511 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007512 case OR_Success: {
7513 // We found a built-in operator or an overloaded operator.
7514 FunctionDecl *FnDecl = Best->Function;
7515
7516 if (FnDecl) {
7517 // We matched an overloaded operator. Build a call to that
7518 // operator.
7519
John McCalla0296f72010-03-19 07:35:19 +00007520 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007521 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007522
Sebastian Redladba46e2009-10-29 20:17:01 +00007523 // Convert the arguments.
7524 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007525 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007526 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007527 return ExprError();
7528
Anders Carlssona68e51e2010-01-29 18:37:50 +00007529 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007530 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007531 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007532 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007533 FnDecl->getParamDecl(0)),
7534 SourceLocation(),
7535 Owned(Args[1]));
7536 if (InputInit.isInvalid())
7537 return ExprError();
7538
7539 Args[1] = InputInit.takeAs<Expr>();
7540
Sebastian Redladba46e2009-10-29 20:17:01 +00007541 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007542 QualType ResultTy = FnDecl->getResultType();
7543 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7544 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007545
7546 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007547 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007548
John McCallb268a282010-08-23 23:25:46 +00007549 CXXOperatorCallExpr *TheCall =
7550 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7551 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007552 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007553
John McCallb268a282010-08-23 23:25:46 +00007554 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007555 FnDecl))
7556 return ExprError();
7557
John McCallb268a282010-08-23 23:25:46 +00007558 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007559 } else {
7560 // We matched a built-in operator. Convert the arguments, then
7561 // break out so that we will build the appropriate built-in
7562 // operator node.
7563 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007564 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007565 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007566 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007567 return ExprError();
7568
7569 break;
7570 }
7571 }
7572
7573 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007574 if (CandidateSet.empty())
7575 Diag(LLoc, diag::err_ovl_no_oper)
7576 << Args[0]->getType() << /*subscript*/ 0
7577 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7578 else
7579 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7580 << Args[0]->getType()
7581 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007582 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7583 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007584 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007585 }
7586
7587 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007588 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7589 << "[]"
7590 << Args[0]->getType() << Args[1]->getType()
7591 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007592 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7593 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007594 return ExprError();
7595
7596 case OR_Deleted:
7597 Diag(LLoc, diag::err_ovl_deleted_oper)
7598 << Best->Function->isDeleted() << "[]"
7599 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007600 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7601 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007602 return ExprError();
7603 }
7604
7605 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007606 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007607}
7608
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007609/// BuildCallToMemberFunction - Build a call to a member
7610/// function. MemExpr is the expression that refers to the member
7611/// function (and includes the object parameter), Args/NumArgs are the
7612/// arguments to the function call (not including the object
7613/// parameter). The caller needs to validate that the member
7614/// expression refers to a member function or an overloaded member
7615/// function.
John McCalldadc5752010-08-24 06:29:42 +00007616ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007617Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7618 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007619 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007620 // Dig out the member expression. This holds both the object
7621 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007622 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7623
John McCall10eae182009-11-30 22:42:35 +00007624 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007625 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007626 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007627 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007628 if (isa<MemberExpr>(NakedMemExpr)) {
7629 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007630 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007631 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007632 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007633 } else {
7634 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007635 Qualifier = UnresExpr->getQualifier();
7636
John McCall6e9f8f62009-12-03 04:06:58 +00007637 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007638
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007639 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007640 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007641
John McCall2d74de92009-12-01 22:10:20 +00007642 // FIXME: avoid copy.
7643 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7644 if (UnresExpr->hasExplicitTemplateArgs()) {
7645 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7646 TemplateArgs = &TemplateArgsBuffer;
7647 }
7648
John McCall10eae182009-11-30 22:42:35 +00007649 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7650 E = UnresExpr->decls_end(); I != E; ++I) {
7651
John McCall6e9f8f62009-12-03 04:06:58 +00007652 NamedDecl *Func = *I;
7653 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7654 if (isa<UsingShadowDecl>(Func))
7655 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7656
John McCall10eae182009-11-30 22:42:35 +00007657 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007658 // If explicit template arguments were provided, we can't call a
7659 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007660 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007661 continue;
7662
John McCalla0296f72010-03-19 07:35:19 +00007663 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007664 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007665 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007666 } else {
John McCall10eae182009-11-30 22:42:35 +00007667 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007668 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007669 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007670 CandidateSet,
7671 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007672 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007673 }
Mike Stump11289f42009-09-09 15:08:12 +00007674
John McCall10eae182009-11-30 22:42:35 +00007675 DeclarationName DeclName = UnresExpr->getMemberName();
7676
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007677 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007678 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007679 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007680 case OR_Success:
7681 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007682 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007683 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007684 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007685 break;
7686
7687 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007688 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007689 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007690 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007691 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007692 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007693 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007694
7695 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007696 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007697 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007698 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007699 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007700 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007701
7702 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007703 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007704 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007705 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007706 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007707 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007708 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007709 }
7710
John McCall16df1e52010-03-30 21:47:33 +00007711 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007712
John McCall2d74de92009-12-01 22:10:20 +00007713 // If overload resolution picked a static member, build a
7714 // non-member call based on that function.
7715 if (Method->isStatic()) {
7716 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7717 Args, NumArgs, RParenLoc);
7718 }
7719
John McCall10eae182009-11-30 22:42:35 +00007720 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007721 }
7722
John McCall7decc9e2010-11-18 06:31:45 +00007723 QualType ResultType = Method->getResultType();
7724 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7725 ResultType = ResultType.getNonLValueExprType(Context);
7726
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007727 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007728 CXXMemberCallExpr *TheCall =
7729 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00007730 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007731
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007732 // Check for a valid return type.
7733 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007734 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007735 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007736
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007737 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007738 // We only need to do this if there was actually an overload; otherwise
7739 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007740 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007741 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007742 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7743 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007744 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007745 MemExpr->setBase(ObjectArg);
7746
7747 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007748 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007749 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007750 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007752
John McCallb268a282010-08-23 23:25:46 +00007753 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007754 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007755
John McCallb268a282010-08-23 23:25:46 +00007756 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007757}
7758
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007759/// BuildCallToObjectOfClassType - Build a call to an object of class
7760/// type (C++ [over.call.object]), which can end up invoking an
7761/// overloaded function call operator (@c operator()) or performing a
7762/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007763ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007764Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007765 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007766 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007767 SourceLocation RParenLoc) {
7768 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007769 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007770
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007771 // C++ [over.call.object]p1:
7772 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007773 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007774 // candidate functions includes at least the function call
7775 // operators of T. The function call operators of T are obtained by
7776 // ordinary lookup of the name operator() in the context of
7777 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007778 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007779 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007780
7781 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007782 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007783 << Object->getSourceRange()))
7784 return true;
7785
John McCall27b18f82009-11-17 02:14:36 +00007786 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7787 LookupQualifiedName(R, Record->getDecl());
7788 R.suppressDiagnostics();
7789
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007790 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007791 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007792 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007793 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007794 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007795 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007796
Douglas Gregorab7897a2008-11-19 22:57:39 +00007797 // C++ [over.call.object]p2:
7798 // In addition, for each conversion function declared in T of the
7799 // form
7800 //
7801 // operator conversion-type-id () cv-qualifier;
7802 //
7803 // where cv-qualifier is the same cv-qualification as, or a
7804 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007805 // denotes the type "pointer to function of (P1,...,Pn) returning
7806 // R", or the type "reference to pointer to function of
7807 // (P1,...,Pn) returning R", or the type "reference to function
7808 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007809 // is also considered as a candidate function. Similarly,
7810 // surrogate call functions are added to the set of candidate
7811 // functions for each conversion function declared in an
7812 // accessible base class provided the function is not hidden
7813 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007814 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007815 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007816 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007817 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007818 NamedDecl *D = *I;
7819 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7820 if (isa<UsingShadowDecl>(D))
7821 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7822
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007823 // Skip over templated conversion functions; they aren't
7824 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007825 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007826 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007827
John McCall6e9f8f62009-12-03 04:06:58 +00007828 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007829
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007830 // Strip the reference type (if any) and then the pointer type (if
7831 // any) to get down to what might be a function type.
7832 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7833 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7834 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007835
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007836 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007837 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007838 Object->getType(), Args, NumArgs,
7839 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007840 }
Mike Stump11289f42009-09-09 15:08:12 +00007841
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007842 // Perform overload resolution.
7843 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007844 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7845 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007846 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007847 // Overload resolution succeeded; we'll build the appropriate call
7848 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007849 break;
7850
7851 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007852 if (CandidateSet.empty())
7853 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7854 << Object->getType() << /*call*/ 1
7855 << Object->getSourceRange();
7856 else
7857 Diag(Object->getSourceRange().getBegin(),
7858 diag::err_ovl_no_viable_object_call)
7859 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007860 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007861 break;
7862
7863 case OR_Ambiguous:
7864 Diag(Object->getSourceRange().getBegin(),
7865 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007866 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007867 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007868 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007869
7870 case OR_Deleted:
7871 Diag(Object->getSourceRange().getBegin(),
7872 diag::err_ovl_deleted_object_call)
7873 << Best->Function->isDeleted()
7874 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007875 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007876 break;
Mike Stump11289f42009-09-09 15:08:12 +00007877 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007878
Douglas Gregorb412e172010-07-25 18:17:45 +00007879 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007880 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007881
Douglas Gregorab7897a2008-11-19 22:57:39 +00007882 if (Best->Function == 0) {
7883 // Since there is no function declaration, this is one of the
7884 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007885 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007886 = cast<CXXConversionDecl>(
7887 Best->Conversions[0].UserDefined.ConversionFunction);
7888
John McCalla0296f72010-03-19 07:35:19 +00007889 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007890 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007891
Douglas Gregorab7897a2008-11-19 22:57:39 +00007892 // We selected one of the surrogate functions that converts the
7893 // object parameter to a function pointer. Perform the conversion
7894 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007895
7896 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007897 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007898 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7899 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007900
John McCallfaf5fb42010-08-26 23:41:50 +00007901 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007902 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007903 }
7904
John McCalla0296f72010-03-19 07:35:19 +00007905 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007906 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007907
Douglas Gregorab7897a2008-11-19 22:57:39 +00007908 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7909 // that calls this method, using Object for the implicit object
7910 // parameter and passing along the remaining arguments.
7911 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007912 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007913
7914 unsigned NumArgsInProto = Proto->getNumArgs();
7915 unsigned NumArgsToCheck = NumArgs;
7916
7917 // Build the full argument list for the method call (the
7918 // implicit object parameter is placed at the beginning of the
7919 // list).
7920 Expr **MethodArgs;
7921 if (NumArgs < NumArgsInProto) {
7922 NumArgsToCheck = NumArgsInProto;
7923 MethodArgs = new Expr*[NumArgsInProto + 1];
7924 } else {
7925 MethodArgs = new Expr*[NumArgs + 1];
7926 }
7927 MethodArgs[0] = Object;
7928 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7929 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007930
John McCall7decc9e2010-11-18 06:31:45 +00007931 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007932
7933 // Once we've built TheCall, all of the expressions are properly
7934 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00007935 QualType ResultTy = Method->getResultType();
7936 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7937 ResultTy = ResultTy.getNonLValueExprType(Context);
7938
John McCallb268a282010-08-23 23:25:46 +00007939 CXXOperatorCallExpr *TheCall =
7940 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7941 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00007942 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007943 delete [] MethodArgs;
7944
John McCallb268a282010-08-23 23:25:46 +00007945 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007946 Method))
7947 return true;
7948
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007949 // We may have default arguments. If so, we need to allocate more
7950 // slots in the call for them.
7951 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007952 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007953 else if (NumArgs > NumArgsInProto)
7954 NumArgsToCheck = NumArgsInProto;
7955
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007956 bool IsError = false;
7957
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007958 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007959 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007960 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007961 TheCall->setArg(0, Object);
7962
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007963
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007964 // Check the argument types.
7965 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007966 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007967 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007968 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007969
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007970 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007971
John McCalldadc5752010-08-24 06:29:42 +00007972 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007973 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007974 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007975 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007976 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007977
7978 IsError |= InputInit.isInvalid();
7979 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007980 } else {
John McCalldadc5752010-08-24 06:29:42 +00007981 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007982 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7983 if (DefArg.isInvalid()) {
7984 IsError = true;
7985 break;
7986 }
7987
7988 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007989 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007990
7991 TheCall->setArg(i + 1, Arg);
7992 }
7993
7994 // If this is a variadic call, handle args passed through "...".
7995 if (Proto->isVariadic()) {
7996 // Promote the arguments (C99 6.5.2.2p7).
7997 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7998 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007999 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008000 TheCall->setArg(i + 1, Arg);
8001 }
8002 }
8003
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008004 if (IsError) return true;
8005
John McCallb268a282010-08-23 23:25:46 +00008006 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008007 return true;
8008
John McCalle172be52010-08-24 06:09:16 +00008009 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008010}
8011
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008012/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008013/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008014/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008015ExprResult
John McCallb268a282010-08-23 23:25:46 +00008016Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008017 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008018
John McCallbc077cf2010-02-08 23:07:23 +00008019 SourceLocation Loc = Base->getExprLoc();
8020
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008021 // C++ [over.ref]p1:
8022 //
8023 // [...] An expression x->m is interpreted as (x.operator->())->m
8024 // for a class object x of type T if T::operator->() exists and if
8025 // the operator is selected as the best match function by the
8026 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008027 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008028 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008029 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008030
John McCallbc077cf2010-02-08 23:07:23 +00008031 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008032 PDiag(diag::err_typecheck_incomplete_tag)
8033 << Base->getSourceRange()))
8034 return ExprError();
8035
John McCall27b18f82009-11-17 02:14:36 +00008036 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8037 LookupQualifiedName(R, BaseRecord->getDecl());
8038 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008039
8040 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008041 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008042 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008043 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008044 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008045
8046 // Perform overload resolution.
8047 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008048 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008049 case OR_Success:
8050 // Overload resolution succeeded; we'll build the call below.
8051 break;
8052
8053 case OR_No_Viable_Function:
8054 if (CandidateSet.empty())
8055 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008056 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008057 else
8058 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008059 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008060 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008061 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008062
8063 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008064 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8065 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008066 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008067 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008068
8069 case OR_Deleted:
8070 Diag(OpLoc, diag::err_ovl_deleted_oper)
8071 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008072 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008073 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008074 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008075 }
8076
John McCalla0296f72010-03-19 07:35:19 +00008077 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008078 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008079
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008080 // Convert the object parameter.
8081 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008082 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8083 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008084 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008085
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008086 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008087 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008088
John McCall7decc9e2010-11-18 06:31:45 +00008089 QualType ResultTy = Method->getResultType();
8090 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8091 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008092 CXXOperatorCallExpr *TheCall =
8093 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008094 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008095
John McCallb268a282010-08-23 23:25:46 +00008096 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008097 Method))
8098 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008099 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008100}
8101
Douglas Gregorcd695e52008-11-10 20:40:00 +00008102/// FixOverloadedFunctionReference - E is an expression that refers to
8103/// a C++ overloaded function (possibly with some parentheses and
8104/// perhaps a '&' around it). We have resolved the overloaded function
8105/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008106/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008107Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008108 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008109 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008110 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8111 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008112 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008113 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008114
8115 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8116 }
8117
8118 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008119 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8120 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008121 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008122 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008123 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008124 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008125 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008126 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008127
John McCallcf142162010-08-07 06:22:56 +00008128 return ImplicitCastExpr::Create(Context, ICE->getType(),
8129 ICE->getCastKind(),
8130 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008131 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008132 }
8133
8134 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008135 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008136 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008137 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8138 if (Method->isStatic()) {
8139 // Do nothing: static member functions aren't any different
8140 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008141 } else {
John McCalle66edc12009-11-24 19:00:30 +00008142 // Fix the sub expression, which really has to be an
8143 // UnresolvedLookupExpr holding an overloaded member function
8144 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008145 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8146 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008147 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008148 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008149
John McCalld14a8642009-11-21 08:51:07 +00008150 assert(isa<DeclRefExpr>(SubExpr)
8151 && "fixed to something other than a decl ref");
8152 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8153 && "fixed to a member ref with no nested name qualifier");
8154
8155 // We have taken the address of a pointer to member
8156 // function. Perform the computation here so that we get the
8157 // appropriate pointer to member type.
8158 QualType ClassType
8159 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8160 QualType MemPtrType
8161 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8162
John McCall7decc9e2010-11-18 06:31:45 +00008163 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8164 VK_RValue, OK_Ordinary,
8165 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008166 }
8167 }
John McCall16df1e52010-03-30 21:47:33 +00008168 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8169 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008170 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008171 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008172
John McCalle3027922010-08-25 11:45:40 +00008173 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008174 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008175 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008176 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008177 }
John McCalld14a8642009-11-21 08:51:07 +00008178
8179 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008180 // FIXME: avoid copy.
8181 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008182 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008183 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8184 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008185 }
8186
John McCalld14a8642009-11-21 08:51:07 +00008187 return DeclRefExpr::Create(Context,
8188 ULE->getQualifier(),
8189 ULE->getQualifierRange(),
8190 Fn,
8191 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008192 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008193 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008194 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008195 }
8196
John McCall10eae182009-11-30 22:42:35 +00008197 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008198 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008199 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8200 if (MemExpr->hasExplicitTemplateArgs()) {
8201 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8202 TemplateArgs = &TemplateArgsBuffer;
8203 }
John McCall6b51f282009-11-23 01:53:49 +00008204
John McCall2d74de92009-12-01 22:10:20 +00008205 Expr *Base;
8206
John McCall7decc9e2010-11-18 06:31:45 +00008207 // If we're filling in a static method where we used to have an
8208 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008209 if (MemExpr->isImplicitAccess()) {
8210 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8211 return DeclRefExpr::Create(Context,
8212 MemExpr->getQualifier(),
8213 MemExpr->getQualifierRange(),
8214 Fn,
8215 MemExpr->getMemberLoc(),
8216 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008217 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008218 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008219 } else {
8220 SourceLocation Loc = MemExpr->getMemberLoc();
8221 if (MemExpr->getQualifier())
8222 Loc = MemExpr->getQualifierRange().getBegin();
8223 Base = new (Context) CXXThisExpr(Loc,
8224 MemExpr->getBaseType(),
8225 /*isImplicit=*/true);
8226 }
John McCall2d74de92009-12-01 22:10:20 +00008227 } else
John McCallc3007a22010-10-26 07:05:15 +00008228 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008229
8230 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008231 MemExpr->isArrow(),
8232 MemExpr->getQualifier(),
8233 MemExpr->getQualifierRange(),
8234 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008235 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008236 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008237 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008238 Fn->getType(),
8239 cast<CXXMethodDecl>(Fn)->isStatic()
8240 ? VK_LValue : VK_RValue,
8241 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008242 }
8243
John McCallc3007a22010-10-26 07:05:15 +00008244 llvm_unreachable("Invalid reference to overloaded function");
8245 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008246}
8247
John McCalldadc5752010-08-24 06:29:42 +00008248ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8249 DeclAccessPair Found,
8250 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008251 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008252}
8253
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008254} // end namespace clang