Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Warning:line 9795, column 50
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp -faddrsig
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
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
14#include "clang/Sema/Overload.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/DiagnosticOptions.h"
24#include "clang/Basic/PartialDiagnostic.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/Optional.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/SmallString.h"
36#include <algorithm>
37#include <cstdlib>
38
39using namespace clang;
40using namespace sema;
41
42static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
46}
47
48/// A convenience routine for creating a decayed reference to a function.
49static ExprResult
50CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 const Expr *Base, bool HadMultipleCandidates,
52 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55 return ExprError();
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63 return ExprError();
64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
70
71 S.MarkDeclRefReferenced(DRE, Base);
72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
74}
75
76static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle,
80 bool AllowObjCWritebackConversion);
81
82static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
87static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
91 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
93
94
95static ImplicitConversionSequence::CompareKind
96CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
106CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
110/// GetConversionRank - Retrieve the implicit conversion rank
111/// corresponding to the given implicit conversion kind.
112ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Promotion,
122 ICR_Promotion,
123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_OCL_Scalar_Widening,
135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
156 "Function pointer conversion",
157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
160 "Complex promotion",
161 "Integral conversion",
162 "Floating conversion",
163 "Complex conversion",
164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
167 "Boolean conversion",
168 "Compatible-types conversion",
169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
172 "Complex-real conversion",
173 "Block Pointer conversion",
174 "Transparent Union Conversion",
175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
177 "C specific type conversion",
178 "Incompatible pointer conversion"
179 };
180 return Name[Kind];
181}
182
183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
189 DeprecatedStringLiteralToCharPtr = false;
190 QualificationIncludesObjCLifetime = false;
191 ReferenceBinding = false;
192 DirectBinding = false;
193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
197 ObjCLifetimeConversionBinding = false;
198 CopyConstructor = nullptr;
199}
200
201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
217/// used as part of the ranking of standard conversion sequences
218/// (C++ 13.3.3.2p4).
219bool StandardConversionSequence::isPointerConversionToBool() const {
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
224 if (getToType(1)->isBooleanType() &&
225 (getFromType()->isPointerType() ||
226 getFromType()->isMemberPointerType() ||
227 getFromType()->isObjCObjectPointerType() ||
228 getFromType()->isBlockPointerType() ||
229 getFromType()->isNullPtrType() ||
230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231 return true;
232
233 return false;
234}
235
236/// isPointerConversionToVoidPointer - Determines whether this
237/// conversion is a conversion of a pointer to a void pointer. This is
238/// used as part of the ranking of standard conversion sequences (C++
239/// 13.3.3.2p4).
240bool
241StandardConversionSequence::
242isPointerConversionToVoidPointer(ASTContext& Context) const {
243 QualType FromType = getFromType();
244 QualType ToType = getToType(1);
245
246 // Note that FromType has not necessarily been transformed by the
247 // array-to-pointer implicit conversion, so check for its presence
248 // and redo the conversion to get a pointer.
249 if (First == ICK_Array_To_Pointer)
250 FromType = Context.getArrayDecayedType(FromType);
251
252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254 return ToPtrType->getPointeeType()->isVoidType();
255
256 return false;
257}
258
259/// Skip any implicit casts which could be either part of a narrowing conversion
260/// or after one in an implicit conversion.
261static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263 switch (ICE->getCastKind()) {
264 case CK_NoOp:
265 case CK_IntegralCast:
266 case CK_IntegralToBoolean:
267 case CK_IntegralToFloating:
268 case CK_BooleanToSignedIntegral:
269 case CK_FloatingToIntegral:
270 case CK_FloatingToBoolean:
271 case CK_FloatingCast:
272 Converted = ICE->getSubExpr();
273 continue;
274
275 default:
276 return Converted;
277 }
278 }
279
280 return Converted;
281}
282
283/// Check if this standard conversion sequence represents a narrowing
284/// conversion, according to C++11 [dcl.init.list]p7.
285///
286/// \param Ctx The AST context.
287/// \param Converted The result of applying this standard conversion sequence.
288/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
289/// value of the expression prior to the narrowing conversion.
290/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
291/// type of the expression prior to the narrowing conversion.
292/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293/// from floating point types to integral types should be ignored.
294NarrowingKind StandardConversionSequence::getNarrowingKind(
295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus &&
"narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298
299 // C++11 [dcl.init.list]p7:
300 // A narrowing conversion is an implicit conversion ...
301 QualType FromType = getToType(0);
302 QualType ToType = getToType(1);
303
304 // A conversion to an enumeration type is narrowing if the conversion to
305 // the underlying type is narrowing. This only arises for expressions of
306 // the form 'Enum{init}'.
307 if (auto *ET = ToType->getAs<EnumType>())
308 ToType = ET->getDecl()->getIntegerType();
309
310 switch (Second) {
311 // 'bool' is an integral type; dispatch to the right place to handle it.
312 case ICK_Boolean_Conversion:
313 if (FromType->isRealFloatingType())
314 goto FloatingIntegralConversion;
315 if (FromType->isIntegralOrUnscopedEnumerationType())
316 goto IntegralConversion;
317 // Boolean conversions can be from pointers and pointers to members
318 // [conv.bool], and those aren't considered narrowing conversions.
319 return NK_Not_Narrowing;
320
321 // -- from a floating-point type to an integer type, or
322 //
323 // -- from an integer type or unscoped enumeration type to a floating-point
324 // type, except where the source is a constant expression and the actual
325 // value after conversion will fit into the target type and will produce
326 // the original value when converted back to the original type, or
327 case ICK_Floating_Integral:
328 FloatingIntegralConversion:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332 ToType->isRealFloatingType()) {
333 if (IgnoreFloatToIntegralConversion)
334 return NK_Not_Narrowing;
335 llvm::APSInt IntConstantValue;
336 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337 assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 337, __extension__ __PRETTY_FUNCTION__))
;
338
339 // If it's value-dependent, we can't tell whether it's narrowing.
340 if (Initializer->isValueDependent())
341 return NK_Dependent_Narrowing;
342
343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344 // Convert the integer to the floating type.
345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347 llvm::APFloat::rmNearestTiesToEven);
348 // And back.
349 llvm::APSInt ConvertedValue = IntConstantValue;
350 bool ignored;
351 Result.convertToInteger(ConvertedValue,
352 llvm::APFloat::rmTowardZero, &ignored);
353 // If the resulting value is different, this was a narrowing conversion.
354 if (IntConstantValue != ConvertedValue) {
355 ConstantValue = APValue(IntConstantValue);
356 ConstantType = Initializer->getType();
357 return NK_Constant_Narrowing;
358 }
359 } else {
360 // Variables are always narrowings.
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from long double to double or float, or from double to float, except
367 // where the source is a constant expression and the actual value after
368 // conversion is within the range of values that can be represented (even
369 // if it cannot be represented exactly), or
370 case ICK_Floating_Conversion:
371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373 // FromType is larger than ToType.
374 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375
376 // If it's value-dependent, we can't tell whether it's narrowing.
377 if (Initializer->isValueDependent())
378 return NK_Dependent_Narrowing;
379
380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381 // Constant!
382 assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 382, __extension__ __PRETTY_FUNCTION__))
;
383 llvm::APFloat FloatVal = ConstantValue.getFloat();
384 // Convert the source value into the target type.
385 bool ignored;
386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387 Ctx.getFloatTypeSemantics(ToType),
388 llvm::APFloat::rmNearestTiesToEven, &ignored);
389 // If there was no overflow, the source value is within the range of
390 // values that can be represented.
391 if (ConvertStatus & llvm::APFloat::opOverflow) {
392 ConstantType = Initializer->getType();
393 return NK_Constant_Narrowing;
394 }
395 } else {
396 return NK_Variable_Narrowing;
397 }
398 }
399 return NK_Not_Narrowing;
400
401 // -- from an integer type or unscoped enumeration type to an integer type
402 // that cannot represent all the values of the original type, except where
403 // the source is a constant expression and the actual value after
404 // conversion will fit into the target type and will produce the original
405 // value when converted back to the original type.
406 case ICK_Integral_Conversion:
407 IntegralConversion: {
408 assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 408, __extension__ __PRETTY_FUNCTION__))
;
409 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 409, __extension__ __PRETTY_FUNCTION__))
;
410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411 const unsigned FromWidth = Ctx.getIntWidth(FromType);
412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413 const unsigned ToWidth = Ctx.getIntWidth(ToType);
414
415 if (FromWidth > ToWidth ||
416 (FromWidth == ToWidth && FromSigned != ToSigned) ||
417 (FromSigned && !ToSigned)) {
418 // Not all values of FromType can be represented in ToType.
419 llvm::APSInt InitializerValue;
420 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421
422 // If it's value-dependent, we can't tell whether it's narrowing.
423 if (Initializer->isValueDependent())
424 return NK_Dependent_Narrowing;
425
426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427 // Such conversions on variables are always narrowing.
428 return NK_Variable_Narrowing;
429 }
430 bool Narrowing = false;
431 if (FromWidth < ToWidth) {
432 // Negative -> unsigned is narrowing. Otherwise, more bits is never
433 // narrowing.
434 if (InitializerValue.isSigned() && InitializerValue.isNegative())
435 Narrowing = true;
436 } else {
437 // Add a bit to the InitializerValue so we don't have to worry about
438 // signed vs. unsigned comparisons.
439 InitializerValue = InitializerValue.extend(
440 InitializerValue.getBitWidth() + 1);
441 // Convert the initializer to and from the target width and signed-ness.
442 llvm::APSInt ConvertedValue = InitializerValue;
443 ConvertedValue = ConvertedValue.trunc(ToWidth);
444 ConvertedValue.setIsSigned(ToSigned);
445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446 ConvertedValue.setIsSigned(InitializerValue.isSigned());
447 // If the result is different, this was a narrowing conversion.
448 if (ConvertedValue != InitializerValue)
449 Narrowing = true;
450 }
451 if (Narrowing) {
452 ConstantType = Initializer->getType();
453 ConstantValue = APValue(InitializerValue);
454 return NK_Constant_Narrowing;
455 }
456 }
457 return NK_Not_Narrowing;
458 }
459
460 default:
461 // Other kinds of conversions are not narrowings.
462 return NK_Not_Narrowing;
463 }
464}
465
466/// dump - Print this standard conversion sequence to standard
467/// error. Useful for debugging overloading issues.
468LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
469 raw_ostream &OS = llvm::errs();
470 bool PrintedSomething = false;
471 if (First != ICK_Identity) {
472 OS << GetImplicitConversionName(First);
473 PrintedSomething = true;
474 }
475
476 if (Second != ICK_Identity) {
477 if (PrintedSomething) {
478 OS << " -> ";
479 }
480 OS << GetImplicitConversionName(Second);
481
482 if (CopyConstructor) {
483 OS << " (by copy constructor)";
484 } else if (DirectBinding) {
485 OS << " (direct reference binding)";
486 } else if (ReferenceBinding) {
487 OS << " (reference binding)";
488 }
489 PrintedSomething = true;
490 }
491
492 if (Third != ICK_Identity) {
493 if (PrintedSomething) {
494 OS << " -> ";
495 }
496 OS << GetImplicitConversionName(Third);
497 PrintedSomething = true;
498 }
499
500 if (!PrintedSomething) {
501 OS << "No conversions required";
502 }
503}
504
505/// dump - Print this user-defined conversion sequence to standard
506/// error. Useful for debugging overloading issues.
507void UserDefinedConversionSequence::dump() const {
508 raw_ostream &OS = llvm::errs();
509 if (Before.First || Before.Second || Before.Third) {
510 Before.dump();
511 OS << " -> ";
512 }
513 if (ConversionFunction)
514 OS << '\'' << *ConversionFunction << '\'';
515 else
516 OS << "aggregate initialization";
517 if (After.First || After.Second || After.Third) {
518 OS << " -> ";
519 After.dump();
520 }
521}
522
523/// dump - Print this implicit conversion sequence to standard
524/// error. Useful for debugging overloading issues.
525void ImplicitConversionSequence::dump() const {
526 raw_ostream &OS = llvm::errs();
527 if (isStdInitializerListElement())
528 OS << "Worst std::initializer_list element conversion: ";
529 switch (ConversionKind) {
530 case StandardConversion:
531 OS << "Standard conversion: ";
532 Standard.dump();
533 break;
534 case UserDefinedConversion:
535 OS << "User-defined conversion: ";
536 UserDefined.dump();
537 break;
538 case EllipsisConversion:
539 OS << "Ellipsis conversion";
540 break;
541 case AmbiguousConversion:
542 OS << "Ambiguous conversion";
543 break;
544 case BadConversion:
545 OS << "Bad conversion";
546 break;
547 }
548
549 OS << "\n";
550}
551
552void AmbiguousConversionSequence::construct() {
553 new (&conversions()) ConversionSet();
554}
555
556void AmbiguousConversionSequence::destruct() {
557 conversions().~ConversionSet();
558}
559
560void
561AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562 FromTypePtr = O.FromTypePtr;
563 ToTypePtr = O.ToTypePtr;
564 new (&conversions()) ConversionSet(O.conversions());
565}
566
567namespace {
568 // Structure used by DeductionFailureInfo to store
569 // template argument information.
570 struct DFIArguments {
571 TemplateArgument FirstArg;
572 TemplateArgument SecondArg;
573 };
574 // Structure used by DeductionFailureInfo to store
575 // template parameter and template argument information.
576 struct DFIParamWithArguments : DFIArguments {
577 TemplateParameter Param;
578 };
579 // Structure used by DeductionFailureInfo to store template argument
580 // information and the index of the problematic call argument.
581 struct DFIDeducedMismatchArgs : DFIArguments {
582 TemplateArgumentList *TemplateArgs;
583 unsigned CallArgIndex;
584 };
585}
586
587/// Convert from Sema's representation of template deduction information
588/// to the form used in overload-candidate information.
589DeductionFailureInfo
590clang::MakeDeductionFailureInfo(ASTContext &Context,
591 Sema::TemplateDeductionResult TDK,
592 TemplateDeductionInfo &Info) {
593 DeductionFailureInfo Result;
594 Result.Result = static_cast<unsigned>(TDK);
595 Result.HasDiagnostic = false;
596 switch (TDK) {
597 case Sema::TDK_Invalid:
598 case Sema::TDK_InstantiationDepth:
599 case Sema::TDK_TooManyArguments:
600 case Sema::TDK_TooFewArguments:
601 case Sema::TDK_MiscellaneousDeductionFailure:
602 case Sema::TDK_CUDATargetMismatch:
603 Result.Data = nullptr;
604 break;
605
606 case Sema::TDK_Incomplete:
607 case Sema::TDK_InvalidExplicitArguments:
608 Result.Data = Info.Param.getOpaqueValue();
609 break;
610
611 case Sema::TDK_DeducedMismatch:
612 case Sema::TDK_DeducedMismatchNested: {
613 // FIXME: Should allocate from normal heap so that we can free this later.
614 auto *Saved = new (Context) DFIDeducedMismatchArgs;
615 Saved->FirstArg = Info.FirstArg;
616 Saved->SecondArg = Info.SecondArg;
617 Saved->TemplateArgs = Info.take();
618 Saved->CallArgIndex = Info.CallArgIndex;
619 Result.Data = Saved;
620 break;
621 }
622
623 case Sema::TDK_NonDeducedMismatch: {
624 // FIXME: Should allocate from normal heap so that we can free this later.
625 DFIArguments *Saved = new (Context) DFIArguments;
626 Saved->FirstArg = Info.FirstArg;
627 Saved->SecondArg = Info.SecondArg;
628 Result.Data = Saved;
629 break;
630 }
631
632 case Sema::TDK_IncompletePack:
633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634 case Sema::TDK_Inconsistent:
635 case Sema::TDK_Underqualified: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
638 Saved->Param = Info.Param;
639 Saved->FirstArg = Info.FirstArg;
640 Saved->SecondArg = Info.SecondArg;
641 Result.Data = Saved;
642 break;
643 }
644
645 case Sema::TDK_SubstitutionFailure:
646 Result.Data = Info.take();
647 if (Info.hasSFINAEDiagnostic()) {
648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649 SourceLocation(), PartialDiagnostic::NullDiagnostic());
650 Info.takeSFINAEDiagnostic(*Diag);
651 Result.HasDiagnostic = true;
652 }
653 break;
654
655 case Sema::TDK_Success:
656 case Sema::TDK_NonDependentConversionFailure:
657 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 657)
;
658 }
659
660 return Result;
661}
662
663void DeductionFailureInfo::Destroy() {
664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
666 case Sema::TDK_Invalid:
667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_Incomplete:
669 case Sema::TDK_TooManyArguments:
670 case Sema::TDK_TooFewArguments:
671 case Sema::TDK_InvalidExplicitArguments:
672 case Sema::TDK_CUDATargetMismatch:
673 case Sema::TDK_NonDependentConversionFailure:
674 break;
675
676 case Sema::TDK_IncompletePack:
677 case Sema::TDK_Inconsistent:
678 case Sema::TDK_Underqualified:
679 case Sema::TDK_DeducedMismatch:
680 case Sema::TDK_DeducedMismatchNested:
681 case Sema::TDK_NonDeducedMismatch:
682 // FIXME: Destroy the data?
683 Data = nullptr;
684 break;
685
686 case Sema::TDK_SubstitutionFailure:
687 // FIXME: Destroy the template argument list?
688 Data = nullptr;
689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690 Diag->~PartialDiagnosticAt();
691 HasDiagnostic = false;
692 }
693 break;
694
695 // Unhandled
696 case Sema::TDK_MiscellaneousDeductionFailure:
697 break;
698 }
699}
700
701PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702 if (HasDiagnostic)
703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704 return nullptr;
705}
706
707TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709 case Sema::TDK_Success:
710 case Sema::TDK_Invalid:
711 case Sema::TDK_InstantiationDepth:
712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
714 case Sema::TDK_SubstitutionFailure:
715 case Sema::TDK_DeducedMismatch:
716 case Sema::TDK_DeducedMismatchNested:
717 case Sema::TDK_NonDeducedMismatch:
718 case Sema::TDK_CUDATargetMismatch:
719 case Sema::TDK_NonDependentConversionFailure:
720 return TemplateParameter();
721
722 case Sema::TDK_Incomplete:
723 case Sema::TDK_InvalidExplicitArguments:
724 return TemplateParameter::getFromOpaqueValue(Data);
725
726 case Sema::TDK_IncompletePack:
727 case Sema::TDK_Inconsistent:
728 case Sema::TDK_Underqualified:
729 return static_cast<DFIParamWithArguments*>(Data)->Param;
730
731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
734 }
735
736 return TemplateParameter();
737}
738
739TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741 case Sema::TDK_Success:
742 case Sema::TDK_Invalid:
743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_TooManyArguments:
745 case Sema::TDK_TooFewArguments:
746 case Sema::TDK_Incomplete:
747 case Sema::TDK_IncompletePack:
748 case Sema::TDK_InvalidExplicitArguments:
749 case Sema::TDK_Inconsistent:
750 case Sema::TDK_Underqualified:
751 case Sema::TDK_NonDeducedMismatch:
752 case Sema::TDK_CUDATargetMismatch:
753 case Sema::TDK_NonDependentConversionFailure:
754 return nullptr;
755
756 case Sema::TDK_DeducedMismatch:
757 case Sema::TDK_DeducedMismatchNested:
758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759
760 case Sema::TDK_SubstitutionFailure:
761 return static_cast<TemplateArgumentList*>(Data);
762
763 // Unhandled
764 case Sema::TDK_MiscellaneousDeductionFailure:
765 break;
766 }
767
768 return nullptr;
769}
770
771const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773 case Sema::TDK_Success:
774 case Sema::TDK_Invalid:
775 case Sema::TDK_InstantiationDepth:
776 case Sema::TDK_Incomplete:
777 case Sema::TDK_TooManyArguments:
778 case Sema::TDK_TooFewArguments:
779 case Sema::TDK_InvalidExplicitArguments:
780 case Sema::TDK_SubstitutionFailure:
781 case Sema::TDK_CUDATargetMismatch:
782 case Sema::TDK_NonDependentConversionFailure:
783 return nullptr;
784
785 case Sema::TDK_IncompletePack:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_DeducedMismatch:
789 case Sema::TDK_DeducedMismatchNested:
790 case Sema::TDK_NonDeducedMismatch:
791 return &static_cast<DFIArguments*>(Data)->FirstArg;
792
793 // Unhandled
794 case Sema::TDK_MiscellaneousDeductionFailure:
795 break;
796 }
797
798 return nullptr;
799}
800
801const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803 case Sema::TDK_Success:
804 case Sema::TDK_Invalid:
805 case Sema::TDK_InstantiationDepth:
806 case Sema::TDK_Incomplete:
807 case Sema::TDK_IncompletePack:
808 case Sema::TDK_TooManyArguments:
809 case Sema::TDK_TooFewArguments:
810 case Sema::TDK_InvalidExplicitArguments:
811 case Sema::TDK_SubstitutionFailure:
812 case Sema::TDK_CUDATargetMismatch:
813 case Sema::TDK_NonDependentConversionFailure:
814 return nullptr;
815
816 case Sema::TDK_Inconsistent:
817 case Sema::TDK_Underqualified:
818 case Sema::TDK_DeducedMismatch:
819 case Sema::TDK_DeducedMismatchNested:
820 case Sema::TDK_NonDeducedMismatch:
821 return &static_cast<DFIArguments*>(Data)->SecondArg;
822
823 // Unhandled
824 case Sema::TDK_MiscellaneousDeductionFailure:
825 break;
826 }
827
828 return nullptr;
829}
830
831llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836
837 default:
838 return llvm::None;
839 }
840}
841
842void OverloadCandidateSet::destroyCandidates() {
843 for (iterator i = begin(), e = end(); i != e; ++i) {
844 for (auto &C : i->Conversions)
845 C.~ImplicitConversionSequence();
846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847 i->DeductionFailure.Destroy();
848 }
849}
850
851void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852 destroyCandidates();
853 SlabAllocator.Reset();
854 NumInlineBytesUsed = 0;
855 Candidates.clear();
856 Functions.clear();
857 Kind = CSK;
858}
859
860namespace {
861 class UnbridgedCastsSet {
862 struct Entry {
863 Expr **Addr;
864 Expr *Saved;
865 };
866 SmallVector<Entry, 2> Entries;
867
868 public:
869 void save(Sema &S, Expr *&E) {
870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 870, __extension__ __PRETTY_FUNCTION__))
;
871 Entry entry = { &E, E };
872 Entries.push_back(entry);
873 E = S.stripARCUnbridgedCast(E);
874 }
875
876 void restore() {
877 for (SmallVectorImpl<Entry>::iterator
878 i = Entries.begin(), e = Entries.end(); i != e; ++i)
879 *i->Addr = i->Saved;
880 }
881 };
882}
883
884/// checkPlaceholderForOverload - Do any interesting placeholder-like
885/// preprocessing on the given expression.
886///
887/// \param unbridgedCasts a collection to which to add unbridged casts;
888/// without this, they will be immediately diagnosed as errors
889///
890/// Return true on unrecoverable error.
891static bool
892checkPlaceholderForOverload(Sema &S, Expr *&E,
893 UnbridgedCastsSet *unbridgedCasts = nullptr) {
894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
895 // We can't handle overloaded expressions here because overload
896 // resolution might reasonably tweak them.
897 if (placeholder->getKind() == BuiltinType::Overload) return false;
898
899 // If the context potentially accepts unbridged ARC casts, strip
900 // the unbridged cast and add it to the collection for later restoration.
901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902 unbridgedCasts) {
903 unbridgedCasts->save(S, E);
904 return false;
905 }
906
907 // Go ahead and check everything else.
908 ExprResult result = S.CheckPlaceholderExpr(E);
909 if (result.isInvalid())
910 return true;
911
912 E = result.get();
913 return false;
914 }
915
916 // Nothing to do.
917 return false;
918}
919
920/// checkArgPlaceholdersForOverload - Check a set of call operands for
921/// placeholders.
922static bool checkArgPlaceholdersForOverload(Sema &S,
923 MultiExprArg Args,
924 UnbridgedCastsSet &unbridged) {
925 for (unsigned i = 0, e = Args.size(); i != e; ++i)
926 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927 return true;
928
929 return false;
930}
931
932/// Determine whether the given New declaration is an overload of the
933/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934/// New and Old cannot be overloaded, e.g., if New has the same signature as
935/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936/// functions (or function templates) at all. When it does return Ovl_Match or
937/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939/// declaration.
940///
941/// Example: Given the following input:
942///
943/// void f(int, float); // #1
944/// void f(int, int); // #2
945/// int f(int, int); // #3
946///
947/// When we process #1, there is no previous declaration of "f", so IsOverload
948/// will not be used.
949///
950/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951/// the parameter types, we see that #1 and #2 are overloaded (since they have
952/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953/// unchanged.
954///
955/// When we process #3, Old is an overload set containing #1 and #2. We compare
956/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958/// functions are not part of the signature), IsOverload returns Ovl_Match and
959/// MatchedDecl will be set to point to the FunctionDecl for #2.
960///
961/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962/// by a using declaration. The rules for whether to hide shadow declarations
963/// ignore some properties which otherwise figure into a function template's
964/// signature.
965Sema::OverloadKind
966Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967 NamedDecl *&Match, bool NewIsUsingDecl) {
968 for (LookupResult::iterator I = Old.begin(), E = Old.end();
969 I != E; ++I) {
970 NamedDecl *OldD = *I;
971
972 bool OldIsUsingDecl = false;
973 if (isa<UsingShadowDecl>(OldD)) {
974 OldIsUsingDecl = true;
975
976 // We can always introduce two using declarations into the same
977 // context, even if they have identical signatures.
978 if (NewIsUsingDecl) continue;
979
980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981 }
982
983 // A using-declaration does not conflict with another declaration
984 // if one of them is hidden.
985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986 continue;
987
988 // If either declaration was introduced by a using declaration,
989 // we'll need to use slightly different rules for matching.
990 // Essentially, these rules are the normal rules, except that
991 // function templates hide function templates with different
992 // return types or template parameter lists.
993 bool UseMemberUsingDeclRules =
994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995 !New->getFriendObjectKind();
996
997 if (FunctionDecl *OldF = OldD->getAsFunction()) {
998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001 continue;
1002 }
1003
1004 if (!isa<FunctionTemplateDecl>(OldD) &&
1005 !shouldLinkPossiblyHiddenDecl(*I, New))
1006 continue;
1007
1008 Match = *I;
1009 return Ovl_Match;
1010 }
1011
1012 // Builtins that have custom typechecking or have a reference should
1013 // not be overloadable or redeclarable.
1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015 Match = *I;
1016 return Ovl_NonFunction;
1017 }
1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019 // We can overload with these, which can show up when doing
1020 // redeclaration checks for UsingDecls.
1021 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022 } else if (isa<TagDecl>(OldD)) {
1023 // We can always overload with tags by hiding them.
1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025 // Optimistically assume that an unresolved using decl will
1026 // overload; if it doesn't, we'll have to diagnose during
1027 // template instantiation.
1028 //
1029 // Exception: if the scope is dependent and this is not a class
1030 // member, the using declaration can only introduce an enumerator.
1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032 Match = *I;
1033 return Ovl_NonFunction;
1034 }
1035 } else {
1036 // (C++ 13p1):
1037 // Only function declarations can be overloaded; object and type
1038 // declarations cannot be overloaded.
1039 Match = *I;
1040 return Ovl_NonFunction;
1041 }
1042 }
1043
1044 return Ovl_Overload;
1045}
1046
1047bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1049 // C++ [basic.start.main]p2: This function shall not be overloaded.
1050 if (New->isMain())
1051 return false;
1052
1053 // MSVCRT user defined entry points cannot be overloaded.
1054 if (New->isMSVCRTEntryPoint())
1055 return false;
1056
1057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059
1060 // C++ [temp.fct]p2:
1061 // A function template can be overloaded with other function templates
1062 // and with normal (non-template) functions.
1063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1064 return true;
1065
1066 // Is the function New an overload of the function Old?
1067 QualType OldQType = Context.getCanonicalType(Old->getType());
1068 QualType NewQType = Context.getCanonicalType(New->getType());
1069
1070 // Compare the signatures (C++ 1.3.10) of the two functions to
1071 // determine whether they are overloads. If we find any mismatch
1072 // in the signature, they are overloads.
1073
1074 // If either of these functions is a K&R-style function (no
1075 // prototype), then we consider them to have matching signatures.
1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078 return false;
1079
1080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1082
1083 // The signature of a function includes the types of its
1084 // parameters (C++ 1.3.10), which includes the presence or absence
1085 // of the ellipsis; see C++ DR 357).
1086 if (OldQType != NewQType &&
1087 (OldType->getNumParams() != NewType->getNumParams() ||
1088 OldType->isVariadic() != NewType->isVariadic() ||
1089 !FunctionParamTypesAreEqual(OldType, NewType)))
1090 return true;
1091
1092 // C++ [temp.over.link]p4:
1093 // The signature of a function template consists of its function
1094 // signature, its return type and its template parameter list. The names
1095 // of the template parameters are significant only for establishing the
1096 // relationship between the template parameters and the rest of the
1097 // signature.
1098 //
1099 // We check the return type and template parameter lists for function
1100 // templates first; the remaining checks follow.
1101 //
1102 // However, we don't consider either of these when deciding whether
1103 // a member introduced by a shadow declaration is hidden.
1104 if (!UseMemberUsingDeclRules && NewTemplate &&
1105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106 OldTemplate->getTemplateParameters(),
1107 false, TPL_TemplateMatch) ||
1108 OldType->getReturnType() != NewType->getReturnType()))
1109 return true;
1110
1111 // If the function is a class member, its signature includes the
1112 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1113 //
1114 // As part of this, also check whether one of the member functions
1115 // is static, in which case they are not overloads (C++
1116 // 13.1p2). While not part of the definition of the signature,
1117 // this check is important to determine whether these functions
1118 // can be overloaded.
1119 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1120 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1121 if (OldMethod && NewMethod &&
1122 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1123 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1124 if (!UseMemberUsingDeclRules &&
1125 (OldMethod->getRefQualifier() == RQ_None ||
1126 NewMethod->getRefQualifier() == RQ_None)) {
1127 // C++0x [over.load]p2:
1128 // - Member function declarations with the same name and the same
1129 // parameter-type-list as well as member function template
1130 // declarations with the same name, the same parameter-type-list, and
1131 // the same template parameter lists cannot be overloaded if any of
1132 // them, but not all, have a ref-qualifier (8.3.5).
1133 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1134 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1135 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1136 }
1137 return true;
1138 }
1139
1140 // We may not have applied the implicit const for a constexpr member
1141 // function yet (because we haven't yet resolved whether this is a static
1142 // or non-static member function). Add it now, on the assumption that this
1143 // is a redeclaration of OldMethod.
1144 unsigned OldQuals = OldMethod->getTypeQualifiers();
1145 unsigned NewQuals = NewMethod->getTypeQualifiers();
1146 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1147 !isa<CXXConstructorDecl>(NewMethod))
1148 NewQuals |= Qualifiers::Const;
1149
1150 // We do not allow overloading based off of '__restrict'.
1151 OldQuals &= ~Qualifiers::Restrict;
1152 NewQuals &= ~Qualifiers::Restrict;
1153 if (OldQuals != NewQuals)
1154 return true;
1155 }
1156
1157 // Though pass_object_size is placed on parameters and takes an argument, we
1158 // consider it to be a function-level modifier for the sake of function
1159 // identity. Either the function has one or more parameters with
1160 // pass_object_size or it doesn't.
1161 if (functionHasPassObjectSizeParams(New) !=
1162 functionHasPassObjectSizeParams(Old))
1163 return true;
1164
1165 // enable_if attributes are an order-sensitive part of the signature.
1166 for (specific_attr_iterator<EnableIfAttr>
1167 NewI = New->specific_attr_begin<EnableIfAttr>(),
1168 NewE = New->specific_attr_end<EnableIfAttr>(),
1169 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1170 OldE = Old->specific_attr_end<EnableIfAttr>();
1171 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1172 if (NewI == NewE || OldI == OldE)
1173 return true;
1174 llvm::FoldingSetNodeID NewID, OldID;
1175 NewI->getCond()->Profile(NewID, Context, true);
1176 OldI->getCond()->Profile(OldID, Context, true);
1177 if (NewID != OldID)
1178 return true;
1179 }
1180
1181 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1182 // Don't allow overloading of destructors. (In theory we could, but it
1183 // would be a giant change to clang.)
1184 if (isa<CXXDestructorDecl>(New))
1185 return false;
1186
1187 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1188 OldTarget = IdentifyCUDATarget(Old);
1189 if (NewTarget == CFT_InvalidTarget)
1190 return false;
1191
1192 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1192, __extension__ __PRETTY_FUNCTION__))
;
1193
1194 // Allow overloading of functions with same signature and different CUDA
1195 // target attributes.
1196 return NewTarget != OldTarget;
1197 }
1198
1199 // The signatures match; this is not an overload.
1200 return false;
1201}
1202
1203/// Checks availability of the function depending on the current
1204/// function context. Inside an unavailable function, unavailability is ignored.
1205///
1206/// \returns true if \arg FD is unavailable and current context is inside
1207/// an available function, false otherwise.
1208bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1209 if (!FD->isUnavailable())
1210 return false;
1211
1212 // Walk up the context of the caller.
1213 Decl *C = cast<Decl>(CurContext);
1214 do {
1215 if (C->isUnavailable())
1216 return false;
1217 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1218 return true;
1219}
1220
1221/// Tries a user-defined conversion from From to ToType.
1222///
1223/// Produces an implicit conversion sequence for when a standard conversion
1224/// is not an option. See TryImplicitConversion for more information.
1225static ImplicitConversionSequence
1226TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1227 bool SuppressUserConversions,
1228 bool AllowExplicit,
1229 bool InOverloadResolution,
1230 bool CStyle,
1231 bool AllowObjCWritebackConversion,
1232 bool AllowObjCConversionOnExplicit) {
1233 ImplicitConversionSequence ICS;
1234
1235 if (SuppressUserConversions) {
1236 // We're not in the case above, so there is no conversion that
1237 // we can perform.
1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1239 return ICS;
1240 }
1241
1242 // Attempt user-defined conversion.
1243 OverloadCandidateSet Conversions(From->getExprLoc(),
1244 OverloadCandidateSet::CSK_Normal);
1245 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1246 Conversions, AllowExplicit,
1247 AllowObjCConversionOnExplicit)) {
1248 case OR_Success:
1249 case OR_Deleted:
1250 ICS.setUserDefined();
1251 // C++ [over.ics.user]p4:
1252 // A conversion of an expression of class type to the same class
1253 // type is given Exact Match rank, and a conversion of an
1254 // expression of class type to a base class of that type is
1255 // given Conversion rank, in spite of the fact that a copy
1256 // constructor (i.e., a user-defined conversion function) is
1257 // called for those cases.
1258 if (CXXConstructorDecl *Constructor
1259 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1260 QualType FromCanon
1261 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1262 QualType ToCanon
1263 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1264 if (Constructor->isCopyConstructor() &&
1265 (FromCanon == ToCanon ||
1266 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1267 // Turn this into a "standard" conversion sequence, so that it
1268 // gets ranked with standard conversion sequences.
1269 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1270 ICS.setStandard();
1271 ICS.Standard.setAsIdentityConversion();
1272 ICS.Standard.setFromType(From->getType());
1273 ICS.Standard.setAllToTypes(ToType);
1274 ICS.Standard.CopyConstructor = Constructor;
1275 ICS.Standard.FoundCopyConstructor = Found;
1276 if (ToCanon != FromCanon)
1277 ICS.Standard.Second = ICK_Derived_To_Base;
1278 }
1279 }
1280 break;
1281
1282 case OR_Ambiguous:
1283 ICS.setAmbiguous();
1284 ICS.Ambiguous.setFromType(From->getType());
1285 ICS.Ambiguous.setToType(ToType);
1286 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1287 Cand != Conversions.end(); ++Cand)
1288 if (Cand->Viable)
1289 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1290 break;
1291
1292 // Fall through.
1293 case OR_No_Viable_Function:
1294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1295 break;
1296 }
1297
1298 return ICS;
1299}
1300
1301/// TryImplicitConversion - Attempt to perform an implicit conversion
1302/// from the given expression (Expr) to the given type (ToType). This
1303/// function returns an implicit conversion sequence that can be used
1304/// to perform the initialization. Given
1305///
1306/// void f(float f);
1307/// void g(int i) { f(i); }
1308///
1309/// this routine would produce an implicit conversion sequence to
1310/// describe the initialization of f from i, which will be a standard
1311/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1312/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1313//
1314/// Note that this routine only determines how the conversion can be
1315/// performed; it does not actually perform the conversion. As such,
1316/// it will not produce any diagnostics if no conversion is available,
1317/// but will instead return an implicit conversion sequence of kind
1318/// "BadConversion".
1319///
1320/// If @p SuppressUserConversions, then user-defined conversions are
1321/// not permitted.
1322/// If @p AllowExplicit, then explicit user-defined conversions are
1323/// permitted.
1324///
1325/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1326/// writeback conversion, which allows __autoreleasing id* parameters to
1327/// be initialized with __strong id* or __weak id* arguments.
1328static ImplicitConversionSequence
1329TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1330 bool SuppressUserConversions,
1331 bool AllowExplicit,
1332 bool InOverloadResolution,
1333 bool CStyle,
1334 bool AllowObjCWritebackConversion,
1335 bool AllowObjCConversionOnExplicit) {
1336 ImplicitConversionSequence ICS;
1337 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1338 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1339 ICS.setStandard();
1340 return ICS;
1341 }
1342
1343 if (!S.getLangOpts().CPlusPlus) {
1344 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1345 return ICS;
1346 }
1347
1348 // C++ [over.ics.user]p4:
1349 // A conversion of an expression of class type to the same class
1350 // type is given Exact Match rank, and a conversion of an
1351 // expression of class type to a base class of that type is
1352 // given Conversion rank, in spite of the fact that a copy/move
1353 // constructor (i.e., a user-defined conversion function) is
1354 // called for those cases.
1355 QualType FromType = From->getType();
1356 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1357 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1358 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1359 ICS.setStandard();
1360 ICS.Standard.setAsIdentityConversion();
1361 ICS.Standard.setFromType(FromType);
1362 ICS.Standard.setAllToTypes(ToType);
1363
1364 // We don't actually check at this point whether there is a valid
1365 // copy/move constructor, since overloading just assumes that it
1366 // exists. When we actually perform initialization, we'll find the
1367 // appropriate constructor to copy the returned object, if needed.
1368 ICS.Standard.CopyConstructor = nullptr;
1369
1370 // Determine whether this is considered a derived-to-base conversion.
1371 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1372 ICS.Standard.Second = ICK_Derived_To_Base;
1373
1374 return ICS;
1375 }
1376
1377 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1378 AllowExplicit, InOverloadResolution, CStyle,
1379 AllowObjCWritebackConversion,
1380 AllowObjCConversionOnExplicit);
1381}
1382
1383ImplicitConversionSequence
1384Sema::TryImplicitConversion(Expr *From, QualType ToType,
1385 bool SuppressUserConversions,
1386 bool AllowExplicit,
1387 bool InOverloadResolution,
1388 bool CStyle,
1389 bool AllowObjCWritebackConversion) {
1390 return ::TryImplicitConversion(*this, From, ToType,
1391 SuppressUserConversions, AllowExplicit,
1392 InOverloadResolution, CStyle,
1393 AllowObjCWritebackConversion,
1394 /*AllowObjCConversionOnExplicit=*/false);
1395}
1396
1397/// PerformImplicitConversion - Perform an implicit conversion of the
1398/// expression From to the type ToType. Returns the
1399/// converted expression. Flavor is the kind of conversion we're
1400/// performing, used in the error message. If @p AllowExplicit,
1401/// explicit user-defined conversions are permitted.
1402ExprResult
1403Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1404 AssignmentAction Action, bool AllowExplicit) {
1405 ImplicitConversionSequence ICS;
1406 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1407}
1408
1409ExprResult
1410Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1411 AssignmentAction Action, bool AllowExplicit,
1412 ImplicitConversionSequence& ICS) {
1413 if (checkPlaceholderForOverload(*this, From))
1414 return ExprError();
1415
1416 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1417 bool AllowObjCWritebackConversion
1418 = getLangOpts().ObjCAutoRefCount &&
1419 (Action == AA_Passing || Action == AA_Sending);
1420 if (getLangOpts().ObjC1)
1421 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1422 ToType, From->getType(), From);
1423 ICS = ::TryImplicitConversion(*this, From, ToType,
1424 /*SuppressUserConversions=*/false,
1425 AllowExplicit,
1426 /*InOverloadResolution=*/false,
1427 /*CStyle=*/false,
1428 AllowObjCWritebackConversion,
1429 /*AllowObjCConversionOnExplicit=*/false);
1430 return PerformImplicitConversion(From, ToType, ICS, Action);
1431}
1432
1433/// Determine whether the conversion from FromType to ToType is a valid
1434/// conversion that strips "noexcept" or "noreturn" off the nested function
1435/// type.
1436bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1437 QualType &ResultTy) {
1438 if (Context.hasSameUnqualifiedType(FromType, ToType))
1439 return false;
1440
1441 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1442 // or F(t noexcept) -> F(t)
1443 // where F adds one of the following at most once:
1444 // - a pointer
1445 // - a member pointer
1446 // - a block pointer
1447 // Changes here need matching changes in FindCompositePointerType.
1448 CanQualType CanTo = Context.getCanonicalType(ToType);
1449 CanQualType CanFrom = Context.getCanonicalType(FromType);
1450 Type::TypeClass TyClass = CanTo->getTypeClass();
1451 if (TyClass != CanFrom->getTypeClass()) return false;
1452 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1453 if (TyClass == Type::Pointer) {
1454 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1455 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1456 } else if (TyClass == Type::BlockPointer) {
1457 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1458 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1459 } else if (TyClass == Type::MemberPointer) {
1460 auto ToMPT = CanTo.getAs<MemberPointerType>();
1461 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1462 // A function pointer conversion cannot change the class of the function.
1463 if (ToMPT->getClass() != FromMPT->getClass())
1464 return false;
1465 CanTo = ToMPT->getPointeeType();
1466 CanFrom = FromMPT->getPointeeType();
1467 } else {
1468 return false;
1469 }
1470
1471 TyClass = CanTo->getTypeClass();
1472 if (TyClass != CanFrom->getTypeClass()) return false;
1473 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1474 return false;
1475 }
1476
1477 const auto *FromFn = cast<FunctionType>(CanFrom);
1478 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1479
1480 const auto *ToFn = cast<FunctionType>(CanTo);
1481 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1482
1483 bool Changed = false;
1484
1485 // Drop 'noreturn' if not present in target type.
1486 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1487 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1488 Changed = true;
1489 }
1490
1491 // Drop 'noexcept' if not present in target type.
1492 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1493 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1494 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1495 FromFn = cast<FunctionType>(
1496 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1497 EST_None)
1498 .getTypePtr());
1499 Changed = true;
1500 }
1501
1502 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1503 // only if the ExtParameterInfo lists of the two function prototypes can be
1504 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1505 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1506 bool CanUseToFPT, CanUseFromFPT;
1507 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1508 CanUseFromFPT, NewParamInfos) &&
1509 CanUseToFPT && !CanUseFromFPT) {
1510 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1511 ExtInfo.ExtParameterInfos =
1512 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1513 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1514 FromFPT->getParamTypes(), ExtInfo);
1515 FromFn = QT->getAs<FunctionType>();
1516 Changed = true;
1517 }
1518 }
1519
1520 if (!Changed)
1521 return false;
1522
1523 assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1523, __extension__ __PRETTY_FUNCTION__))
;
1524 if (QualType(FromFn, 0) != CanTo) return false;
1525
1526 ResultTy = ToType;
1527 return true;
1528}
1529
1530/// Determine whether the conversion from FromType to ToType is a valid
1531/// vector conversion.
1532///
1533/// \param ICK Will be set to the vector conversion kind, if this is a vector
1534/// conversion.
1535static bool IsVectorConversion(Sema &S, QualType FromType,
1536 QualType ToType, ImplicitConversionKind &ICK) {
1537 // We need at least one of these types to be a vector type to have a vector
1538 // conversion.
1539 if (!ToType->isVectorType() && !FromType->isVectorType())
1540 return false;
1541
1542 // Identical types require no conversions.
1543 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1544 return false;
1545
1546 // There are no conversions between extended vector types, only identity.
1547 if (ToType->isExtVectorType()) {
1548 // There are no conversions between extended vector types other than the
1549 // identity conversion.
1550 if (FromType->isExtVectorType())
1551 return false;
1552
1553 // Vector splat from any arithmetic type to a vector.
1554 if (FromType->isArithmeticType()) {
1555 ICK = ICK_Vector_Splat;
1556 return true;
1557 }
1558 }
1559
1560 // We can perform the conversion between vector types in the following cases:
1561 // 1)vector types are equivalent AltiVec and GCC vector types
1562 // 2)lax vector conversions are permitted and the vector types are of the
1563 // same size
1564 if (ToType->isVectorType() && FromType->isVectorType()) {
1565 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1566 S.isLaxVectorConversion(FromType, ToType)) {
1567 ICK = ICK_Vector_Conversion;
1568 return true;
1569 }
1570 }
1571
1572 return false;
1573}
1574
1575static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1576 bool InOverloadResolution,
1577 StandardConversionSequence &SCS,
1578 bool CStyle);
1579
1580/// IsStandardConversion - Determines whether there is a standard
1581/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1582/// expression From to the type ToType. Standard conversion sequences
1583/// only consider non-class types; for conversions that involve class
1584/// types, use TryImplicitConversion. If a conversion exists, SCS will
1585/// contain the standard conversion sequence required to perform this
1586/// conversion and this routine will return true. Otherwise, this
1587/// routine will return false and the value of SCS is unspecified.
1588static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1589 bool InOverloadResolution,
1590 StandardConversionSequence &SCS,
1591 bool CStyle,
1592 bool AllowObjCWritebackConversion) {
1593 QualType FromType = From->getType();
1594
1595 // Standard conversions (C++ [conv])
1596 SCS.setAsIdentityConversion();
1597 SCS.IncompatibleObjC = false;
1598 SCS.setFromType(FromType);
1599 SCS.CopyConstructor = nullptr;
1600
1601 // There are no standard conversions for class types in C++, so
1602 // abort early. When overloading in C, however, we do permit them.
1603 if (S.getLangOpts().CPlusPlus &&
1604 (FromType->isRecordType() || ToType->isRecordType()))
1605 return false;
1606
1607 // The first conversion can be an lvalue-to-rvalue conversion,
1608 // array-to-pointer conversion, or function-to-pointer conversion
1609 // (C++ 4p1).
1610
1611 if (FromType == S.Context.OverloadTy) {
1612 DeclAccessPair AccessPair;
1613 if (FunctionDecl *Fn
1614 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1615 AccessPair)) {
1616 // We were able to resolve the address of the overloaded function,
1617 // so we can convert to the type of that function.
1618 FromType = Fn->getType();
1619 SCS.setFromType(FromType);
1620
1621 // we can sometimes resolve &foo<int> regardless of ToType, so check
1622 // if the type matches (identity) or we are converting to bool
1623 if (!S.Context.hasSameUnqualifiedType(
1624 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1625 QualType resultTy;
1626 // if the function type matches except for [[noreturn]], it's ok
1627 if (!S.IsFunctionConversion(FromType,
1628 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1629 // otherwise, only a boolean conversion is standard
1630 if (!ToType->isBooleanType())
1631 return false;
1632 }
1633
1634 // Check if the "from" expression is taking the address of an overloaded
1635 // function and recompute the FromType accordingly. Take advantage of the
1636 // fact that non-static member functions *must* have such an address-of
1637 // expression.
1638 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1639 if (Method && !Method->isStatic()) {
1640 assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1641, __extension__ __PRETTY_FUNCTION__))
1641 "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1641, __extension__ __PRETTY_FUNCTION__))
;
1642 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1643 == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1644 "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
;
1645 const Type *ClassType
1646 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1647 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1648 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1649 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
1650 UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
1651 "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
;
1652 FromType = S.Context.getPointerType(FromType);
1653 }
1654
1655 // Check that we've computed the proper type after overload resolution.
1656 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1657 // be calling it from within an NDEBUG block.
1658 assert(S.Context.hasSameType((static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1660, __extension__ __PRETTY_FUNCTION__))
1659 FromType,(static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1660, __extension__ __PRETTY_FUNCTION__))
1660 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))(static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1660, __extension__ __PRETTY_FUNCTION__))
;
1661 } else {
1662 return false;
1663 }
1664 }
1665 // Lvalue-to-rvalue conversion (C++11 4.1):
1666 // A glvalue (3.10) of a non-function, non-array type T can
1667 // be converted to a prvalue.
1668 bool argIsLValue = From->isGLValue();
1669 if (argIsLValue &&
1670 !FromType->isFunctionType() && !FromType->isArrayType() &&
1671 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1672 SCS.First = ICK_Lvalue_To_Rvalue;
1673
1674 // C11 6.3.2.1p2:
1675 // ... if the lvalue has atomic type, the value has the non-atomic version
1676 // of the type of the lvalue ...
1677 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1678 FromType = Atomic->getValueType();
1679
1680 // If T is a non-class type, the type of the rvalue is the
1681 // cv-unqualified version of T. Otherwise, the type of the rvalue
1682 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1683 // just strip the qualifiers because they don't matter.
1684 FromType = FromType.getUnqualifiedType();
1685 } else if (FromType->isArrayType()) {
1686 // Array-to-pointer conversion (C++ 4.2)
1687 SCS.First = ICK_Array_To_Pointer;
1688
1689 // An lvalue or rvalue of type "array of N T" or "array of unknown
1690 // bound of T" can be converted to an rvalue of type "pointer to
1691 // T" (C++ 4.2p1).
1692 FromType = S.Context.getArrayDecayedType(FromType);
1693
1694 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1695 // This conversion is deprecated in C++03 (D.4)
1696 SCS.DeprecatedStringLiteralToCharPtr = true;
1697
1698 // For the purpose of ranking in overload resolution
1699 // (13.3.3.1.1), this conversion is considered an
1700 // array-to-pointer conversion followed by a qualification
1701 // conversion (4.4). (C++ 4.2p2)
1702 SCS.Second = ICK_Identity;
1703 SCS.Third = ICK_Qualification;
1704 SCS.QualificationIncludesObjCLifetime = false;
1705 SCS.setAllToTypes(FromType);
1706 return true;
1707 }
1708 } else if (FromType->isFunctionType() && argIsLValue) {
1709 // Function-to-pointer conversion (C++ 4.3).
1710 SCS.First = ICK_Function_To_Pointer;
1711
1712 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1713 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1714 if (!S.checkAddressOfFunctionIsAvailable(FD))
1715 return false;
1716
1717 // An lvalue of function type T can be converted to an rvalue of
1718 // type "pointer to T." The result is a pointer to the
1719 // function. (C++ 4.3p1).
1720 FromType = S.Context.getPointerType(FromType);
1721 } else {
1722 // We don't require any conversions for the first step.
1723 SCS.First = ICK_Identity;
1724 }
1725 SCS.setToType(0, FromType);
1726
1727 // The second conversion can be an integral promotion, floating
1728 // point promotion, integral conversion, floating point conversion,
1729 // floating-integral conversion, pointer conversion,
1730 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1731 // For overloading in C, this can also be a "compatible-type"
1732 // conversion.
1733 bool IncompatibleObjC = false;
1734 ImplicitConversionKind SecondICK = ICK_Identity;
1735 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1736 // The unqualified versions of the types are the same: there's no
1737 // conversion to do.
1738 SCS.Second = ICK_Identity;
1739 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1740 // Integral promotion (C++ 4.5).
1741 SCS.Second = ICK_Integral_Promotion;
1742 FromType = ToType.getUnqualifiedType();
1743 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1744 // Floating point promotion (C++ 4.6).
1745 SCS.Second = ICK_Floating_Promotion;
1746 FromType = ToType.getUnqualifiedType();
1747 } else if (S.IsComplexPromotion(FromType, ToType)) {
1748 // Complex promotion (Clang extension)
1749 SCS.Second = ICK_Complex_Promotion;
1750 FromType = ToType.getUnqualifiedType();
1751 } else if (ToType->isBooleanType() &&
1752 (FromType->isArithmeticType() ||
1753 FromType->isAnyPointerType() ||
1754 FromType->isBlockPointerType() ||
1755 FromType->isMemberPointerType() ||
1756 FromType->isNullPtrType())) {
1757 // Boolean conversions (C++ 4.12).
1758 SCS.Second = ICK_Boolean_Conversion;
1759 FromType = S.Context.BoolTy;
1760 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1761 ToType->isIntegralType(S.Context)) {
1762 // Integral conversions (C++ 4.7).
1763 SCS.Second = ICK_Integral_Conversion;
1764 FromType = ToType.getUnqualifiedType();
1765 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1766 // Complex conversions (C99 6.3.1.6)
1767 SCS.Second = ICK_Complex_Conversion;
1768 FromType = ToType.getUnqualifiedType();
1769 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1770 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1771 // Complex-real conversions (C99 6.3.1.7)
1772 SCS.Second = ICK_Complex_Real;
1773 FromType = ToType.getUnqualifiedType();
1774 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1775 // FIXME: disable conversions between long double and __float128 if
1776 // their representation is different until there is back end support
1777 // We of course allow this conversion if long double is really double.
1778 if (&S.Context.getFloatTypeSemantics(FromType) !=
1779 &S.Context.getFloatTypeSemantics(ToType)) {
1780 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1781 ToType == S.Context.LongDoubleTy) ||
1782 (FromType == S.Context.LongDoubleTy &&
1783 ToType == S.Context.Float128Ty));
1784 if (Float128AndLongDouble &&
1785 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1786 &llvm::APFloat::PPCDoubleDouble()))
1787 return false;
1788 }
1789 // Floating point conversions (C++ 4.8).
1790 SCS.Second = ICK_Floating_Conversion;
1791 FromType = ToType.getUnqualifiedType();
1792 } else if ((FromType->isRealFloatingType() &&
1793 ToType->isIntegralType(S.Context)) ||
1794 (FromType->isIntegralOrUnscopedEnumerationType() &&
1795 ToType->isRealFloatingType())) {
1796 // Floating-integral conversions (C++ 4.9).
1797 SCS.Second = ICK_Floating_Integral;
1798 FromType = ToType.getUnqualifiedType();
1799 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1800 SCS.Second = ICK_Block_Pointer_Conversion;
1801 } else if (AllowObjCWritebackConversion &&
1802 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1803 SCS.Second = ICK_Writeback_Conversion;
1804 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1805 FromType, IncompatibleObjC)) {
1806 // Pointer conversions (C++ 4.10).
1807 SCS.Second = ICK_Pointer_Conversion;
1808 SCS.IncompatibleObjC = IncompatibleObjC;
1809 FromType = FromType.getUnqualifiedType();
1810 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1811 InOverloadResolution, FromType)) {
1812 // Pointer to member conversions (4.11).
1813 SCS.Second = ICK_Pointer_Member;
1814 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1815 SCS.Second = SecondICK;
1816 FromType = ToType.getUnqualifiedType();
1817 } else if (!S.getLangOpts().CPlusPlus &&
1818 S.Context.typesAreCompatible(ToType, FromType)) {
1819 // Compatible conversions (Clang extension for C function overloading)
1820 SCS.Second = ICK_Compatible_Conversion;
1821 FromType = ToType.getUnqualifiedType();
1822 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1823 InOverloadResolution,
1824 SCS, CStyle)) {
1825 SCS.Second = ICK_TransparentUnionConversion;
1826 FromType = ToType;
1827 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1828 CStyle)) {
1829 // tryAtomicConversion has updated the standard conversion sequence
1830 // appropriately.
1831 return true;
1832 } else if (ToType->isEventT() &&
1833 From->isIntegerConstantExpr(S.getASTContext()) &&
1834 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1835 SCS.Second = ICK_Zero_Event_Conversion;
1836 FromType = ToType;
1837 } else if (ToType->isQueueT() &&
1838 From->isIntegerConstantExpr(S.getASTContext()) &&
1839 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1840 SCS.Second = ICK_Zero_Queue_Conversion;
1841 FromType = ToType;
1842 } else {
1843 // No second conversion required.
1844 SCS.Second = ICK_Identity;
1845 }
1846 SCS.setToType(1, FromType);
1847
1848 // The third conversion can be a function pointer conversion or a
1849 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1850 bool ObjCLifetimeConversion;
1851 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1852 // Function pointer conversions (removing 'noexcept') including removal of
1853 // 'noreturn' (Clang extension).
1854 SCS.Third = ICK_Function_Conversion;
1855 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1856 ObjCLifetimeConversion)) {
1857 SCS.Third = ICK_Qualification;
1858 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1859 FromType = ToType;
1860 } else {
1861 // No conversion required
1862 SCS.Third = ICK_Identity;
1863 }
1864
1865 // C++ [over.best.ics]p6:
1866 // [...] Any difference in top-level cv-qualification is
1867 // subsumed by the initialization itself and does not constitute
1868 // a conversion. [...]
1869 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1870 QualType CanonTo = S.Context.getCanonicalType(ToType);
1871 if (CanonFrom.getLocalUnqualifiedType()
1872 == CanonTo.getLocalUnqualifiedType() &&
1873 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1874 FromType = ToType;
1875 CanonFrom = CanonTo;
1876 }
1877
1878 SCS.setToType(2, FromType);
1879
1880 if (CanonFrom == CanonTo)
1881 return true;
1882
1883 // If we have not converted the argument type to the parameter type,
1884 // this is a bad conversion sequence, unless we're resolving an overload in C.
1885 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1886 return false;
1887
1888 ExprResult ER = ExprResult{From};
1889 Sema::AssignConvertType Conv =
1890 S.CheckSingleAssignmentConstraints(ToType, ER,
1891 /*Diagnose=*/false,
1892 /*DiagnoseCFAudited=*/false,
1893 /*ConvertRHS=*/false);
1894 ImplicitConversionKind SecondConv;
1895 switch (Conv) {
1896 case Sema::Compatible:
1897 SecondConv = ICK_C_Only_Conversion;
1898 break;
1899 // For our purposes, discarding qualifiers is just as bad as using an
1900 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1901 // qualifiers, as well.
1902 case Sema::CompatiblePointerDiscardsQualifiers:
1903 case Sema::IncompatiblePointer:
1904 case Sema::IncompatiblePointerSign:
1905 SecondConv = ICK_Incompatible_Pointer_Conversion;
1906 break;
1907 default:
1908 return false;
1909 }
1910
1911 // First can only be an lvalue conversion, so we pretend that this was the
1912 // second conversion. First should already be valid from earlier in the
1913 // function.
1914 SCS.Second = SecondConv;
1915 SCS.setToType(1, ToType);
1916
1917 // Third is Identity, because Second should rank us worse than any other
1918 // conversion. This could also be ICK_Qualification, but it's simpler to just
1919 // lump everything in with the second conversion, and we don't gain anything
1920 // from making this ICK_Qualification.
1921 SCS.Third = ICK_Identity;
1922 SCS.setToType(2, ToType);
1923 return true;
1924}
1925
1926static bool
1927IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1928 QualType &ToType,
1929 bool InOverloadResolution,
1930 StandardConversionSequence &SCS,
1931 bool CStyle) {
1932
1933 const RecordType *UT = ToType->getAsUnionType();
1934 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1935 return false;
1936 // The field to initialize within the transparent union.
1937 RecordDecl *UD = UT->getDecl();
1938 // It's compatible if the expression matches any of the fields.
1939 for (const auto *it : UD->fields()) {
1940 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1941 CStyle, /*ObjCWritebackConversion=*/false)) {
1942 ToType = it->getType();
1943 return true;
1944 }
1945 }
1946 return false;
1947}
1948
1949/// IsIntegralPromotion - Determines whether the conversion from the
1950/// expression From (whose potentially-adjusted type is FromType) to
1951/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1952/// sets PromotedType to the promoted type.
1953bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1954 const BuiltinType *To = ToType->getAs<BuiltinType>();
1955 // All integers are built-in.
1956 if (!To) {
1957 return false;
1958 }
1959
1960 // An rvalue of type char, signed char, unsigned char, short int, or
1961 // unsigned short int can be converted to an rvalue of type int if
1962 // int can represent all the values of the source type; otherwise,
1963 // the source rvalue can be converted to an rvalue of type unsigned
1964 // int (C++ 4.5p1).
1965 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1966 !FromType->isEnumeralType()) {
1967 if (// We can promote any signed, promotable integer type to an int
1968 (FromType->isSignedIntegerType() ||
1969 // We can promote any unsigned integer type whose size is
1970 // less than int to an int.
1971 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1972 return To->getKind() == BuiltinType::Int;
1973 }
1974
1975 return To->getKind() == BuiltinType::UInt;
1976 }
1977
1978 // C++11 [conv.prom]p3:
1979 // A prvalue of an unscoped enumeration type whose underlying type is not
1980 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1981 // following types that can represent all the values of the enumeration
1982 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1983 // unsigned int, long int, unsigned long int, long long int, or unsigned
1984 // long long int. If none of the types in that list can represent all the
1985 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1986 // type can be converted to an rvalue a prvalue of the extended integer type
1987 // with lowest integer conversion rank (4.13) greater than the rank of long
1988 // long in which all the values of the enumeration can be represented. If
1989 // there are two such extended types, the signed one is chosen.
1990 // C++11 [conv.prom]p4:
1991 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1992 // can be converted to a prvalue of its underlying type. Moreover, if
1993 // integral promotion can be applied to its underlying type, a prvalue of an
1994 // unscoped enumeration type whose underlying type is fixed can also be
1995 // converted to a prvalue of the promoted underlying type.
1996 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1997 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1998 // provided for a scoped enumeration.
1999 if (FromEnumType->getDecl()->isScoped())
2000 return false;
2001
2002 // We can perform an integral promotion to the underlying type of the enum,
2003 // even if that's not the promoted type. Note that the check for promoting
2004 // the underlying type is based on the type alone, and does not consider
2005 // the bitfield-ness of the actual source expression.
2006 if (FromEnumType->getDecl()->isFixed()) {
2007 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2008 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2009 IsIntegralPromotion(nullptr, Underlying, ToType);
2010 }
2011
2012 // We have already pre-calculated the promotion type, so this is trivial.
2013 if (ToType->isIntegerType() &&
2014 isCompleteType(From->getLocStart(), FromType))
2015 return Context.hasSameUnqualifiedType(
2016 ToType, FromEnumType->getDecl()->getPromotionType());
2017
2018 // C++ [conv.prom]p5:
2019 // If the bit-field has an enumerated type, it is treated as any other
2020 // value of that type for promotion purposes.
2021 //
2022 // ... so do not fall through into the bit-field checks below in C++.
2023 if (getLangOpts().CPlusPlus)
2024 return false;
2025 }
2026
2027 // C++0x [conv.prom]p2:
2028 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2029 // to an rvalue a prvalue of the first of the following types that can
2030 // represent all the values of its underlying type: int, unsigned int,
2031 // long int, unsigned long int, long long int, or unsigned long long int.
2032 // If none of the types in that list can represent all the values of its
2033 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2034 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2035 // type.
2036 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2037 ToType->isIntegerType()) {
2038 // Determine whether the type we're converting from is signed or
2039 // unsigned.
2040 bool FromIsSigned = FromType->isSignedIntegerType();
2041 uint64_t FromSize = Context.getTypeSize(FromType);
2042
2043 // The types we'll try to promote to, in the appropriate
2044 // order. Try each of these types.
2045 QualType PromoteTypes[6] = {
2046 Context.IntTy, Context.UnsignedIntTy,
2047 Context.LongTy, Context.UnsignedLongTy ,
2048 Context.LongLongTy, Context.UnsignedLongLongTy
2049 };
2050 for (int Idx = 0; Idx < 6; ++Idx) {
2051 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2052 if (FromSize < ToSize ||
2053 (FromSize == ToSize &&
2054 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2055 // We found the type that we can promote to. If this is the
2056 // type we wanted, we have a promotion. Otherwise, no
2057 // promotion.
2058 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2059 }
2060 }
2061 }
2062
2063 // An rvalue for an integral bit-field (9.6) can be converted to an
2064 // rvalue of type int if int can represent all the values of the
2065 // bit-field; otherwise, it can be converted to unsigned int if
2066 // unsigned int can represent all the values of the bit-field. If
2067 // the bit-field is larger yet, no integral promotion applies to
2068 // it. If the bit-field has an enumerated type, it is treated as any
2069 // other value of that type for promotion purposes (C++ 4.5p3).
2070 // FIXME: We should delay checking of bit-fields until we actually perform the
2071 // conversion.
2072 //
2073 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2074 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2075 // bit-fields and those whose underlying type is larger than int) for GCC
2076 // compatibility.
2077 if (From) {
2078 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2079 llvm::APSInt BitWidth;
2080 if (FromType->isIntegralType(Context) &&
2081 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2082 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2083 ToSize = Context.getTypeSize(ToType);
2084
2085 // Are we promoting to an int from a bitfield that fits in an int?
2086 if (BitWidth < ToSize ||
2087 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2088 return To->getKind() == BuiltinType::Int;
2089 }
2090
2091 // Are we promoting to an unsigned int from an unsigned bitfield
2092 // that fits into an unsigned int?
2093 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2094 return To->getKind() == BuiltinType::UInt;
2095 }
2096
2097 return false;
2098 }
2099 }
2100 }
2101
2102 // An rvalue of type bool can be converted to an rvalue of type int,
2103 // with false becoming zero and true becoming one (C++ 4.5p4).
2104 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
2111/// IsFloatingPointPromotion - Determines whether the conversion from
2112/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2113/// returns true and sets PromotedType to the promoted type.
2114bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2115 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2116 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2117 /// An rvalue of type float can be converted to an rvalue of type
2118 /// double. (C++ 4.6p1).
2119 if (FromBuiltin->getKind() == BuiltinType::Float &&
2120 ToBuiltin->getKind() == BuiltinType::Double)
2121 return true;
2122
2123 // C99 6.3.1.5p1:
2124 // When a float is promoted to double or long double, or a
2125 // double is promoted to long double [...].
2126 if (!getLangOpts().CPlusPlus &&
2127 (FromBuiltin->getKind() == BuiltinType::Float ||
2128 FromBuiltin->getKind() == BuiltinType::Double) &&
2129 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2130 ToBuiltin->getKind() == BuiltinType::Float128))
2131 return true;
2132
2133 // Half can be promoted to float.
2134 if (!getLangOpts().NativeHalfType &&
2135 FromBuiltin->getKind() == BuiltinType::Half &&
2136 ToBuiltin->getKind() == BuiltinType::Float)
2137 return true;
2138 }
2139
2140 return false;
2141}
2142
2143/// Determine if a conversion is a complex promotion.
2144///
2145/// A complex promotion is defined as a complex -> complex conversion
2146/// where the conversion between the underlying real types is a
2147/// floating-point or integral promotion.
2148bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2149 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2150 if (!FromComplex)
2151 return false;
2152
2153 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2154 if (!ToComplex)
2155 return false;
2156
2157 return IsFloatingPointPromotion(FromComplex->getElementType(),
2158 ToComplex->getElementType()) ||
2159 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2160 ToComplex->getElementType());
2161}
2162
2163/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2164/// the pointer type FromPtr to a pointer to type ToPointee, with the
2165/// same type qualifiers as FromPtr has on its pointee type. ToType,
2166/// if non-empty, will be a pointer to ToType that may or may not have
2167/// the right set of qualifiers on its pointee.
2168///
2169static QualType
2170BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2171 QualType ToPointee, QualType ToType,
2172 ASTContext &Context,
2173 bool StripObjCLifetime = false) {
2174 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2176, __extension__ __PRETTY_FUNCTION__))
2175 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2176, __extension__ __PRETTY_FUNCTION__))
2176 "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2176, __extension__ __PRETTY_FUNCTION__))
;
2177
2178 /// Conversions to 'id' subsume cv-qualifier conversions.
2179 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2180 return ToType.getUnqualifiedType();
2181
2182 QualType CanonFromPointee
2183 = Context.getCanonicalType(FromPtr->getPointeeType());
2184 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2185 Qualifiers Quals = CanonFromPointee.getQualifiers();
2186
2187 if (StripObjCLifetime)
2188 Quals.removeObjCLifetime();
2189
2190 // Exact qualifier match -> return the pointer type we're converting to.
2191 if (CanonToPointee.getLocalQualifiers() == Quals) {
2192 // ToType is exactly what we need. Return it.
2193 if (!ToType.isNull())
2194 return ToType.getUnqualifiedType();
2195
2196 // Build a pointer to ToPointee. It has the right qualifiers
2197 // already.
2198 if (isa<ObjCObjectPointerType>(ToType))
2199 return Context.getObjCObjectPointerType(ToPointee);
2200 return Context.getPointerType(ToPointee);
2201 }
2202
2203 // Just build a canonical type that has the right qualifiers.
2204 QualType QualifiedCanonToPointee
2205 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2206
2207 if (isa<ObjCObjectPointerType>(ToType))
2208 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2209 return Context.getPointerType(QualifiedCanonToPointee);
2210}
2211
2212static bool isNullPointerConstantForConversion(Expr *Expr,
2213 bool InOverloadResolution,
2214 ASTContext &Context) {
2215 // Handle value-dependent integral null pointer constants correctly.
2216 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2217 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2218 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2219 return !InOverloadResolution;
2220
2221 return Expr->isNullPointerConstant(Context,
2222 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2223 : Expr::NPC_ValueDependentIsNull);
2224}
2225
2226/// IsPointerConversion - Determines whether the conversion of the
2227/// expression From, which has the (possibly adjusted) type FromType,
2228/// can be converted to the type ToType via a pointer conversion (C++
2229/// 4.10). If so, returns true and places the converted type (that
2230/// might differ from ToType in its cv-qualifiers at some level) into
2231/// ConvertedType.
2232///
2233/// This routine also supports conversions to and from block pointers
2234/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2235/// pointers to interfaces. FIXME: Once we've determined the
2236/// appropriate overloading rules for Objective-C, we may want to
2237/// split the Objective-C checks into a different routine; however,
2238/// GCC seems to consider all of these conversions to be pointer
2239/// conversions, so for now they live here. IncompatibleObjC will be
2240/// set if the conversion is an allowed Objective-C conversion that
2241/// should result in a warning.
2242bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2243 bool InOverloadResolution,
2244 QualType& ConvertedType,
2245 bool &IncompatibleObjC) {
2246 IncompatibleObjC = false;
2247 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2248 IncompatibleObjC))
2249 return true;
2250
2251 // Conversion from a null pointer constant to any Objective-C pointer type.
2252 if (ToType->isObjCObjectPointerType() &&
2253 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2254 ConvertedType = ToType;
2255 return true;
2256 }
2257
2258 // Blocks: Block pointers can be converted to void*.
2259 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2260 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2261 ConvertedType = ToType;
2262 return true;
2263 }
2264 // Blocks: A null pointer constant can be converted to a block
2265 // pointer type.
2266 if (ToType->isBlockPointerType() &&
2267 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2268 ConvertedType = ToType;
2269 return true;
2270 }
2271
2272 // If the left-hand-side is nullptr_t, the right side can be a null
2273 // pointer constant.
2274 if (ToType->isNullPtrType() &&
2275 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2276 ConvertedType = ToType;
2277 return true;
2278 }
2279
2280 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2281 if (!ToTypePtr)
2282 return false;
2283
2284 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2285 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2286 ConvertedType = ToType;
2287 return true;
2288 }
2289
2290 // Beyond this point, both types need to be pointers
2291 // , including objective-c pointers.
2292 QualType ToPointeeType = ToTypePtr->getPointeeType();
2293 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2294 !getLangOpts().ObjCAutoRefCount) {
2295 ConvertedType = BuildSimilarlyQualifiedPointerType(
2296 FromType->getAs<ObjCObjectPointerType>(),
2297 ToPointeeType,
2298 ToType, Context);
2299 return true;
2300 }
2301 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2302 if (!FromTypePtr)
2303 return false;
2304
2305 QualType FromPointeeType = FromTypePtr->getPointeeType();
2306
2307 // If the unqualified pointee types are the same, this can't be a
2308 // pointer conversion, so don't do all of the work below.
2309 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2310 return false;
2311
2312 // An rvalue of type "pointer to cv T," where T is an object type,
2313 // can be converted to an rvalue of type "pointer to cv void" (C++
2314 // 4.10p2).
2315 if (FromPointeeType->isIncompleteOrObjectType() &&
2316 ToPointeeType->isVoidType()) {
2317 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2318 ToPointeeType,
2319 ToType, Context,
2320 /*StripObjCLifetime=*/true);
2321 return true;
2322 }
2323
2324 // MSVC allows implicit function to void* type conversion.
2325 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2326 ToPointeeType->isVoidType()) {
2327 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2328 ToPointeeType,
2329 ToType, Context);
2330 return true;
2331 }
2332
2333 // When we're overloading in C, we allow a special kind of pointer
2334 // conversion for compatible-but-not-identical pointee types.
2335 if (!getLangOpts().CPlusPlus &&
2336 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2337 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338 ToPointeeType,
2339 ToType, Context);
2340 return true;
2341 }
2342
2343 // C++ [conv.ptr]p3:
2344 //
2345 // An rvalue of type "pointer to cv D," where D is a class type,
2346 // can be converted to an rvalue of type "pointer to cv B," where
2347 // B is a base class (clause 10) of D. If B is an inaccessible
2348 // (clause 11) or ambiguous (10.2) base class of D, a program that
2349 // necessitates this conversion is ill-formed. The result of the
2350 // conversion is a pointer to the base class sub-object of the
2351 // derived class object. The null pointer value is converted to
2352 // the null pointer value of the destination type.
2353 //
2354 // Note that we do not check for ambiguity or inaccessibility
2355 // here. That is handled by CheckPointerConversion.
2356 if (getLangOpts().CPlusPlus &&
2357 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2358 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2359 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2360 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2361 ToPointeeType,
2362 ToType, Context);
2363 return true;
2364 }
2365
2366 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2367 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2368 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2369 ToPointeeType,
2370 ToType, Context);
2371 return true;
2372 }
2373
2374 return false;
2375}
2376
2377/// Adopt the given qualifiers for the given type.
2378static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2379 Qualifiers TQs = T.getQualifiers();
2380
2381 // Check whether qualifiers already match.
2382 if (TQs == Qs)
2383 return T;
2384
2385 if (Qs.compatiblyIncludes(TQs))
2386 return Context.getQualifiedType(T, Qs);
2387
2388 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2389}
2390
2391/// isObjCPointerConversion - Determines whether this is an
2392/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2393/// with the same arguments and return values.
2394bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2395 QualType& ConvertedType,
2396 bool &IncompatibleObjC) {
2397 if (!getLangOpts().ObjC1)
2398 return false;
2399
2400 // The set of qualifiers on the type we're converting from.
2401 Qualifiers FromQualifiers = FromType.getQualifiers();
2402
2403 // First, we handle all conversions on ObjC object pointer types.
2404 const ObjCObjectPointerType* ToObjCPtr =
2405 ToType->getAs<ObjCObjectPointerType>();
2406 const ObjCObjectPointerType *FromObjCPtr =
2407 FromType->getAs<ObjCObjectPointerType>();
2408
2409 if (ToObjCPtr && FromObjCPtr) {
2410 // If the pointee types are the same (ignoring qualifications),
2411 // then this is not a pointer conversion.
2412 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2413 FromObjCPtr->getPointeeType()))
2414 return false;
2415
2416 // Conversion between Objective-C pointers.
2417 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2418 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2419 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2420 if (getLangOpts().CPlusPlus && LHS && RHS &&
2421 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2422 FromObjCPtr->getPointeeType()))
2423 return false;
2424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2425 ToObjCPtr->getPointeeType(),
2426 ToType, Context);
2427 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2428 return true;
2429 }
2430
2431 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2432 // Okay: this is some kind of implicit downcast of Objective-C
2433 // interfaces, which is permitted. However, we're going to
2434 // complain about it.
2435 IncompatibleObjC = true;
2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2437 ToObjCPtr->getPointeeType(),
2438 ToType, Context);
2439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2440 return true;
2441 }
2442 }
2443 // Beyond this point, both types need to be C pointers or block pointers.
2444 QualType ToPointeeType;
2445 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2446 ToPointeeType = ToCPtr->getPointeeType();
2447 else if (const BlockPointerType *ToBlockPtr =
2448 ToType->getAs<BlockPointerType>()) {
2449 // Objective C++: We're able to convert from a pointer to any object
2450 // to a block pointer type.
2451 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2452 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2453 return true;
2454 }
2455 ToPointeeType = ToBlockPtr->getPointeeType();
2456 }
2457 else if (FromType->getAs<BlockPointerType>() &&
2458 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2459 // Objective C++: We're able to convert from a block pointer type to a
2460 // pointer to any object.
2461 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2462 return true;
2463 }
2464 else
2465 return false;
2466
2467 QualType FromPointeeType;
2468 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2469 FromPointeeType = FromCPtr->getPointeeType();
2470 else if (const BlockPointerType *FromBlockPtr =
2471 FromType->getAs<BlockPointerType>())
2472 FromPointeeType = FromBlockPtr->getPointeeType();
2473 else
2474 return false;
2475
2476 // If we have pointers to pointers, recursively check whether this
2477 // is an Objective-C conversion.
2478 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2479 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2480 IncompatibleObjC)) {
2481 // We always complain about this conversion.
2482 IncompatibleObjC = true;
2483 ConvertedType = Context.getPointerType(ConvertedType);
2484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2485 return true;
2486 }
2487 // Allow conversion of pointee being objective-c pointer to another one;
2488 // as in I* to id.
2489 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2490 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2492 IncompatibleObjC)) {
2493
2494 ConvertedType = Context.getPointerType(ConvertedType);
2495 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2496 return true;
2497 }
2498
2499 // If we have pointers to functions or blocks, check whether the only
2500 // differences in the argument and result types are in Objective-C
2501 // pointer conversions. If so, we permit the conversion (but
2502 // complain about it).
2503 const FunctionProtoType *FromFunctionType
2504 = FromPointeeType->getAs<FunctionProtoType>();
2505 const FunctionProtoType *ToFunctionType
2506 = ToPointeeType->getAs<FunctionProtoType>();
2507 if (FromFunctionType && ToFunctionType) {
2508 // If the function types are exactly the same, this isn't an
2509 // Objective-C pointer conversion.
2510 if (Context.getCanonicalType(FromPointeeType)
2511 == Context.getCanonicalType(ToPointeeType))
2512 return false;
2513
2514 // Perform the quick checks that will tell us whether these
2515 // function types are obviously different.
2516 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2517 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2518 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2519 return false;
2520
2521 bool HasObjCConversion = false;
2522 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2523 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2524 // Okay, the types match exactly. Nothing to do.
2525 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2526 ToFunctionType->getReturnType(),
2527 ConvertedType, IncompatibleObjC)) {
2528 // Okay, we have an Objective-C pointer conversion.
2529 HasObjCConversion = true;
2530 } else {
2531 // Function types are too different. Abort.
2532 return false;
2533 }
2534
2535 // Check argument types.
2536 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2537 ArgIdx != NumArgs; ++ArgIdx) {
2538 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2539 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2540 if (Context.getCanonicalType(FromArgType)
2541 == Context.getCanonicalType(ToArgType)) {
2542 // Okay, the types match exactly. Nothing to do.
2543 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2544 ConvertedType, IncompatibleObjC)) {
2545 // Okay, we have an Objective-C pointer conversion.
2546 HasObjCConversion = true;
2547 } else {
2548 // Argument types are too different. Abort.
2549 return false;
2550 }
2551 }
2552
2553 if (HasObjCConversion) {
2554 // We had an Objective-C conversion. Allow this pointer
2555 // conversion, but complain about it.
2556 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2557 IncompatibleObjC = true;
2558 return true;
2559 }
2560 }
2561
2562 return false;
2563}
2564
2565/// Determine whether this is an Objective-C writeback conversion,
2566/// used for parameter passing when performing automatic reference counting.
2567///
2568/// \param FromType The type we're converting form.
2569///
2570/// \param ToType The type we're converting to.
2571///
2572/// \param ConvertedType The type that will be produced after applying
2573/// this conversion.
2574bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2575 QualType &ConvertedType) {
2576 if (!getLangOpts().ObjCAutoRefCount ||
2577 Context.hasSameUnqualifiedType(FromType, ToType))
2578 return false;
2579
2580 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2581 QualType ToPointee;
2582 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2583 ToPointee = ToPointer->getPointeeType();
2584 else
2585 return false;
2586
2587 Qualifiers ToQuals = ToPointee.getQualifiers();
2588 if (!ToPointee->isObjCLifetimeType() ||
2589 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2590 !ToQuals.withoutObjCLifetime().empty())
2591 return false;
2592
2593 // Argument must be a pointer to __strong to __weak.
2594 QualType FromPointee;
2595 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2596 FromPointee = FromPointer->getPointeeType();
2597 else
2598 return false;
2599
2600 Qualifiers FromQuals = FromPointee.getQualifiers();
2601 if (!FromPointee->isObjCLifetimeType() ||
2602 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2603 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2604 return false;
2605
2606 // Make sure that we have compatible qualifiers.
2607 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2608 if (!ToQuals.compatiblyIncludes(FromQuals))
2609 return false;
2610
2611 // Remove qualifiers from the pointee type we're converting from; they
2612 // aren't used in the compatibility check belong, and we'll be adding back
2613 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2614 FromPointee = FromPointee.getUnqualifiedType();
2615
2616 // The unqualified form of the pointee types must be compatible.
2617 ToPointee = ToPointee.getUnqualifiedType();
2618 bool IncompatibleObjC;
2619 if (Context.typesAreCompatible(FromPointee, ToPointee))
2620 FromPointee = ToPointee;
2621 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2622 IncompatibleObjC))
2623 return false;
2624
2625 /// Construct the type we're converting to, which is a pointer to
2626 /// __autoreleasing pointee.
2627 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2628 ConvertedType = Context.getPointerType(FromPointee);
2629 return true;
2630}
2631
2632bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2633 QualType& ConvertedType) {
2634 QualType ToPointeeType;
2635 if (const BlockPointerType *ToBlockPtr =
2636 ToType->getAs<BlockPointerType>())
2637 ToPointeeType = ToBlockPtr->getPointeeType();
2638 else
2639 return false;
2640
2641 QualType FromPointeeType;
2642 if (const BlockPointerType *FromBlockPtr =
2643 FromType->getAs<BlockPointerType>())
2644 FromPointeeType = FromBlockPtr->getPointeeType();
2645 else
2646 return false;
2647 // We have pointer to blocks, check whether the only
2648 // differences in the argument and result types are in Objective-C
2649 // pointer conversions. If so, we permit the conversion.
2650
2651 const FunctionProtoType *FromFunctionType
2652 = FromPointeeType->getAs<FunctionProtoType>();
2653 const FunctionProtoType *ToFunctionType
2654 = ToPointeeType->getAs<FunctionProtoType>();
2655
2656 if (!FromFunctionType || !ToFunctionType)
2657 return false;
2658
2659 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2660 return true;
2661
2662 // Perform the quick checks that will tell us whether these
2663 // function types are obviously different.
2664 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2665 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2666 return false;
2667
2668 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2669 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2670 if (FromEInfo != ToEInfo)
2671 return false;
2672
2673 bool IncompatibleObjC = false;
2674 if (Context.hasSameType(FromFunctionType->getReturnType(),
2675 ToFunctionType->getReturnType())) {
2676 // Okay, the types match exactly. Nothing to do.
2677 } else {
2678 QualType RHS = FromFunctionType->getReturnType();
2679 QualType LHS = ToFunctionType->getReturnType();
2680 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2681 !RHS.hasQualifiers() && LHS.hasQualifiers())
2682 LHS = LHS.getUnqualifiedType();
2683
2684 if (Context.hasSameType(RHS,LHS)) {
2685 // OK exact match.
2686 } else if (isObjCPointerConversion(RHS, LHS,
2687 ConvertedType, IncompatibleObjC)) {
2688 if (IncompatibleObjC)
2689 return false;
2690 // Okay, we have an Objective-C pointer conversion.
2691 }
2692 else
2693 return false;
2694 }
2695
2696 // Check argument types.
2697 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2698 ArgIdx != NumArgs; ++ArgIdx) {
2699 IncompatibleObjC = false;
2700 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2701 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2702 if (Context.hasSameType(FromArgType, ToArgType)) {
2703 // Okay, the types match exactly. Nothing to do.
2704 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2705 ConvertedType, IncompatibleObjC)) {
2706 if (IncompatibleObjC)
2707 return false;
2708 // Okay, we have an Objective-C pointer conversion.
2709 } else
2710 // Argument types are too different. Abort.
2711 return false;
2712 }
2713
2714 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2715 bool CanUseToFPT, CanUseFromFPT;
2716 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2717 CanUseToFPT, CanUseFromFPT,
2718 NewParamInfos))
2719 return false;
2720
2721 ConvertedType = ToType;
2722 return true;
2723}
2724
2725enum {
2726 ft_default,
2727 ft_different_class,
2728 ft_parameter_arity,
2729 ft_parameter_mismatch,
2730 ft_return_type,
2731 ft_qualifer_mismatch,
2732 ft_noexcept
2733};
2734
2735/// Attempts to get the FunctionProtoType from a Type. Handles
2736/// MemberFunctionPointers properly.
2737static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2738 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2739 return FPT;
2740
2741 if (auto *MPT = FromType->getAs<MemberPointerType>())
2742 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2743
2744 return nullptr;
2745}
2746
2747/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2748/// function types. Catches different number of parameter, mismatch in
2749/// parameter types, and different return types.
2750void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2751 QualType FromType, QualType ToType) {
2752 // If either type is not valid, include no extra info.
2753 if (FromType.isNull() || ToType.isNull()) {
2754 PDiag << ft_default;
2755 return;
2756 }
2757
2758 // Get the function type from the pointers.
2759 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2760 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2761 *ToMember = ToType->getAs<MemberPointerType>();
2762 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2763 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2764 << QualType(FromMember->getClass(), 0);
2765 return;
2766 }
2767 FromType = FromMember->getPointeeType();
2768 ToType = ToMember->getPointeeType();
2769 }
2770
2771 if (FromType->isPointerType())
2772 FromType = FromType->getPointeeType();
2773 if (ToType->isPointerType())
2774 ToType = ToType->getPointeeType();
2775
2776 // Remove references.
2777 FromType = FromType.getNonReferenceType();
2778 ToType = ToType.getNonReferenceType();
2779
2780 // Don't print extra info for non-specialized template functions.
2781 if (FromType->isInstantiationDependentType() &&
2782 !FromType->getAs<TemplateSpecializationType>()) {
2783 PDiag << ft_default;
2784 return;
2785 }
2786
2787 // No extra info for same types.
2788 if (Context.hasSameType(FromType, ToType)) {
2789 PDiag << ft_default;
2790 return;
2791 }
2792
2793 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2794 *ToFunction = tryGetFunctionProtoType(ToType);
2795
2796 // Both types need to be function types.
2797 if (!FromFunction || !ToFunction) {
2798 PDiag << ft_default;
2799 return;
2800 }
2801
2802 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2803 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2804 << FromFunction->getNumParams();
2805 return;
2806 }
2807
2808 // Handle different parameter types.
2809 unsigned ArgPos;
2810 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2811 PDiag << ft_parameter_mismatch << ArgPos + 1
2812 << ToFunction->getParamType(ArgPos)
2813 << FromFunction->getParamType(ArgPos);
2814 return;
2815 }
2816
2817 // Handle different return type.
2818 if (!Context.hasSameType(FromFunction->getReturnType(),
2819 ToFunction->getReturnType())) {
2820 PDiag << ft_return_type << ToFunction->getReturnType()
2821 << FromFunction->getReturnType();
2822 return;
2823 }
2824
2825 unsigned FromQuals = FromFunction->getTypeQuals(),
2826 ToQuals = ToFunction->getTypeQuals();
2827 if (FromQuals != ToQuals) {
2828 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2829 return;
2830 }
2831
2832 // Handle exception specification differences on canonical type (in C++17
2833 // onwards).
2834 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2835 ->isNothrow() !=
2836 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2837 ->isNothrow()) {
2838 PDiag << ft_noexcept;
2839 return;
2840 }
2841
2842 // Unable to find a difference, so add no extra info.
2843 PDiag << ft_default;
2844}
2845
2846/// FunctionParamTypesAreEqual - This routine checks two function proto types
2847/// for equality of their argument types. Caller has already checked that
2848/// they have same number of arguments. If the parameters are different,
2849/// ArgPos will have the parameter index of the first different parameter.
2850bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2851 const FunctionProtoType *NewType,
2852 unsigned *ArgPos) {
2853 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2854 N = NewType->param_type_begin(),
2855 E = OldType->param_type_end();
2856 O && (O != E); ++O, ++N) {
2857 if (!Context.hasSameType(O->getUnqualifiedType(),
2858 N->getUnqualifiedType())) {
2859 if (ArgPos)
2860 *ArgPos = O - OldType->param_type_begin();
2861 return false;
2862 }
2863 }
2864 return true;
2865}
2866
2867/// CheckPointerConversion - Check the pointer conversion from the
2868/// expression From to the type ToType. This routine checks for
2869/// ambiguous or inaccessible derived-to-base pointer
2870/// conversions for which IsPointerConversion has already returned
2871/// true. It returns true and produces a diagnostic if there was an
2872/// error, or returns false otherwise.
2873bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2874 CastKind &Kind,
2875 CXXCastPath& BasePath,
2876 bool IgnoreBaseAccess,
2877 bool Diagnose) {
2878 QualType FromType = From->getType();
2879 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2880
2881 Kind = CK_BitCast;
2882
2883 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2884 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2885 Expr::NPCK_ZeroExpression) {
2886 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2887 DiagRuntimeBehavior(From->getExprLoc(), From,
2888 PDiag(diag::warn_impcast_bool_to_null_pointer)
2889 << ToType << From->getSourceRange());
2890 else if (!isUnevaluatedContext())
2891 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2892 << ToType << From->getSourceRange();
2893 }
2894 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2895 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2896 QualType FromPointeeType = FromPtrType->getPointeeType(),
2897 ToPointeeType = ToPtrType->getPointeeType();
2898
2899 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2900 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2901 // We must have a derived-to-base conversion. Check an
2902 // ambiguous or inaccessible conversion.
2903 unsigned InaccessibleID = 0;
2904 unsigned AmbigiousID = 0;
2905 if (Diagnose) {
2906 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2907 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2908 }
2909 if (CheckDerivedToBaseConversion(
2910 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2911 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2912 &BasePath, IgnoreBaseAccess))
2913 return true;
2914
2915 // The conversion was successful.
2916 Kind = CK_DerivedToBase;
2917 }
2918
2919 if (Diagnose && !IsCStyleOrFunctionalCast &&
2920 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2921 assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2922, __extension__ __PRETTY_FUNCTION__))
2922 "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2922, __extension__ __PRETTY_FUNCTION__))
;
2923 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2924 << From->getSourceRange();
2925 }
2926 }
2927 } else if (const ObjCObjectPointerType *ToPtrType =
2928 ToType->getAs<ObjCObjectPointerType>()) {
2929 if (const ObjCObjectPointerType *FromPtrType =
2930 FromType->getAs<ObjCObjectPointerType>()) {
2931 // Objective-C++ conversions are always okay.
2932 // FIXME: We should have a different class of conversions for the
2933 // Objective-C++ implicit conversions.
2934 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2935 return false;
2936 } else if (FromType->isBlockPointerType()) {
2937 Kind = CK_BlockPointerToObjCPointerCast;
2938 } else {
2939 Kind = CK_CPointerToObjCPointerCast;
2940 }
2941 } else if (ToType->isBlockPointerType()) {
2942 if (!FromType->isBlockPointerType())
2943 Kind = CK_AnyPointerToBlockPointerCast;
2944 }
2945
2946 // We shouldn't fall into this case unless it's valid for other
2947 // reasons.
2948 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2949 Kind = CK_NullToPointer;
2950
2951 return false;
2952}
2953
2954/// IsMemberPointerConversion - Determines whether the conversion of the
2955/// expression From, which has the (possibly adjusted) type FromType, can be
2956/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2957/// If so, returns true and places the converted type (that might differ from
2958/// ToType in its cv-qualifiers at some level) into ConvertedType.
2959bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2960 QualType ToType,
2961 bool InOverloadResolution,
2962 QualType &ConvertedType) {
2963 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2964 if (!ToTypePtr)
2965 return false;
2966
2967 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2968 if (From->isNullPointerConstant(Context,
2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970 : Expr::NPC_ValueDependentIsNull)) {
2971 ConvertedType = ToType;
2972 return true;
2973 }
2974
2975 // Otherwise, both types have to be member pointers.
2976 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2977 if (!FromTypePtr)
2978 return false;
2979
2980 // A pointer to member of B can be converted to a pointer to member of D,
2981 // where D is derived from B (C++ 4.11p2).
2982 QualType FromClass(FromTypePtr->getClass(), 0);
2983 QualType ToClass(ToTypePtr->getClass(), 0);
2984
2985 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2986 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2987 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2988 ToClass.getTypePtr());
2989 return true;
2990 }
2991
2992 return false;
2993}
2994
2995/// CheckMemberPointerConversion - Check the member pointer conversion from the
2996/// expression From to the type ToType. This routine checks for ambiguous or
2997/// virtual or inaccessible base-to-derived member pointer conversions
2998/// for which IsMemberPointerConversion has already returned true. It returns
2999/// true and produces a diagnostic if there was an error, or returns false
3000/// otherwise.
3001bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3002 CastKind &Kind,
3003 CXXCastPath &BasePath,
3004 bool IgnoreBaseAccess) {
3005 QualType FromType = From->getType();
3006 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3007 if (!FromPtrType) {
3008 // This must be a null pointer to member pointer conversion
3009 assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
3010 Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
3011 "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
;
3012 Kind = CK_NullToMemberPointer;
3013 return false;
3014 }
3015
3016 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3017 assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
3018 "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
;
3019
3020 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3021 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3022
3023 // FIXME: What about dependent types?
3024 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3024, __extension__ __PRETTY_FUNCTION__))
;
3025 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
;
3026
3027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3028 /*DetectVirtual=*/true);
3029 bool DerivationOkay =
3030 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3031 assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3032, __extension__ __PRETTY_FUNCTION__))
3032 "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3032, __extension__ __PRETTY_FUNCTION__))
;
3033 (void)DerivationOkay;
3034
3035 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3036 getUnqualifiedType())) {
3037 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3038 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3039 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3040 return true;
3041 }
3042
3043 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3044 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3045 << FromClass << ToClass << QualType(VBase, 0)
3046 << From->getSourceRange();
3047 return true;
3048 }
3049
3050 if (!IgnoreBaseAccess)
3051 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3052 Paths.front(),
3053 diag::err_downcast_from_inaccessible_base);
3054
3055 // Must be a base to derived member conversion.
3056 BuildBasePathArray(Paths, BasePath);
3057 Kind = CK_BaseToDerivedMemberPointer;
3058 return false;
3059}
3060
3061/// Determine whether the lifetime conversion between the two given
3062/// qualifiers sets is nontrivial.
3063static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3064 Qualifiers ToQuals) {
3065 // Converting anything to const __unsafe_unretained is trivial.
3066 if (ToQuals.hasConst() &&
3067 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3068 return false;
3069
3070 return true;
3071}
3072
3073/// IsQualificationConversion - Determines whether the conversion from
3074/// an rvalue of type FromType to ToType is a qualification conversion
3075/// (C++ 4.4).
3076///
3077/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3078/// when the qualification conversion involves a change in the Objective-C
3079/// object lifetime.
3080bool
3081Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3082 bool CStyle, bool &ObjCLifetimeConversion) {
3083 FromType = Context.getCanonicalType(FromType);
3084 ToType = Context.getCanonicalType(ToType);
3085 ObjCLifetimeConversion = false;
3086
3087 // If FromType and ToType are the same type, this is not a
3088 // qualification conversion.
3089 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3090 return false;
3091
3092 // (C++ 4.4p4):
3093 // A conversion can add cv-qualifiers at levels other than the first
3094 // in multi-level pointers, subject to the following rules: [...]
3095 bool PreviousToQualsIncludeConst = true;
3096 bool UnwrappedAnyPointer = false;
3097 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3098 // Within each iteration of the loop, we check the qualifiers to
3099 // determine if this still looks like a qualification
3100 // conversion. Then, if all is well, we unwrap one more level of
3101 // pointers or pointers-to-members and do it all again
3102 // until there are no more pointers or pointers-to-members left to
3103 // unwrap.
3104 UnwrappedAnyPointer = true;
3105
3106 Qualifiers FromQuals = FromType.getQualifiers();
3107 Qualifiers ToQuals = ToType.getQualifiers();
3108
3109 // Ignore __unaligned qualifier if this type is void.
3110 if (ToType.getUnqualifiedType()->isVoidType())
3111 FromQuals.removeUnaligned();
3112
3113 // Objective-C ARC:
3114 // Check Objective-C lifetime conversions.
3115 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3116 UnwrappedAnyPointer) {
3117 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3118 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3119 ObjCLifetimeConversion = true;
3120 FromQuals.removeObjCLifetime();
3121 ToQuals.removeObjCLifetime();
3122 } else {
3123 // Qualification conversions cannot cast between different
3124 // Objective-C lifetime qualifiers.
3125 return false;
3126 }
3127 }
3128
3129 // Allow addition/removal of GC attributes but not changing GC attributes.
3130 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3131 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3132 FromQuals.removeObjCGCAttr();
3133 ToQuals.removeObjCGCAttr();
3134 }
3135
3136 // -- for every j > 0, if const is in cv 1,j then const is in cv
3137 // 2,j, and similarly for volatile.
3138 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3139 return false;
3140
3141 // -- if the cv 1,j and cv 2,j are different, then const is in
3142 // every cv for 0 < k < j.
3143 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3144 && !PreviousToQualsIncludeConst)
3145 return false;
3146
3147 // Keep track of whether all prior cv-qualifiers in the "to" type
3148 // include const.
3149 PreviousToQualsIncludeConst
3150 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3151 }
3152
3153 // Allows address space promotion by language rules implemented in
3154 // Type::Qualifiers::isAddressSpaceSupersetOf.
3155 Qualifiers FromQuals = FromType.getQualifiers();
3156 Qualifiers ToQuals = ToType.getQualifiers();
3157 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3158 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3159 return false;
3160 }
3161
3162 // We are left with FromType and ToType being the pointee types
3163 // after unwrapping the original FromType and ToType the same number
3164 // of types. If we unwrapped any pointers, and if FromType and
3165 // ToType have the same unqualified type (since we checked
3166 // qualifiers above), then this is a qualification conversion.
3167 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3168}
3169
3170/// - Determine whether this is a conversion from a scalar type to an
3171/// atomic type.
3172///
3173/// If successful, updates \c SCS's second and third steps in the conversion
3174/// sequence to finish the conversion.
3175static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3176 bool InOverloadResolution,
3177 StandardConversionSequence &SCS,
3178 bool CStyle) {
3179 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3180 if (!ToAtomic)
3181 return false;
3182
3183 StandardConversionSequence InnerSCS;
3184 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3185 InOverloadResolution, InnerSCS,
3186 CStyle, /*AllowObjCWritebackConversion=*/false))
3187 return false;
3188
3189 SCS.Second = InnerSCS.Second;
3190 SCS.setToType(1, InnerSCS.getToType(1));
3191 SCS.Third = InnerSCS.Third;
3192 SCS.QualificationIncludesObjCLifetime
3193 = InnerSCS.QualificationIncludesObjCLifetime;
3194 SCS.setToType(2, InnerSCS.getToType(2));
3195 return true;
3196}
3197
3198static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3199 CXXConstructorDecl *Constructor,
3200 QualType Type) {
3201 const FunctionProtoType *CtorType =
3202 Constructor->getType()->getAs<FunctionProtoType>();
3203 if (CtorType->getNumParams() > 0) {
3204 QualType FirstArg = CtorType->getParamType(0);
3205 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3206 return true;
3207 }
3208 return false;
3209}
3210
3211static OverloadingResult
3212IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3213 CXXRecordDecl *To,
3214 UserDefinedConversionSequence &User,
3215 OverloadCandidateSet &CandidateSet,
3216 bool AllowExplicit) {
3217 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3218 for (auto *D : S.LookupConstructors(To)) {
3219 auto Info = getConstructorInfo(D);
3220 if (!Info)
3221 continue;
3222
3223 bool Usable = !Info.Constructor->isInvalidDecl() &&
3224 S.isInitListConstructor(Info.Constructor) &&
3225 (AllowExplicit || !Info.Constructor->isExplicit());
3226 if (Usable) {
3227 // If the first argument is (a reference to) the target type,
3228 // suppress conversions.
3229 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3230 S.Context, Info.Constructor, ToType);
3231 if (Info.ConstructorTmpl)
3232 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3233 /*ExplicitArgs*/ nullptr, From,
3234 CandidateSet, SuppressUserConversions);
3235 else
3236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3237 CandidateSet, SuppressUserConversions);
3238 }
3239 }
3240
3241 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3242
3243 OverloadCandidateSet::iterator Best;
3244 switch (auto Result =
3245 CandidateSet.BestViableFunction(S, From->getLocStart(),
3246 Best)) {
3247 case OR_Deleted:
3248 case OR_Success: {
3249 // Record the standard conversion we used and the conversion function.
3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3251 QualType ThisType = Constructor->getThisType(S.Context);
3252 // Initializer lists don't have conversions as such.
3253 User.Before.setAsIdentityConversion();
3254 User.HadMultipleCandidates = HadMultipleCandidates;
3255 User.ConversionFunction = Constructor;
3256 User.FoundConversionFunction = Best->FoundDecl;
3257 User.After.setAsIdentityConversion();
3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259 User.After.setAllToTypes(ToType);
3260 return Result;
3261 }
3262
3263 case OR_No_Viable_Function:
3264 return OR_No_Viable_Function;
3265 case OR_Ambiguous:
3266 return OR_Ambiguous;
3267 }
3268
3269 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3269)
;
3270}
3271
3272/// Determines whether there is a user-defined conversion sequence
3273/// (C++ [over.ics.user]) that converts expression From to the type
3274/// ToType. If such a conversion exists, User will contain the
3275/// user-defined conversion sequence that performs such a conversion
3276/// and this routine will return true. Otherwise, this routine returns
3277/// false and User is unspecified.
3278///
3279/// \param AllowExplicit true if the conversion should consider C++0x
3280/// "explicit" conversion functions as well as non-explicit conversion
3281/// functions (C++0x [class.conv.fct]p2).
3282///
3283/// \param AllowObjCConversionOnExplicit true if the conversion should
3284/// allow an extra Objective-C pointer conversion on uses of explicit
3285/// constructors. Requires \c AllowExplicit to also be set.
3286static OverloadingResult
3287IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3288 UserDefinedConversionSequence &User,
3289 OverloadCandidateSet &CandidateSet,
3290 bool AllowExplicit,
3291 bool AllowObjCConversionOnExplicit) {
3292 assert(AllowExplicit || !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit || !AllowObjCConversionOnExplicit
) ? void (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3292, __extension__ __PRETTY_FUNCTION__))
;
3293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3294
3295 // Whether we will only visit constructors.
3296 bool ConstructorsOnly = false;
3297
3298 // If the type we are conversion to is a class type, enumerate its
3299 // constructors.
3300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3301 // C++ [over.match.ctor]p1:
3302 // When objects of class type are direct-initialized (8.5), or
3303 // copy-initialized from an expression of the same or a
3304 // derived class type (8.5), overload resolution selects the
3305 // constructor. [...] For copy-initialization, the candidate
3306 // functions are all the converting constructors (12.3.1) of
3307 // that class. The argument list is the expression-list within
3308 // the parentheses of the initializer.
3309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3310 (From->getType()->getAs<RecordType>() &&
3311 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3312 ConstructorsOnly = true;
3313
3314 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3315 // We're not going to find any constructors.
3316 } else if (CXXRecordDecl *ToRecordDecl
3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3318
3319 Expr **Args = &From;
3320 unsigned NumArgs = 1;
3321 bool ListInitializing = false;
3322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3323 // But first, see if there is an init-list-constructor that will work.
3324 OverloadingResult Result = IsInitializerListConstructorConversion(
3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326 if (Result != OR_No_Viable_Function)
3327 return Result;
3328 // Never mind.
3329 CandidateSet.clear(
3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3331
3332 // If we're list-initializing, we pass the individual elements as
3333 // arguments, not the entire list.
3334 Args = InitList->getInits();
3335 NumArgs = InitList->getNumInits();
3336 ListInitializing = true;
3337 }
3338
3339 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340 auto Info = getConstructorInfo(D);
3341 if (!Info)
3342 continue;
3343
3344 bool Usable = !Info.Constructor->isInvalidDecl();
3345 if (ListInitializing)
3346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3347 else
3348 Usable = Usable &&
3349 Info.Constructor->isConvertingConstructor(AllowExplicit);
3350 if (Usable) {
3351 bool SuppressUserConversions = !ConstructorsOnly;
3352 if (SuppressUserConversions && ListInitializing) {
3353 SuppressUserConversions = false;
3354 if (NumArgs == 1) {
3355 // If the first argument is (a reference to) the target type,
3356 // suppress conversions.
3357 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3358 S.Context, Info.Constructor, ToType);
3359 }
3360 }
3361 if (Info.ConstructorTmpl)
3362 S.AddTemplateOverloadCandidate(
3363 Info.ConstructorTmpl, Info.FoundDecl,
3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365 CandidateSet, SuppressUserConversions);
3366 else
3367 // Allow one user-defined conversion when user specifies a
3368 // From->ToType conversion via an static cast (c-style, etc).
3369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3370 llvm::makeArrayRef(Args, NumArgs),
3371 CandidateSet, SuppressUserConversions);
3372 }
3373 }
3374 }
3375 }
3376
3377 // Enumerate conversion functions, if we're allowed to.
3378 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3379 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3380 // No conversion functions from incomplete types.
3381 } else if (const RecordType *FromRecordType
3382 = From->getType()->getAs<RecordType>()) {
3383 if (CXXRecordDecl *FromRecordDecl
3384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385 // Add all of the conversion functions as candidates.
3386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3388 DeclAccessPair FoundDecl = I.getPair();
3389 NamedDecl *D = FoundDecl.getDecl();
3390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391 if (isa<UsingShadowDecl>(D))
3392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393
3394 CXXConversionDecl *Conv;
3395 FunctionTemplateDecl *ConvTemplate;
3396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3398 else
3399 Conv = cast<CXXConversionDecl>(D);
3400
3401 if (AllowExplicit || !Conv->isExplicit()) {
3402 if (ConvTemplate)
3403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404 ActingContext, From, ToType,
3405 CandidateSet,
3406 AllowObjCConversionOnExplicit);
3407 else
3408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3409 From, ToType, CandidateSet,
3410 AllowObjCConversionOnExplicit);
3411 }
3412 }
3413 }
3414 }
3415
3416 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417
3418 OverloadCandidateSet::iterator Best;
3419 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3420 Best)) {
3421 case OR_Success:
3422 case OR_Deleted:
3423 // Record the standard conversion we used and the conversion function.
3424 if (CXXConstructorDecl *Constructor
3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426 // C++ [over.ics.user]p1:
3427 // If the user-defined conversion is specified by a
3428 // constructor (12.3.1), the initial standard conversion
3429 // sequence converts the source type to the type required by
3430 // the argument of the constructor.
3431 //
3432 QualType ThisType = Constructor->getThisType(S.Context);
3433 if (isa<InitListExpr>(From)) {
3434 // Initializer lists don't have conversions as such.
3435 User.Before.setAsIdentityConversion();
3436 } else {
3437 if (Best->Conversions[0].isEllipsis())
3438 User.EllipsisConversion = true;
3439 else {
3440 User.Before = Best->Conversions[0].Standard;
3441 User.EllipsisConversion = false;
3442 }
3443 }
3444 User.HadMultipleCandidates = HadMultipleCandidates;
3445 User.ConversionFunction = Constructor;
3446 User.FoundConversionFunction = Best->FoundDecl;
3447 User.After.setAsIdentityConversion();
3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449 User.After.setAllToTypes(ToType);
3450 return Result;
3451 }
3452 if (CXXConversionDecl *Conversion
3453 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454 // C++ [over.ics.user]p1:
3455 //
3456 // [...] If the user-defined conversion is specified by a
3457 // conversion function (12.3.2), the initial standard
3458 // conversion sequence converts the source type to the
3459 // implicit object parameter of the conversion function.
3460 User.Before = Best->Conversions[0].Standard;
3461 User.HadMultipleCandidates = HadMultipleCandidates;
3462 User.ConversionFunction = Conversion;
3463 User.FoundConversionFunction = Best->FoundDecl;
3464 User.EllipsisConversion = false;
3465
3466 // C++ [over.ics.user]p2:
3467 // The second standard conversion sequence converts the
3468 // result of the user-defined conversion to the target type
3469 // for the sequence. Since an implicit conversion sequence
3470 // is an initialization, the special rules for
3471 // initialization by user-defined conversion apply when
3472 // selecting the best user-defined conversion for a
3473 // user-defined conversion sequence (see 13.3.3 and
3474 // 13.3.3.1).
3475 User.After = Best->FinalConversion;
3476 return Result;
3477 }
3478 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3478)
;
3479
3480 case OR_No_Viable_Function:
3481 return OR_No_Viable_Function;
3482
3483 case OR_Ambiguous:
3484 return OR_Ambiguous;
3485 }
3486
3487 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3487)
;
3488}
3489
3490bool
3491Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3492 ImplicitConversionSequence ICS;
3493 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494 OverloadCandidateSet::CSK_Normal);
3495 OverloadingResult OvResult =
3496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3497 CandidateSet, false, false);
3498 if (OvResult == OR_Ambiguous)
3499 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3500 << From->getType() << ToType << From->getSourceRange();
3501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3502 if (!RequireCompleteType(From->getLocStart(), ToType,
3503 diag::err_typecheck_nonviable_condition_incomplete,
3504 From->getType(), From->getSourceRange()))
3505 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3506 << false << From->getType() << From->getSourceRange() << ToType;
3507 } else
3508 return false;
3509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3510 return true;
3511}
3512
3513/// Compare the user-defined conversion functions or constructors
3514/// of two user-defined conversion sequences to determine whether any ordering
3515/// is possible.
3516static ImplicitConversionSequence::CompareKind
3517compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3518 FunctionDecl *Function2) {
3519 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3520 return ImplicitConversionSequence::Indistinguishable;
3521
3522 // Objective-C++:
3523 // If both conversion functions are implicitly-declared conversions from
3524 // a lambda closure type to a function pointer and a block pointer,
3525 // respectively, always prefer the conversion to a function pointer,
3526 // because the function pointer is more lightweight and is more likely
3527 // to keep code working.
3528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3529 if (!Conv1)
3530 return ImplicitConversionSequence::Indistinguishable;
3531
3532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533 if (!Conv2)
3534 return ImplicitConversionSequence::Indistinguishable;
3535
3536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539 if (Block1 != Block2)
3540 return Block1 ? ImplicitConversionSequence::Worse
3541 : ImplicitConversionSequence::Better;
3542 }
3543
3544 return ImplicitConversionSequence::Indistinguishable;
3545}
3546
3547static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548 const ImplicitConversionSequence &ICS) {
3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550 (ICS.isUserDefined() &&
3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552}
3553
3554/// CompareImplicitConversionSequences - Compare two implicit
3555/// conversion sequences to determine whether one is better than the
3556/// other or if they are indistinguishable (C++ 13.3.3.2).
3557static ImplicitConversionSequence::CompareKind
3558CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3559 const ImplicitConversionSequence& ICS1,
3560 const ImplicitConversionSequence& ICS2)
3561{
3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563 // conversion sequences (as defined in 13.3.3.1)
3564 // -- a standard conversion sequence (13.3.3.1.1) is a better
3565 // conversion sequence than a user-defined conversion sequence or
3566 // an ellipsis conversion sequence, and
3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568 // conversion sequence than an ellipsis conversion sequence
3569 // (13.3.3.1.3).
3570 //
3571 // C++0x [over.best.ics]p10:
3572 // For the purpose of ranking implicit conversion sequences as
3573 // described in 13.3.3.2, the ambiguous conversion sequence is
3574 // treated as a user-defined sequence that is indistinguishable
3575 // from any other user-defined conversion sequence.
3576
3577 // String literal to 'char *' conversion has been deprecated in C++03. It has
3578 // been removed from C++11. We still accept this conversion, if it happens at
3579 // the best viable function. Otherwise, this conversion is considered worse
3580 // than ellipsis conversion. Consider this as an extension; this is not in the
3581 // standard. For example:
3582 //
3583 // int &f(...); // #1
3584 // void f(char*); // #2
3585 // void g() { int &r = f("foo"); }
3586 //
3587 // In C++03, we pick #2 as the best viable function.
3588 // In C++11, we pick #1 as the best viable function, because ellipsis
3589 // conversion is better than string-literal to char* conversion (since there
3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591 // convert arguments, #2 would be the best viable function in C++11.
3592 // If the best viable function has this conversion, a warning will be issued
3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594
3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599 ? ImplicitConversionSequence::Worse
3600 : ImplicitConversionSequence::Better;
3601
3602 if (ICS1.getKindRank() < ICS2.getKindRank())
3603 return ImplicitConversionSequence::Better;
3604 if (ICS2.getKindRank() < ICS1.getKindRank())
3605 return ImplicitConversionSequence::Worse;
3606
3607 // The following checks require both conversion sequences to be of
3608 // the same kind.
3609 if (ICS1.getKind() != ICS2.getKind())
3610 return ImplicitConversionSequence::Indistinguishable;
3611
3612 ImplicitConversionSequence::CompareKind Result =
3613 ImplicitConversionSequence::Indistinguishable;
3614
3615 // Two implicit conversion sequences of the same form are
3616 // indistinguishable conversion sequences unless one of the
3617 // following rules apply: (C++ 13.3.3.2p3):
3618
3619 // List-initialization sequence L1 is a better conversion sequence than
3620 // list-initialization sequence L2 if:
3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622 // if not that,
3623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3624 // and N1 is smaller than N2.,
3625 // even if one of the other rules in this paragraph would otherwise apply.
3626 if (!ICS1.isBad()) {
3627 if (ICS1.isStdInitializerListElement() &&
3628 !ICS2.isStdInitializerListElement())
3629 return ImplicitConversionSequence::Better;
3630 if (!ICS1.isStdInitializerListElement() &&
3631 ICS2.isStdInitializerListElement())
3632 return ImplicitConversionSequence::Worse;
3633 }
3634
3635 if (ICS1.isStandard())
3636 // Standard conversion sequence S1 is a better conversion sequence than
3637 // standard conversion sequence S2 if [...]
3638 Result = CompareStandardConversionSequences(S, Loc,
3639 ICS1.Standard, ICS2.Standard);
3640 else if (ICS1.isUserDefined()) {
3641 // User-defined conversion sequence U1 is a better conversion
3642 // sequence than another user-defined conversion sequence U2 if
3643 // they contain the same user-defined conversion function or
3644 // constructor and if the second standard conversion sequence of
3645 // U1 is better than the second standard conversion sequence of
3646 // U2 (C++ 13.3.3.2p3).
3647 if (ICS1.UserDefined.ConversionFunction ==
3648 ICS2.UserDefined.ConversionFunction)
3649 Result = CompareStandardConversionSequences(S, Loc,
3650 ICS1.UserDefined.After,
3651 ICS2.UserDefined.After);
3652 else
3653 Result = compareConversionFunctions(S,
3654 ICS1.UserDefined.ConversionFunction,
3655 ICS2.UserDefined.ConversionFunction);
3656 }
3657
3658 return Result;
3659}
3660
3661// Per 13.3.3.2p3, compare the given standard conversion sequences to
3662// determine if one is a proper subset of the other.
3663static ImplicitConversionSequence::CompareKind
3664compareStandardConversionSubsets(ASTContext &Context,
3665 const StandardConversionSequence& SCS1,
3666 const StandardConversionSequence& SCS2) {
3667 ImplicitConversionSequence::CompareKind Result
3668 = ImplicitConversionSequence::Indistinguishable;
3669
3670 // the identity conversion sequence is considered to be a subsequence of
3671 // any non-identity conversion sequence
3672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673 return ImplicitConversionSequence::Better;
3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675 return ImplicitConversionSequence::Worse;
3676
3677 if (SCS1.Second != SCS2.Second) {
3678 if (SCS1.Second == ICK_Identity)
3679 Result = ImplicitConversionSequence::Better;
3680 else if (SCS2.Second == ICK_Identity)
3681 Result = ImplicitConversionSequence::Worse;
3682 else
3683 return ImplicitConversionSequence::Indistinguishable;
3684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3685 return ImplicitConversionSequence::Indistinguishable;
3686
3687 if (SCS1.Third == SCS2.Third) {
3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689 : ImplicitConversionSequence::Indistinguishable;
3690 }
3691
3692 if (SCS1.Third == ICK_Identity)
3693 return Result == ImplicitConversionSequence::Worse
3694 ? ImplicitConversionSequence::Indistinguishable
3695 : ImplicitConversionSequence::Better;
3696
3697 if (SCS2.Third == ICK_Identity)
3698 return Result == ImplicitConversionSequence::Better
3699 ? ImplicitConversionSequence::Indistinguishable
3700 : ImplicitConversionSequence::Worse;
3701
3702 return ImplicitConversionSequence::Indistinguishable;
3703}
3704
3705/// Determine whether one of the given reference bindings is better
3706/// than the other based on what kind of bindings they are.
3707static bool
3708isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709 const StandardConversionSequence &SCS2) {
3710 // C++0x [over.ics.rank]p3b4:
3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712 // implicit object parameter of a non-static member function declared
3713 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3715 // lvalue reference to a function lvalue and S2 binds an rvalue
3716 // reference*.
3717 //
3718 // FIXME: Rvalue references. We're going rogue with the above edits,
3719 // because the semantics in the current C++0x working paper (N3225 at the
3720 // time of this writing) break the standard definition of std::forward
3721 // and std::reference_wrapper when dealing with references to functions.
3722 // Proposed wording changes submitted to CWG for consideration.
3723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725 return false;
3726
3727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728 SCS2.IsLvalueReference) ||
3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3731}
3732
3733/// CompareStandardConversionSequences - Compare two standard
3734/// conversion sequences to determine whether one is better than the
3735/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3736static ImplicitConversionSequence::CompareKind
3737CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3738 const StandardConversionSequence& SCS1,
3739 const StandardConversionSequence& SCS2)
3740{
3741 // Standard conversion sequence S1 is a better conversion sequence
3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743
3744 // -- S1 is a proper subsequence of S2 (comparing the conversion
3745 // sequences in the canonical form defined by 13.3.3.1.1,
3746 // excluding any Lvalue Transformation; the identity conversion
3747 // sequence is considered to be a subsequence of any
3748 // non-identity conversion sequence) or, if not that,
3749 if (ImplicitConversionSequence::CompareKind CK
3750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3751 return CK;
3752
3753 // -- the rank of S1 is better than the rank of S2 (by the rules
3754 // defined below), or, if not that,
3755 ImplicitConversionRank Rank1 = SCS1.getRank();
3756 ImplicitConversionRank Rank2 = SCS2.getRank();
3757 if (Rank1 < Rank2)
3758 return ImplicitConversionSequence::Better;
3759 else if (Rank2 < Rank1)
3760 return ImplicitConversionSequence::Worse;
3761
3762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763 // are indistinguishable unless one of the following rules
3764 // applies:
3765
3766 // A conversion that is not a conversion of a pointer, or
3767 // pointer to member, to bool is better than another conversion
3768 // that is such a conversion.
3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770 return SCS2.isPointerConversionToBool()
3771 ? ImplicitConversionSequence::Better
3772 : ImplicitConversionSequence::Worse;
3773
3774 // C++ [over.ics.rank]p4b2:
3775 //
3776 // If class B is derived directly or indirectly from class A,
3777 // conversion of B* to A* is better than conversion of B* to
3778 // void*, and conversion of A* to void* is better than conversion
3779 // of B* to void*.
3780 bool SCS1ConvertsToVoid
3781 = SCS1.isPointerConversionToVoidPointer(S.Context);
3782 bool SCS2ConvertsToVoid
3783 = SCS2.isPointerConversionToVoidPointer(S.Context);
3784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785 // Exactly one of the conversion sequences is a conversion to
3786 // a void pointer; it's the worse conversion.
3787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788 : ImplicitConversionSequence::Worse;
3789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790 // Neither conversion sequence converts to a void pointer; compare
3791 // their derived-to-base conversions.
3792 if (ImplicitConversionSequence::CompareKind DerivedCK
3793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3794 return DerivedCK;
3795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3797 // Both conversion sequences are conversions to void
3798 // pointers. Compare the source types to determine if there's an
3799 // inheritance relationship in their sources.
3800 QualType FromType1 = SCS1.getFromType();
3801 QualType FromType2 = SCS2.getFromType();
3802
3803 // Adjust the types we're converting from via the array-to-pointer
3804 // conversion, if we need to.
3805 if (SCS1.First == ICK_Array_To_Pointer)
3806 FromType1 = S.Context.getArrayDecayedType(FromType1);
3807 if (SCS2.First == ICK_Array_To_Pointer)
3808 FromType2 = S.Context.getArrayDecayedType(FromType2);
3809
3810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3812
3813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3814 return ImplicitConversionSequence::Better;
3815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3816 return ImplicitConversionSequence::Worse;
3817
3818 // Objective-C++: If one interface is more specific than the
3819 // other, it is the better one.
3820 const ObjCObjectPointerType* FromObjCPtr1
3821 = FromType1->getAs<ObjCObjectPointerType>();
3822 const ObjCObjectPointerType* FromObjCPtr2
3823 = FromType2->getAs<ObjCObjectPointerType>();
3824 if (FromObjCPtr1 && FromObjCPtr2) {
3825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3826 FromObjCPtr2);
3827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3828 FromObjCPtr1);
3829 if (AssignLeft != AssignRight) {
3830 return AssignLeft? ImplicitConversionSequence::Better
3831 : ImplicitConversionSequence::Worse;
3832 }
3833 }
3834 }
3835
3836 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837 // bullet 3).
3838 if (ImplicitConversionSequence::CompareKind QualCK
3839 = CompareQualificationConversions(S, SCS1, SCS2))
3840 return QualCK;
3841
3842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3843 // Check for a better reference binding based on the kind of bindings.
3844 if (isBetterReferenceBindingKind(SCS1, SCS2))
3845 return ImplicitConversionSequence::Better;
3846 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847 return ImplicitConversionSequence::Worse;
3848
3849 // C++ [over.ics.rank]p3b4:
3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3851 // which the references refer are the same type except for
3852 // top-level cv-qualifiers, and the type to which the reference
3853 // initialized by S2 refers is more cv-qualified than the type
3854 // to which the reference initialized by S1 refers.
3855 QualType T1 = SCS1.getToType(2);
3856 QualType T2 = SCS2.getToType(2);
3857 T1 = S.Context.getCanonicalType(T1);
3858 T2 = S.Context.getCanonicalType(T2);
3859 Qualifiers T1Quals, T2Quals;
3860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3862 if (UnqualT1 == UnqualT2) {
3863 // Objective-C++ ARC: If the references refer to objects with different
3864 // lifetimes, prefer bindings that don't change lifetime.
3865 if (SCS1.ObjCLifetimeConversionBinding !=
3866 SCS2.ObjCLifetimeConversionBinding) {
3867 return SCS1.ObjCLifetimeConversionBinding
3868 ? ImplicitConversionSequence::Worse
3869 : ImplicitConversionSequence::Better;
3870 }
3871
3872 // If the type is an array type, promote the element qualifiers to the
3873 // type for comparison.
3874 if (isa<ArrayType>(T1) && T1Quals)
3875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3876 if (isa<ArrayType>(T2) && T2Quals)
3877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3878 if (T2.isMoreQualifiedThan(T1))
3879 return ImplicitConversionSequence::Better;
3880 else if (T1.isMoreQualifiedThan(T2))
3881 return ImplicitConversionSequence::Worse;
3882 }
3883 }
3884
3885 // In Microsoft mode, prefer an integral conversion to a
3886 // floating-to-integral conversion if the integral conversion
3887 // is between types of the same size.
3888 // For example:
3889 // void f(float);
3890 // void f(int);
3891 // int main {
3892 // long a;
3893 // f(a);
3894 // }
3895 // Here, MSVC will call f(int) instead of generating a compile error
3896 // as clang will do in standard mode.
3897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898 SCS2.Second == ICK_Floating_Integral &&
3899 S.Context.getTypeSize(SCS1.getFromType()) ==
3900 S.Context.getTypeSize(SCS1.getToType(2)))
3901 return ImplicitConversionSequence::Better;
3902
3903 return ImplicitConversionSequence::Indistinguishable;
3904}
3905
3906/// CompareQualificationConversions - Compares two standard conversion
3907/// sequences to determine whether they can be ranked based on their
3908/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3909static ImplicitConversionSequence::CompareKind
3910CompareQualificationConversions(Sema &S,
3911 const StandardConversionSequence& SCS1,
3912 const StandardConversionSequence& SCS2) {
3913 // C++ 13.3.3.2p3:
3914 // -- S1 and S2 differ only in their qualification conversion and
3915 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3916 // cv-qualification signature of type T1 is a proper subset of
3917 // the cv-qualification signature of type T2, and S1 is not the
3918 // deprecated string literal array-to-pointer conversion (4.2).
3919 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3920 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3921 return ImplicitConversionSequence::Indistinguishable;
3922
3923 // FIXME: the example in the standard doesn't use a qualification
3924 // conversion (!)
3925 QualType T1 = SCS1.getToType(2);
3926 QualType T2 = SCS2.getToType(2);
3927 T1 = S.Context.getCanonicalType(T1);
3928 T2 = S.Context.getCanonicalType(T2);
3929 Qualifiers T1Quals, T2Quals;
3930 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3931 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3932
3933 // If the types are the same, we won't learn anything by unwrapped
3934 // them.
3935 if (UnqualT1 == UnqualT2)
3936 return ImplicitConversionSequence::Indistinguishable;
3937
3938 // If the type is an array type, promote the element qualifiers to the type
3939 // for comparison.
3940 if (isa<ArrayType>(T1) && T1Quals)
3941 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3942 if (isa<ArrayType>(T2) && T2Quals)
3943 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3944
3945 ImplicitConversionSequence::CompareKind Result
3946 = ImplicitConversionSequence::Indistinguishable;
3947
3948 // Objective-C++ ARC:
3949 // Prefer qualification conversions not involving a change in lifetime
3950 // to qualification conversions that do not change lifetime.
3951 if (SCS1.QualificationIncludesObjCLifetime !=
3952 SCS2.QualificationIncludesObjCLifetime) {
3953 Result = SCS1.QualificationIncludesObjCLifetime
3954 ? ImplicitConversionSequence::Worse
3955 : ImplicitConversionSequence::Better;
3956 }
3957
3958 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3959 // Within each iteration of the loop, we check the qualifiers to
3960 // determine if this still looks like a qualification
3961 // conversion. Then, if all is well, we unwrap one more level of
3962 // pointers or pointers-to-members and do it all again
3963 // until there are no more pointers or pointers-to-members left
3964 // to unwrap. This essentially mimics what
3965 // IsQualificationConversion does, but here we're checking for a
3966 // strict subset of qualifiers.
3967 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3968 // The qualifiers are the same, so this doesn't tell us anything
3969 // about how the sequences rank.
3970 ;
3971 else if (T2.isMoreQualifiedThan(T1)) {
3972 // T1 has fewer qualifiers, so it could be the better sequence.
3973 if (Result == ImplicitConversionSequence::Worse)
3974 // Neither has qualifiers that are a subset of the other's
3975 // qualifiers.
3976 return ImplicitConversionSequence::Indistinguishable;
3977
3978 Result = ImplicitConversionSequence::Better;
3979 } else if (T1.isMoreQualifiedThan(T2)) {
3980 // T2 has fewer qualifiers, so it could be the better sequence.
3981 if (Result == ImplicitConversionSequence::Better)
3982 // Neither has qualifiers that are a subset of the other's
3983 // qualifiers.
3984 return ImplicitConversionSequence::Indistinguishable;
3985
3986 Result = ImplicitConversionSequence::Worse;
3987 } else {
3988 // Qualifiers are disjoint.
3989 return ImplicitConversionSequence::Indistinguishable;
3990 }
3991
3992 // If the types after this point are equivalent, we're done.
3993 if (S.Context.hasSameUnqualifiedType(T1, T2))
3994 break;
3995 }
3996
3997 // Check that the winning standard conversion sequence isn't using
3998 // the deprecated string literal array to pointer conversion.
3999 switch (Result) {
4000 case ImplicitConversionSequence::Better:
4001 if (SCS1.DeprecatedStringLiteralToCharPtr)
4002 Result = ImplicitConversionSequence::Indistinguishable;
4003 break;
4004
4005 case ImplicitConversionSequence::Indistinguishable:
4006 break;
4007
4008 case ImplicitConversionSequence::Worse:
4009 if (SCS2.DeprecatedStringLiteralToCharPtr)
4010 Result = ImplicitConversionSequence::Indistinguishable;
4011 break;
4012 }
4013
4014 return Result;
4015}
4016
4017/// CompareDerivedToBaseConversions - Compares two standard conversion
4018/// sequences to determine whether they can be ranked based on their
4019/// various kinds of derived-to-base conversions (C++
4020/// [over.ics.rank]p4b3). As part of these checks, we also look at
4021/// conversions between Objective-C interface types.
4022static ImplicitConversionSequence::CompareKind
4023CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4024 const StandardConversionSequence& SCS1,
4025 const StandardConversionSequence& SCS2) {
4026 QualType FromType1 = SCS1.getFromType();
4027 QualType ToType1 = SCS1.getToType(1);
4028 QualType FromType2 = SCS2.getFromType();
4029 QualType ToType2 = SCS2.getToType(1);
4030
4031 // Adjust the types we're converting from via the array-to-pointer
4032 // conversion, if we need to.
4033 if (SCS1.First == ICK_Array_To_Pointer)
4034 FromType1 = S.Context.getArrayDecayedType(FromType1);
4035 if (SCS2.First == ICK_Array_To_Pointer)
4036 FromType2 = S.Context.getArrayDecayedType(FromType2);
4037
4038 // Canonicalize all of the types.
4039 FromType1 = S.Context.getCanonicalType(FromType1);
4040 ToType1 = S.Context.getCanonicalType(ToType1);
4041 FromType2 = S.Context.getCanonicalType(FromType2);
4042 ToType2 = S.Context.getCanonicalType(ToType2);
4043
4044 // C++ [over.ics.rank]p4b3:
4045 //
4046 // If class B is derived directly or indirectly from class A and
4047 // class C is derived directly or indirectly from B,
4048 //
4049 // Compare based on pointer conversions.
4050 if (SCS1.Second == ICK_Pointer_Conversion &&
4051 SCS2.Second == ICK_Pointer_Conversion &&
4052 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4053 FromType1->isPointerType() && FromType2->isPointerType() &&
4054 ToType1->isPointerType() && ToType2->isPointerType()) {
4055 QualType FromPointee1
4056 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4057 QualType ToPointee1
4058 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4059 QualType FromPointee2
4060 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4061 QualType ToPointee2
4062 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4063
4064 // -- conversion of C* to B* is better than conversion of C* to A*,
4065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4066 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4067 return ImplicitConversionSequence::Better;
4068 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4069 return ImplicitConversionSequence::Worse;
4070 }
4071
4072 // -- conversion of B* to A* is better than conversion of C* to A*,
4073 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4074 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4075 return ImplicitConversionSequence::Better;
4076 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4077 return ImplicitConversionSequence::Worse;
4078 }
4079 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4080 SCS2.Second == ICK_Pointer_Conversion) {
4081 const ObjCObjectPointerType *FromPtr1
4082 = FromType1->getAs<ObjCObjectPointerType>();
4083 const ObjCObjectPointerType *FromPtr2
4084 = FromType2->getAs<ObjCObjectPointerType>();
4085 const ObjCObjectPointerType *ToPtr1
4086 = ToType1->getAs<ObjCObjectPointerType>();
4087 const ObjCObjectPointerType *ToPtr2
4088 = ToType2->getAs<ObjCObjectPointerType>();
4089
4090 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4091 // Apply the same conversion ranking rules for Objective-C pointer types
4092 // that we do for C++ pointers to class types. However, we employ the
4093 // Objective-C pseudo-subtyping relationship used for assignment of
4094 // Objective-C pointer types.
4095 bool FromAssignLeft
4096 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4097 bool FromAssignRight
4098 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4099 bool ToAssignLeft
4100 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4101 bool ToAssignRight
4102 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4103
4104 // A conversion to an a non-id object pointer type or qualified 'id'
4105 // type is better than a conversion to 'id'.
4106 if (ToPtr1->isObjCIdType() &&
4107 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4108 return ImplicitConversionSequence::Worse;
4109 if (ToPtr2->isObjCIdType() &&
4110 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4111 return ImplicitConversionSequence::Better;
4112
4113 // A conversion to a non-id object pointer type is better than a
4114 // conversion to a qualified 'id' type
4115 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4116 return ImplicitConversionSequence::Worse;
4117 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4118 return ImplicitConversionSequence::Better;
4119
4120 // A conversion to an a non-Class object pointer type or qualified 'Class'
4121 // type is better than a conversion to 'Class'.
4122 if (ToPtr1->isObjCClassType() &&
4123 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4124 return ImplicitConversionSequence::Worse;
4125 if (ToPtr2->isObjCClassType() &&
4126 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4127 return ImplicitConversionSequence::Better;
4128
4129 // A conversion to a non-Class object pointer type is better than a
4130 // conversion to a qualified 'Class' type.
4131 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4132 return ImplicitConversionSequence::Worse;
4133 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4134 return ImplicitConversionSequence::Better;
4135
4136 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4137 if (S.Context.hasSameType(FromType1, FromType2) &&
4138 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4139 (ToAssignLeft != ToAssignRight)) {
4140 if (FromPtr1->isSpecialized()) {
4141 // "conversion of B<A> * to B * is better than conversion of B * to
4142 // C *.
4143 bool IsFirstSame =
4144 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4145 bool IsSecondSame =
4146 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4147 if (IsFirstSame) {
4148 if (!IsSecondSame)
4149 return ImplicitConversionSequence::Better;
4150 } else if (IsSecondSame)
4151 return ImplicitConversionSequence::Worse;
4152 }
4153 return ToAssignLeft? ImplicitConversionSequence::Worse
4154 : ImplicitConversionSequence::Better;
4155 }
4156
4157 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4158 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4159 (FromAssignLeft != FromAssignRight))
4160 return FromAssignLeft? ImplicitConversionSequence::Better
4161 : ImplicitConversionSequence::Worse;
4162 }
4163 }
4164
4165 // Ranking of member-pointer types.
4166 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4167 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4168 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4169 const MemberPointerType * FromMemPointer1 =
4170 FromType1->getAs<MemberPointerType>();
4171 const MemberPointerType * ToMemPointer1 =
4172 ToType1->getAs<MemberPointerType>();
4173 const MemberPointerType * FromMemPointer2 =
4174 FromType2->getAs<MemberPointerType>();
4175 const MemberPointerType * ToMemPointer2 =
4176 ToType2->getAs<MemberPointerType>();
4177 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4178 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4179 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4180 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4181 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4182 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4183 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4184 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4185 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4186 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4187 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4188 return ImplicitConversionSequence::Worse;
4189 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4190 return ImplicitConversionSequence::Better;
4191 }
4192 // conversion of B::* to C::* is better than conversion of A::* to C::*
4193 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4194 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4195 return ImplicitConversionSequence::Better;
4196 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4197 return ImplicitConversionSequence::Worse;
4198 }
4199 }
4200
4201 if (SCS1.Second == ICK_Derived_To_Base) {
4202 // -- conversion of C to B is better than conversion of C to A,
4203 // -- binding of an expression of type C to a reference of type
4204 // B& is better than binding an expression of type C to a
4205 // reference of type A&,
4206 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4207 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4208 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4209 return ImplicitConversionSequence::Better;
4210 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4211 return ImplicitConversionSequence::Worse;
4212 }
4213
4214 // -- conversion of B to A is better than conversion of C to A.
4215 // -- binding of an expression of type B to a reference of type
4216 // A& is better than binding an expression of type C to a
4217 // reference of type A&,
4218 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4219 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4220 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4221 return ImplicitConversionSequence::Better;
4222 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4223 return ImplicitConversionSequence::Worse;
4224 }
4225 }
4226
4227 return ImplicitConversionSequence::Indistinguishable;
4228}
4229
4230/// Determine whether the given type is valid, e.g., it is not an invalid
4231/// C++ class.
4232static bool isTypeValid(QualType T) {
4233 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4234 return !Record->isInvalidDecl();
4235
4236 return true;
4237}
4238
4239/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4240/// determine whether they are reference-related,
4241/// reference-compatible, reference-compatible with added
4242/// qualification, or incompatible, for use in C++ initialization by
4243/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4244/// type, and the first type (T1) is the pointee type of the reference
4245/// type being initialized.
4246Sema::ReferenceCompareResult
4247Sema::CompareReferenceRelationship(SourceLocation Loc,
4248 QualType OrigT1, QualType OrigT2,
4249 bool &DerivedToBase,
4250 bool &ObjCConversion,
4251 bool &ObjCLifetimeConversion) {
4252 assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4253, __extension__ __PRETTY_FUNCTION__))
4253 "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4253, __extension__ __PRETTY_FUNCTION__))
;
4254 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() &&
"T2 cannot be a reference type") ? void (0) : __assert_fail (
"!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4254, __extension__ __PRETTY_FUNCTION__))
;
4255
4256 QualType T1 = Context.getCanonicalType(OrigT1);
4257 QualType T2 = Context.getCanonicalType(OrigT2);
4258 Qualifiers T1Quals, T2Quals;
4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4261
4262 // C++ [dcl.init.ref]p4:
4263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4264 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4265 // T1 is a base class of T2.
4266 DerivedToBase = false;
4267 ObjCConversion = false;
4268 ObjCLifetimeConversion = false;
4269 QualType ConvertedT2;
4270 if (UnqualT1 == UnqualT2) {
4271 // Nothing to do.
4272 } else if (isCompleteType(Loc, OrigT2) &&
4273 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4274 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4275 DerivedToBase = true;
4276 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4277 UnqualT2->isObjCObjectOrInterfaceType() &&
4278 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4279 ObjCConversion = true;
4280 else if (UnqualT2->isFunctionType() &&
4281 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4282 // C++1z [dcl.init.ref]p4:
4283 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4284 // function" and T1 is "function"
4285 //
4286 // We extend this to also apply to 'noreturn', so allow any function
4287 // conversion between function types.
4288 return Ref_Compatible;
4289 else
4290 return Ref_Incompatible;
4291
4292 // At this point, we know that T1 and T2 are reference-related (at
4293 // least).
4294
4295 // If the type is an array type, promote the element qualifiers to the type
4296 // for comparison.
4297 if (isa<ArrayType>(T1) && T1Quals)
4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4299 if (isa<ArrayType>(T2) && T2Quals)
4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4301
4302 // C++ [dcl.init.ref]p4:
4303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4304 // reference-related to T2 and cv1 is the same cv-qualification
4305 // as, or greater cv-qualification than, cv2. For purposes of
4306 // overload resolution, cases for which cv1 is greater
4307 // cv-qualification than cv2 are identified as
4308 // reference-compatible with added qualification (see 13.3.3.2).
4309 //
4310 // Note that we also require equivalence of Objective-C GC and address-space
4311 // qualifiers when performing these computations, so that e.g., an int in
4312 // address space 1 is not reference-compatible with an int in address
4313 // space 2.
4314 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4315 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4316 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4317 ObjCLifetimeConversion = true;
4318
4319 T1Quals.removeObjCLifetime();
4320 T2Quals.removeObjCLifetime();
4321 }
4322
4323 // MS compiler ignores __unaligned qualifier for references; do the same.
4324 T1Quals.removeUnaligned();
4325 T2Quals.removeUnaligned();
4326
4327 if (T1Quals.compatiblyIncludes(T2Quals))
4328 return Ref_Compatible;
4329 else
4330 return Ref_Related;
4331}
4332
4333/// Look for a user-defined conversion to a value reference-compatible
4334/// with DeclType. Return true if something definite is found.
4335static bool
4336FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4337 QualType DeclType, SourceLocation DeclLoc,
4338 Expr *Init, QualType T2, bool AllowRvalues,
4339 bool AllowExplicit) {
4340 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types."
) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4340, __extension__ __PRETTY_FUNCTION__))
;
4341 CXXRecordDecl *T2RecordDecl
4342 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4343
4344 OverloadCandidateSet CandidateSet(
4345 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4348 NamedDecl *D = *I;
4349 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4350 if (isa<UsingShadowDecl>(D))
4351 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4352
4353 FunctionTemplateDecl *ConvTemplate
4354 = dyn_cast<FunctionTemplateDecl>(D);
4355 CXXConversionDecl *Conv;
4356 if (ConvTemplate)
4357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4358 else
4359 Conv = cast<CXXConversionDecl>(D);
4360
4361 // If this is an explicit conversion, and we're not allowed to consider
4362 // explicit conversions, skip it.
4363 if (!AllowExplicit && Conv->isExplicit())
4364 continue;
4365
4366 if (AllowRvalues) {
4367 bool DerivedToBase = false;
4368 bool ObjCConversion = false;
4369 bool ObjCLifetimeConversion = false;
4370
4371 // If we are initializing an rvalue reference, don't permit conversion
4372 // functions that return lvalues.
4373 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4374 const ReferenceType *RefType
4375 = Conv->getConversionType()->getAs<LValueReferenceType>();
4376 if (RefType && !RefType->getPointeeType()->isFunctionType())
4377 continue;
4378 }
4379
4380 if (!ConvTemplate &&
4381 S.CompareReferenceRelationship(
4382 DeclLoc,
4383 Conv->getConversionType().getNonReferenceType()
4384 .getUnqualifiedType(),
4385 DeclType.getNonReferenceType().getUnqualifiedType(),
4386 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4387 Sema::Ref_Incompatible)
4388 continue;
4389 } else {
4390 // If the conversion function doesn't return a reference type,
4391 // it can't be considered for this conversion. An rvalue reference
4392 // is only acceptable if its referencee is a function type.
4393
4394 const ReferenceType *RefType =
4395 Conv->getConversionType()->getAs<ReferenceType>();
4396 if (!RefType ||
4397 (!RefType->isLValueReferenceType() &&
4398 !RefType->getPointeeType()->isFunctionType()))
4399 continue;
4400 }
4401
4402 if (ConvTemplate)
4403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4404 Init, DeclType, CandidateSet,
4405 /*AllowObjCConversionOnExplicit=*/false);
4406 else
4407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4408 DeclType, CandidateSet,
4409 /*AllowObjCConversionOnExplicit=*/false);
4410 }
4411
4412 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4413
4414 OverloadCandidateSet::iterator Best;
4415 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4416 case OR_Success:
4417 // C++ [over.ics.ref]p1:
4418 //
4419 // [...] If the parameter binds directly to the result of
4420 // applying a conversion function to the argument
4421 // expression, the implicit conversion sequence is a
4422 // user-defined conversion sequence (13.3.3.1.2), with the
4423 // second standard conversion sequence either an identity
4424 // conversion or, if the conversion function returns an
4425 // entity of a type that is a derived class of the parameter
4426 // type, a derived-to-base Conversion.
4427 if (!Best->FinalConversion.DirectBinding)
4428 return false;
4429
4430 ICS.setUserDefined();
4431 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4432 ICS.UserDefined.After = Best->FinalConversion;
4433 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4434 ICS.UserDefined.ConversionFunction = Best->Function;
4435 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4436 ICS.UserDefined.EllipsisConversion = false;
4437 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
4438 ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
4439 "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
;
4440 return true;
4441
4442 case OR_Ambiguous:
4443 ICS.setAmbiguous();
4444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4445 Cand != CandidateSet.end(); ++Cand)
4446 if (Cand->Viable)
4447 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4448 return true;
4449
4450 case OR_No_Viable_Function:
4451 case OR_Deleted:
4452 // There was no suitable conversion, or we found a deleted
4453 // conversion; continue with other checks.
4454 return false;
4455 }
4456
4457 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4457)
;
4458}
4459
4460/// Compute an implicit conversion sequence for reference
4461/// initialization.
4462static ImplicitConversionSequence
4463TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4464 SourceLocation DeclLoc,
4465 bool SuppressUserConversions,
4466 bool AllowExplicit) {
4467 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() &&
"Reference init needs a reference") ? void (0) : __assert_fail
("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4467, __extension__ __PRETTY_FUNCTION__))
;
4468
4469 // Most paths end in a failed conversion.
4470 ImplicitConversionSequence ICS;
4471 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4472
4473 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4474 QualType T2 = Init->getType();
4475
4476 // If the initializer is the address of an overloaded function, try
4477 // to resolve the overloaded function. If all goes well, T2 is the
4478 // type of the resulting function.
4479 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4480 DeclAccessPair Found;
4481 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4482 false, Found))
4483 T2 = Fn->getType();
4484 }
4485
4486 // Compute some basic properties of the types and the initializer.
4487 bool isRValRef = DeclType->isRValueReferenceType();
4488 bool DerivedToBase = false;
4489 bool ObjCConversion = false;
4490 bool ObjCLifetimeConversion = false;
4491 Expr::Classification InitCategory = Init->Classify(S.Context);
4492 Sema::ReferenceCompareResult RefRelationship
4493 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4494 ObjCConversion, ObjCLifetimeConversion);
4495
4496
4497 // C++0x [dcl.init.ref]p5:
4498 // A reference to type "cv1 T1" is initialized by an expression
4499 // of type "cv2 T2" as follows:
4500
4501 // -- If reference is an lvalue reference and the initializer expression
4502 if (!isRValRef) {
4503 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4504 // reference-compatible with "cv2 T2," or
4505 //
4506 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4507 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4508 // C++ [over.ics.ref]p1:
4509 // When a parameter of reference type binds directly (8.5.3)
4510 // to an argument expression, the implicit conversion sequence
4511 // is the identity conversion, unless the argument expression
4512 // has a type that is a derived class of the parameter type,
4513 // in which case the implicit conversion sequence is a
4514 // derived-to-base Conversion (13.3.3.1).
4515 ICS.setStandard();
4516 ICS.Standard.First = ICK_Identity;
4517 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4518 : ObjCConversion? ICK_Compatible_Conversion
4519 : ICK_Identity;
4520 ICS.Standard.Third = ICK_Identity;
4521 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4522 ICS.Standard.setToType(0, T2);
4523 ICS.Standard.setToType(1, T1);
4524 ICS.Standard.setToType(2, T1);
4525 ICS.Standard.ReferenceBinding = true;
4526 ICS.Standard.DirectBinding = true;
4527 ICS.Standard.IsLvalueReference = !isRValRef;
4528 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4529 ICS.Standard.BindsToRvalue = false;
4530 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4531 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4532 ICS.Standard.CopyConstructor = nullptr;
4533 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4534
4535 // Nothing more to do: the inaccessibility/ambiguity check for
4536 // derived-to-base conversions is suppressed when we're
4537 // computing the implicit conversion sequence (C++
4538 // [over.best.ics]p2).
4539 return ICS;
4540 }
4541
4542 // -- has a class type (i.e., T2 is a class type), where T1 is
4543 // not reference-related to T2, and can be implicitly
4544 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4545 // is reference-compatible with "cv3 T3" 92) (this
4546 // conversion is selected by enumerating the applicable
4547 // conversion functions (13.3.1.6) and choosing the best
4548 // one through overload resolution (13.3)),
4549 if (!SuppressUserConversions && T2->isRecordType() &&
4550 S.isCompleteType(DeclLoc, T2) &&
4551 RefRelationship == Sema::Ref_Incompatible) {
4552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4553 Init, T2, /*AllowRvalues=*/false,
4554 AllowExplicit))
4555 return ICS;
4556 }
4557 }
4558
4559 // -- Otherwise, the reference shall be an lvalue reference to a
4560 // non-volatile const type (i.e., cv1 shall be const), or the reference
4561 // shall be an rvalue reference.
4562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4563 return ICS;
4564
4565 // -- If the initializer expression
4566 //
4567 // -- is an xvalue, class prvalue, array prvalue or function
4568 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4569 if (RefRelationship == Sema::Ref_Compatible &&
4570 (InitCategory.isXValue() ||
4571 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4572 (InitCategory.isLValue() && T2->isFunctionType()))) {
4573 ICS.setStandard();
4574 ICS.Standard.First = ICK_Identity;
4575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4576 : ObjCConversion? ICK_Compatible_Conversion
4577 : ICK_Identity;
4578 ICS.Standard.Third = ICK_Identity;
4579 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4580 ICS.Standard.setToType(0, T2);
4581 ICS.Standard.setToType(1, T1);
4582 ICS.Standard.setToType(2, T1);
4583 ICS.Standard.ReferenceBinding = true;
4584 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4585 // binding unless we're binding to a class prvalue.
4586 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4587 // allow the use of rvalue references in C++98/03 for the benefit of
4588 // standard library implementors; therefore, we need the xvalue check here.
4589 ICS.Standard.DirectBinding =
4590 S.getLangOpts().CPlusPlus11 ||
4591 !(InitCategory.isPRValue() || T2->isRecordType());
4592 ICS.Standard.IsLvalueReference = !isRValRef;
4593 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4594 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4595 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4596 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4597 ICS.Standard.CopyConstructor = nullptr;
4598 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4599 return ICS;
4600 }
4601
4602 // -- has a class type (i.e., T2 is a class type), where T1 is not
4603 // reference-related to T2, and can be implicitly converted to
4604 // an xvalue, class prvalue, or function lvalue of type
4605 // "cv3 T3", where "cv1 T1" is reference-compatible with
4606 // "cv3 T3",
4607 //
4608 // then the reference is bound to the value of the initializer
4609 // expression in the first case and to the result of the conversion
4610 // in the second case (or, in either case, to an appropriate base
4611 // class subobject).
4612 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4613 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4614 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4615 Init, T2, /*AllowRvalues=*/true,
4616 AllowExplicit)) {
4617 // In the second case, if the reference is an rvalue reference
4618 // and the second standard conversion sequence of the
4619 // user-defined conversion sequence includes an lvalue-to-rvalue
4620 // conversion, the program is ill-formed.
4621 if (ICS.isUserDefined() && isRValRef &&
4622 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4623 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4624
4625 return ICS;
4626 }
4627
4628 // A temporary of function type cannot be created; don't even try.
4629 if (T1->isFunctionType())
4630 return ICS;
4631
4632 // -- Otherwise, a temporary of type "cv1 T1" is created and
4633 // initialized from the initializer expression using the
4634 // rules for a non-reference copy initialization (8.5). The
4635 // reference is then bound to the temporary. If T1 is
4636 // reference-related to T2, cv1 must be the same
4637 // cv-qualification as, or greater cv-qualification than,
4638 // cv2; otherwise, the program is ill-formed.
4639 if (RefRelationship == Sema::Ref_Related) {
4640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4641 // we would be reference-compatible or reference-compatible with
4642 // added qualification. But that wasn't the case, so the reference
4643 // initialization fails.
4644 //
4645 // Note that we only want to check address spaces and cvr-qualifiers here.
4646 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4647 Qualifiers T1Quals = T1.getQualifiers();
4648 Qualifiers T2Quals = T2.getQualifiers();
4649 T1Quals.removeObjCGCAttr();
4650 T1Quals.removeObjCLifetime();
4651 T2Quals.removeObjCGCAttr();
4652 T2Quals.removeObjCLifetime();
4653 // MS compiler ignores __unaligned qualifier for references; do the same.
4654 T1Quals.removeUnaligned();
4655 T2Quals.removeUnaligned();
4656 if (!T1Quals.compatiblyIncludes(T2Quals))
4657 return ICS;
4658 }
4659
4660 // If at least one of the types is a class type, the types are not
4661 // related, and we aren't allowed any user conversions, the
4662 // reference binding fails. This case is important for breaking
4663 // recursion, since TryImplicitConversion below will attempt to
4664 // create a temporary through the use of a copy constructor.
4665 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666 (T1->isRecordType() || T2->isRecordType()))
4667 return ICS;
4668
4669 // If T1 is reference-related to T2 and the reference is an rvalue
4670 // reference, the initializer expression shall not be an lvalue.
4671 if (RefRelationship >= Sema::Ref_Related &&
4672 isRValRef && Init->Classify(S.Context).isLValue())
4673 return ICS;
4674
4675 // C++ [over.ics.ref]p2:
4676 // When a parameter of reference type is not bound directly to
4677 // an argument expression, the conversion sequence is the one
4678 // required to convert the argument expression to the
4679 // underlying type of the reference according to
4680 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4681 // to copy-initializing a temporary of the underlying type with
4682 // the argument expression. Any difference in top-level
4683 // cv-qualification is subsumed by the initialization itself
4684 // and does not constitute a conversion.
4685 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4686 /*AllowExplicit=*/false,
4687 /*InOverloadResolution=*/false,
4688 /*CStyle=*/false,
4689 /*AllowObjCWritebackConversion=*/false,
4690 /*AllowObjCConversionOnExplicit=*/false);
4691
4692 // Of course, that's still a reference binding.
4693 if (ICS.isStandard()) {
4694 ICS.Standard.ReferenceBinding = true;
4695 ICS.Standard.IsLvalueReference = !isRValRef;
4696 ICS.Standard.BindsToFunctionLvalue = false;
4697 ICS.Standard.BindsToRvalue = true;
4698 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4699 ICS.Standard.ObjCLifetimeConversionBinding = false;
4700 } else if (ICS.isUserDefined()) {
4701 const ReferenceType *LValRefType =
4702 ICS.UserDefined.ConversionFunction->getReturnType()
4703 ->getAs<LValueReferenceType>();
4704
4705 // C++ [over.ics.ref]p3:
4706 // Except for an implicit object parameter, for which see 13.3.1, a
4707 // standard conversion sequence cannot be formed if it requires [...]
4708 // binding an rvalue reference to an lvalue other than a function
4709 // lvalue.
4710 // Note that the function case is not possible here.
4711 if (DeclType->isRValueReferenceType() && LValRefType) {
4712 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4713 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4714 // reference to an rvalue!
4715 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4716 return ICS;
4717 }
4718
4719 ICS.UserDefined.After.ReferenceBinding = true;
4720 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4721 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4722 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4723 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4725 }
4726
4727 return ICS;
4728}
4729
4730static ImplicitConversionSequence
4731TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4732 bool SuppressUserConversions,
4733 bool InOverloadResolution,
4734 bool AllowObjCWritebackConversion,
4735 bool AllowExplicit = false);
4736
4737/// TryListConversion - Try to copy-initialize a value of type ToType from the
4738/// initializer list From.
4739static ImplicitConversionSequence
4740TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4741 bool SuppressUserConversions,
4742 bool InOverloadResolution,
4743 bool AllowObjCWritebackConversion) {
4744 // C++11 [over.ics.list]p1:
4745 // When an argument is an initializer list, it is not an expression and
4746 // special rules apply for converting it to a parameter type.
4747
4748 ImplicitConversionSequence Result;
4749 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4750
4751 // We need a complete type for what follows. Incomplete types can never be
4752 // initialized from init lists.
4753 if (!S.isCompleteType(From->getLocStart(), ToType))
4754 return Result;
4755
4756 // Per DR1467:
4757 // If the parameter type is a class X and the initializer list has a single
4758 // element of type cv U, where U is X or a class derived from X, the
4759 // implicit conversion sequence is the one required to convert the element
4760 // to the parameter type.
4761 //
4762 // Otherwise, if the parameter type is a character array [... ]
4763 // and the initializer list has a single element that is an
4764 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4765 // implicit conversion sequence is the identity conversion.
4766 if (From->getNumInits() == 1) {
4767 if (ToType->isRecordType()) {
4768 QualType InitType = From->getInit(0)->getType();
4769 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4770 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4771 return TryCopyInitialization(S, From->getInit(0), ToType,
4772 SuppressUserConversions,
4773 InOverloadResolution,
4774 AllowObjCWritebackConversion);
4775 }
4776 // FIXME: Check the other conditions here: array of character type,
4777 // initializer is a string literal.
4778 if (ToType->isArrayType()) {
4779 InitializedEntity Entity =
4780 InitializedEntity::InitializeParameter(S.Context, ToType,
4781 /*Consumed=*/false);
4782 if (S.CanPerformCopyInitialization(Entity, From)) {
4783 Result.setStandard();
4784 Result.Standard.setAsIdentityConversion();
4785 Result.Standard.setFromType(ToType);
4786 Result.Standard.setAllToTypes(ToType);
4787 return Result;
4788 }
4789 }
4790 }
4791
4792 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4793 // C++11 [over.ics.list]p2:
4794 // If the parameter type is std::initializer_list<X> or "array of X" and
4795 // all the elements can be implicitly converted to X, the implicit
4796 // conversion sequence is the worst conversion necessary to convert an
4797 // element of the list to X.
4798 //
4799 // C++14 [over.ics.list]p3:
4800 // Otherwise, if the parameter type is "array of N X", if the initializer
4801 // list has exactly N elements or if it has fewer than N elements and X is
4802 // default-constructible, and if all the elements of the initializer list
4803 // can be implicitly converted to X, the implicit conversion sequence is
4804 // the worst conversion necessary to convert an element of the list to X.
4805 //
4806 // FIXME: We're missing a lot of these checks.
4807 bool toStdInitializerList = false;
4808 QualType X;
4809 if (ToType->isArrayType())
4810 X = S.Context.getAsArrayType(ToType)->getElementType();
4811 else
4812 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4813 if (!X.isNull()) {
4814 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4815 Expr *Init = From->getInit(i);
4816 ImplicitConversionSequence ICS =
4817 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4818 InOverloadResolution,
4819 AllowObjCWritebackConversion);
4820 // If a single element isn't convertible, fail.
4821 if (ICS.isBad()) {
4822 Result = ICS;
4823 break;
4824 }
4825 // Otherwise, look for the worst conversion.
4826 if (Result.isBad() ||
4827 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4828 Result) ==
4829 ImplicitConversionSequence::Worse)
4830 Result = ICS;
4831 }
4832
4833 // For an empty list, we won't have computed any conversion sequence.
4834 // Introduce the identity conversion sequence.
4835 if (From->getNumInits() == 0) {
4836 Result.setStandard();
4837 Result.Standard.setAsIdentityConversion();
4838 Result.Standard.setFromType(ToType);
4839 Result.Standard.setAllToTypes(ToType);
4840 }
4841
4842 Result.setStdInitializerListElement(toStdInitializerList);
4843 return Result;
4844 }
4845
4846 // C++14 [over.ics.list]p4:
4847 // C++11 [over.ics.list]p3:
4848 // Otherwise, if the parameter is a non-aggregate class X and overload
4849 // resolution chooses a single best constructor [...] the implicit
4850 // conversion sequence is a user-defined conversion sequence. If multiple
4851 // constructors are viable but none is better than the others, the
4852 // implicit conversion sequence is a user-defined conversion sequence.
4853 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4854 // This function can deal with initializer lists.
4855 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4856 /*AllowExplicit=*/false,
4857 InOverloadResolution, /*CStyle=*/false,
4858 AllowObjCWritebackConversion,
4859 /*AllowObjCConversionOnExplicit=*/false);
4860 }
4861
4862 // C++14 [over.ics.list]p5:
4863 // C++11 [over.ics.list]p4:
4864 // Otherwise, if the parameter has an aggregate type which can be
4865 // initialized from the initializer list [...] the implicit conversion
4866 // sequence is a user-defined conversion sequence.
4867 if (ToType->isAggregateType()) {
4868 // Type is an aggregate, argument is an init list. At this point it comes
4869 // down to checking whether the initialization works.
4870 // FIXME: Find out whether this parameter is consumed or not.
4871 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4872 // need to call into the initialization code here; overload resolution
4873 // should not be doing that.
4874 InitializedEntity Entity =
4875 InitializedEntity::InitializeParameter(S.Context, ToType,
4876 /*Consumed=*/false);
4877 if (S.CanPerformCopyInitialization(Entity, From)) {
4878 Result.setUserDefined();
4879 Result.UserDefined.Before.setAsIdentityConversion();
4880 // Initializer lists don't have a type.
4881 Result.UserDefined.Before.setFromType(QualType());
4882 Result.UserDefined.Before.setAllToTypes(QualType());
4883
4884 Result.UserDefined.After.setAsIdentityConversion();
4885 Result.UserDefined.After.setFromType(ToType);
4886 Result.UserDefined.After.setAllToTypes(ToType);
4887 Result.UserDefined.ConversionFunction = nullptr;
4888 }
4889 return Result;
4890 }
4891
4892 // C++14 [over.ics.list]p6:
4893 // C++11 [over.ics.list]p5:
4894 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4895 if (ToType->isReferenceType()) {
4896 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4897 // mention initializer lists in any way. So we go by what list-
4898 // initialization would do and try to extrapolate from that.
4899
4900 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4901
4902 // If the initializer list has a single element that is reference-related
4903 // to the parameter type, we initialize the reference from that.
4904 if (From->getNumInits() == 1) {
4905 Expr *Init = From->getInit(0);
4906
4907 QualType T2 = Init->getType();
4908
4909 // If the initializer is the address of an overloaded function, try
4910 // to resolve the overloaded function. If all goes well, T2 is the
4911 // type of the resulting function.
4912 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4913 DeclAccessPair Found;
4914 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4915 Init, ToType, false, Found))
4916 T2 = Fn->getType();
4917 }
4918
4919 // Compute some basic properties of the types and the initializer.
4920 bool dummy1 = false;
4921 bool dummy2 = false;
4922 bool dummy3 = false;
4923 Sema::ReferenceCompareResult RefRelationship
4924 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4925 dummy2, dummy3);
4926
4927 if (RefRelationship >= Sema::Ref_Related) {
4928 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4929 SuppressUserConversions,
4930 /*AllowExplicit=*/false);
4931 }
4932 }
4933
4934 // Otherwise, we bind the reference to a temporary created from the
4935 // initializer list.
4936 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4937 InOverloadResolution,
4938 AllowObjCWritebackConversion);
4939 if (Result.isFailure())
4940 return Result;
4941 assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4942, __extension__ __PRETTY_FUNCTION__))
4942 "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4942, __extension__ __PRETTY_FUNCTION__))
;
4943
4944 // Can we even bind to a temporary?
4945 if (ToType->isRValueReferenceType() ||
4946 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4947 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4948 Result.UserDefined.After;
4949 SCS.ReferenceBinding = true;
4950 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4951 SCS.BindsToRvalue = true;
4952 SCS.BindsToFunctionLvalue = false;
4953 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4954 SCS.ObjCLifetimeConversionBinding = false;
4955 } else
4956 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4957 From, ToType);
4958 return Result;
4959 }
4960
4961 // C++14 [over.ics.list]p7:
4962 // C++11 [over.ics.list]p6:
4963 // Otherwise, if the parameter type is not a class:
4964 if (!ToType->isRecordType()) {
4965 // - if the initializer list has one element that is not itself an
4966 // initializer list, the implicit conversion sequence is the one
4967 // required to convert the element to the parameter type.
4968 unsigned NumInits = From->getNumInits();
4969 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4970 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4971 SuppressUserConversions,
4972 InOverloadResolution,
4973 AllowObjCWritebackConversion);
4974 // - if the initializer list has no elements, the implicit conversion
4975 // sequence is the identity conversion.
4976 else if (NumInits == 0) {
4977 Result.setStandard();
4978 Result.Standard.setAsIdentityConversion();
4979 Result.Standard.setFromType(ToType);
4980 Result.Standard.setAllToTypes(ToType);
4981 }
4982 return Result;
4983 }
4984
4985 // C++14 [over.ics.list]p8:
4986 // C++11 [over.ics.list]p7:
4987 // In all cases other than those enumerated above, no conversion is possible
4988 return Result;
4989}
4990
4991/// TryCopyInitialization - Try to copy-initialize a value of type
4992/// ToType from the expression From. Return the implicit conversion
4993/// sequence required to pass this argument, which may be a bad
4994/// conversion sequence (meaning that the argument cannot be passed to
4995/// a parameter of this type). If @p SuppressUserConversions, then we
4996/// do not permit any user-defined conversion sequences.
4997static ImplicitConversionSequence
4998TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4999 bool SuppressUserConversions,
5000 bool InOverloadResolution,
5001 bool AllowObjCWritebackConversion,
5002 bool AllowExplicit) {
5003 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5004 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5005 InOverloadResolution,AllowObjCWritebackConversion);
5006
5007 if (ToType->isReferenceType())
5008 return TryReferenceInit(S, From, ToType,
5009 /*FIXME:*/From->getLocStart(),
5010 SuppressUserConversions,
5011 AllowExplicit);
5012
5013 return TryImplicitConversion(S, From, ToType,
5014 SuppressUserConversions,
5015 /*AllowExplicit=*/false,
5016 InOverloadResolution,
5017 /*CStyle=*/false,
5018 AllowObjCWritebackConversion,
5019 /*AllowObjCConversionOnExplicit=*/false);
5020}
5021
5022static bool TryCopyInitialization(const CanQualType FromQTy,
5023 const CanQualType ToQTy,
5024 Sema &S,
5025 SourceLocation Loc,
5026 ExprValueKind FromVK) {
5027 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5028 ImplicitConversionSequence ICS =
5029 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5030
5031 return !ICS.isBad();
5032}
5033
5034/// TryObjectArgumentInitialization - Try to initialize the object
5035/// parameter of the given member function (@c Method) from the
5036/// expression @p From.
5037static ImplicitConversionSequence
5038TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5039 Expr::Classification FromClassification,
5040 CXXMethodDecl *Method,
5041 CXXRecordDecl *ActingContext) {
5042 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5043 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5044 // const volatile object.
5045 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5046 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5047 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
5048
5049 // Set up the conversion sequence as a "bad" conversion, to allow us
5050 // to exit early.
5051 ImplicitConversionSequence ICS;
5052
5053 // We need to have an object of class type.
5054 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5055 FromType = PT->getPointeeType();
5056
5057 // When we had a pointer, it's implicitly dereferenced, so we
5058 // better have an lvalue.
5059 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5059, __extension__ __PRETTY_FUNCTION__))
;
5060 }
5061
5062 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5062, __extension__ __PRETTY_FUNCTION__))
;
5063
5064 // C++0x [over.match.funcs]p4:
5065 // For non-static member functions, the type of the implicit object
5066 // parameter is
5067 //
5068 // - "lvalue reference to cv X" for functions declared without a
5069 // ref-qualifier or with the & ref-qualifier
5070 // - "rvalue reference to cv X" for functions declared with the &&
5071 // ref-qualifier
5072 //
5073 // where X is the class of which the function is a member and cv is the
5074 // cv-qualification on the member function declaration.
5075 //
5076 // However, when finding an implicit conversion sequence for the argument, we
5077 // are not allowed to perform user-defined conversions
5078 // (C++ [over.match.funcs]p5). We perform a simplified version of
5079 // reference binding here, that allows class rvalues to bind to
5080 // non-constant references.
5081
5082 // First check the qualifiers.
5083 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5084 if (ImplicitParamType.getCVRQualifiers()
5085 != FromTypeCanon.getLocalCVRQualifiers() &&
5086 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5087 ICS.setBad(BadConversionSequence::bad_qualifiers,
5088 FromType, ImplicitParamType);
5089 return ICS;
5090 }
5091
5092 // Check that we have either the same type or a derived type. It
5093 // affects the conversion rank.
5094 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5095 ImplicitConversionKind SecondKind;
5096 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5097 SecondKind = ICK_Identity;
5098 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5099 SecondKind = ICK_Derived_To_Base;
5100 else {
5101 ICS.setBad(BadConversionSequence::unrelated_class,
5102 FromType, ImplicitParamType);
5103 return ICS;
5104 }
5105
5106 // Check the ref-qualifier.
5107 switch (Method->getRefQualifier()) {
5108 case RQ_None:
5109 // Do nothing; we don't care about lvalueness or rvalueness.
5110 break;
5111
5112 case RQ_LValue:
5113 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5114 // non-const lvalue reference cannot bind to an rvalue
5115 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5116 ImplicitParamType);
5117 return ICS;
5118 }
5119 break;
5120
5121 case RQ_RValue:
5122 if (!FromClassification.isRValue()) {
5123 // rvalue reference cannot bind to an lvalue
5124 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5125 ImplicitParamType);
5126 return ICS;
5127 }
5128 break;
5129 }
5130
5131 // Success. Mark this as a reference binding.
5132 ICS.setStandard();
5133 ICS.Standard.setAsIdentityConversion();
5134 ICS.Standard.Second = SecondKind;
5135 ICS.Standard.setFromType(FromType);
5136 ICS.Standard.setAllToTypes(ImplicitParamType);
5137 ICS.Standard.ReferenceBinding = true;
5138 ICS.Standard.DirectBinding = true;
5139 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5140 ICS.Standard.BindsToFunctionLvalue = false;
5141 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5142 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5143 = (Method->getRefQualifier() == RQ_None);
5144 return ICS;
5145}
5146
5147/// PerformObjectArgumentInitialization - Perform initialization of
5148/// the implicit object parameter for the given Method with the given
5149/// expression.
5150ExprResult
5151Sema::PerformObjectArgumentInitialization(Expr *From,
5152 NestedNameSpecifier *Qualifier,
5153 NamedDecl *FoundDecl,
5154 CXXMethodDecl *Method) {
5155 QualType FromRecordType, DestType;
5156 QualType ImplicitParamRecordType =
5157 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5158
5159 Expr::Classification FromClassification;
5160 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5161 FromRecordType = PT->getPointeeType();
5162 DestType = Method->getThisType(Context);
5163 FromClassification = Expr::Classification::makeSimpleLValue();
5164 } else {
5165 FromRecordType = From->getType();
5166 DestType = ImplicitParamRecordType;
5167 FromClassification = From->Classify(Context);
5168
5169 // When performing member access on an rvalue, materialize a temporary.
5170 if (From->isRValue()) {
5171 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5172 Method->getRefQualifier() !=
5173 RefQualifierKind::RQ_RValue);
5174 }
5175 }
5176
5177 // Note that we always use the true parent context when performing
5178 // the actual argument initialization.
5179 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5180 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5181 Method->getParent());
5182 if (ICS.isBad()) {
5183 switch (ICS.Bad.Kind) {
5184 case BadConversionSequence::bad_qualifiers: {
5185 Qualifiers FromQs = FromRecordType.getQualifiers();
5186 Qualifiers ToQs = DestType.getQualifiers();
5187 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5188 if (CVR) {
5189 Diag(From->getLocStart(),
5190 diag::err_member_function_call_bad_cvr)
5191 << Method->getDeclName() << FromRecordType << (CVR - 1)
5192 << From->getSourceRange();
5193 Diag(Method->getLocation(), diag::note_previous_decl)
5194 << Method->getDeclName();
5195 return ExprError();
5196 }
5197 break;
5198 }
5199
5200 case BadConversionSequence::lvalue_ref_to_rvalue:
5201 case BadConversionSequence::rvalue_ref_to_lvalue: {
5202 bool IsRValueQualified =
5203 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5204 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5205 << Method->getDeclName() << FromClassification.isRValue()
5206 << IsRValueQualified;
5207 Diag(Method->getLocation(), diag::note_previous_decl)
5208 << Method->getDeclName();
5209 return ExprError();
5210 }
5211
5212 case BadConversionSequence::no_conversion:
5213 case BadConversionSequence::unrelated_class:
5214 break;
5215 }
5216
5217 return Diag(From->getLocStart(),
5218 diag::err_member_function_call_bad_type)
5219 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5220 }
5221
5222 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5223 ExprResult FromRes =
5224 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5225 if (FromRes.isInvalid())
5226 return ExprError();
5227 From = FromRes.get();
5228 }
5229
5230 if (!Context.hasSameType(From->getType(), DestType))
5231 From = ImpCastExprToType(From, DestType, CK_NoOp,
5232 From->getValueKind()).get();
5233 return From;
5234}
5235
5236/// TryContextuallyConvertToBool - Attempt to contextually convert the
5237/// expression From to bool (C++0x [conv]p3).
5238static ImplicitConversionSequence
5239TryContextuallyConvertToBool(Sema &S, Expr *From) {
5240 return TryImplicitConversion(S, From, S.Context.BoolTy,
5241 /*SuppressUserConversions=*/false,
5242 /*AllowExplicit=*/true,
5243 /*InOverloadResolution=*/false,
5244 /*CStyle=*/false,
5245 /*AllowObjCWritebackConversion=*/false,
5246 /*AllowObjCConversionOnExplicit=*/false);
5247}
5248
5249/// PerformContextuallyConvertToBool - Perform a contextual conversion
5250/// of the expression From to bool (C++0x [conv]p3).
5251ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5252 if (checkPlaceholderForOverload(*this, From))
5253 return ExprError();
5254
5255 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5256 if (!ICS.isBad())
5257 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5258
5259 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5260 return Diag(From->getLocStart(),
5261 diag::err_typecheck_bool_condition)
5262 << From->getType() << From->getSourceRange();
5263 return ExprError();
5264}
5265
5266/// Check that the specified conversion is permitted in a converted constant
5267/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5268/// is acceptable.
5269static bool CheckConvertedConstantConversions(Sema &S,
5270 StandardConversionSequence &SCS) {
5271 // Since we know that the target type is an integral or unscoped enumeration
5272 // type, most conversion kinds are impossible. All possible First and Third
5273 // conversions are fine.
5274 switch (SCS.Second) {
5275 case ICK_Identity:
5276 case ICK_Function_Conversion:
5277 case ICK_Integral_Promotion:
5278 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5279 case ICK_Zero_Queue_Conversion:
5280 return true;
5281
5282 case ICK_Boolean_Conversion:
5283 // Conversion from an integral or unscoped enumeration type to bool is
5284 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5285 // conversion, so we allow it in a converted constant expression.
5286 //
5287 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5288 // a lot of popular code. We should at least add a warning for this
5289 // (non-conforming) extension.
5290 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5291 SCS.getToType(2)->isBooleanType();
5292
5293 case ICK_Pointer_Conversion:
5294 case ICK_Pointer_Member:
5295 // C++1z: null pointer conversions and null member pointer conversions are
5296 // only permitted if the source type is std::nullptr_t.
5297 return SCS.getFromType()->isNullPtrType();
5298
5299 case ICK_Floating_Promotion:
5300 case ICK_Complex_Promotion:
5301 case ICK_Floating_Conversion:
5302 case ICK_Complex_Conversion:
5303 case ICK_Floating_Integral:
5304 case ICK_Compatible_Conversion:
5305 case ICK_Derived_To_Base:
5306 case ICK_Vector_Conversion:
5307 case ICK_Vector_Splat:
5308 case ICK_Complex_Real:
5309 case ICK_Block_Pointer_Conversion:
5310 case ICK_TransparentUnionConversion:
5311 case ICK_Writeback_Conversion:
5312 case ICK_Zero_Event_Conversion:
5313 case ICK_C_Only_Conversion:
5314 case ICK_Incompatible_Pointer_Conversion:
5315 return false;
5316
5317 case ICK_Lvalue_To_Rvalue:
5318 case ICK_Array_To_Pointer:
5319 case ICK_Function_To_Pointer:
5320 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5320)
;
5321
5322 case ICK_Qualification:
5323 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5323)
;
5324
5325 case ICK_Num_Conversion_Kinds:
5326 break;
5327 }
5328
5329 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5329)
;
5330}
5331
5332/// CheckConvertedConstantExpression - Check that the expression From is a
5333/// converted constant expression of type T, perform the conversion and produce
5334/// the converted expression, per C++11 [expr.const]p3.
5335static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5336 QualType T, APValue &Value,
5337 Sema::CCEKind CCE,
5338 bool RequireInt) {
5339 assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5340, __extension__ __PRETTY_FUNCTION__))
5340 "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5340, __extension__ __PRETTY_FUNCTION__))
;
5341
5342 if (checkPlaceholderForOverload(S, From))
5343 return ExprError();
5344
5345 // C++1z [expr.const]p3:
5346 // A converted constant expression of type T is an expression,
5347 // implicitly converted to type T, where the converted
5348 // expression is a constant expression and the implicit conversion
5349 // sequence contains only [... list of conversions ...].
5350 // C++1z [stmt.if]p2:
5351 // If the if statement is of the form if constexpr, the value of the
5352 // condition shall be a contextually converted constant expression of type
5353 // bool.
5354 ImplicitConversionSequence ICS =
5355 CCE == Sema::CCEK_ConstexprIf
5356 ? TryContextuallyConvertToBool(S, From)
5357 : TryCopyInitialization(S, From, T,
5358 /*SuppressUserConversions=*/false,
5359 /*InOverloadResolution=*/false,
5360 /*AllowObjcWritebackConversion=*/false,
5361 /*AllowExplicit=*/false);
5362 StandardConversionSequence *SCS = nullptr;
5363 switch (ICS.getKind()) {
5364 case ImplicitConversionSequence::StandardConversion:
5365 SCS = &ICS.Standard;
5366 break;
5367 case ImplicitConversionSequence::UserDefinedConversion:
5368 // We are converting to a non-class type, so the Before sequence
5369 // must be trivial.
5370 SCS = &ICS.UserDefined.After;
5371 break;
5372 case ImplicitConversionSequence::AmbiguousConversion:
5373 case ImplicitConversionSequence::BadConversion:
5374 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5375 return S.Diag(From->getLocStart(),
5376 diag::err_typecheck_converted_constant_expression)
5377 << From->getType() << From->getSourceRange() << T;
5378 return ExprError();
5379
5380 case ImplicitConversionSequence::EllipsisConversion:
5381 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5381)
;
5382 }
5383
5384 // Check that we would only use permitted conversions.
5385 if (!CheckConvertedConstantConversions(S, *SCS)) {
5386 return S.Diag(From->getLocStart(),
5387 diag::err_typecheck_converted_constant_expression_disallowed)
5388 << From->getType() << From->getSourceRange() << T;
5389 }
5390 // [...] and where the reference binding (if any) binds directly.
5391 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5392 return S.Diag(From->getLocStart(),
5393 diag::err_typecheck_converted_constant_expression_indirect)
5394 << From->getType() << From->getSourceRange() << T;
5395 }
5396
5397 ExprResult Result =
5398 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5399 if (Result.isInvalid())
5400 return Result;
5401
5402 // Check for a narrowing implicit conversion.
5403 APValue PreNarrowingValue;
5404 QualType PreNarrowingType;
5405 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5406 PreNarrowingType)) {
5407 case NK_Dependent_Narrowing:
5408 // Implicit conversion to a narrower type, but the expression is
5409 // value-dependent so we can't tell whether it's actually narrowing.
5410 case NK_Variable_Narrowing:
5411 // Implicit conversion to a narrower type, and the value is not a constant
5412 // expression. We'll diagnose this in a moment.
5413 case NK_Not_Narrowing:
5414 break;
5415
5416 case NK_Constant_Narrowing:
5417 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5418 << CCE << /*Constant*/1
5419 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5420 break;
5421
5422 case NK_Type_Narrowing:
5423 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5424 << CCE << /*Constant*/0 << From->getType() << T;
5425 break;
5426 }
5427
5428 if (Result.get()->isValueDependent()) {
5429 Value = APValue();
5430 return Result;
5431 }
5432
5433 // Check the expression is a constant expression.
5434 SmallVector<PartialDiagnosticAt, 8> Notes;
5435 Expr::EvalResult Eval;
5436 Eval.Diag = &Notes;
5437 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5438 ? Expr::EvaluateForMangling
5439 : Expr::EvaluateForCodeGen;
5440
5441 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5442 (RequireInt && !Eval.Val.isInt())) {
5443 // The expression can't be folded, so we can't keep it at this position in
5444 // the AST.
5445 Result = ExprError();
5446 } else {
5447 Value = Eval.Val;
5448
5449 if (Notes.empty()) {
5450 // It's a constant expression.
5451 return Result;
5452 }
5453 }
5454
5455 // It's not a constant expression. Produce an appropriate diagnostic.
5456 if (Notes.size() == 1 &&
5457 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5458 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5459 else {
5460 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5461 << CCE << From->getSourceRange();
5462 for (unsigned I = 0; I < Notes.size(); ++I)
5463 S.Diag(Notes[I].first, Notes[I].second);
5464 }
5465 return ExprError();
5466}
5467
5468ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5469 APValue &Value, CCEKind CCE) {
5470 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5471}
5472
5473ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5474 llvm::APSInt &Value,
5475 CCEKind CCE) {
5476 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast <bool> (T->isIntegralOrEnumerationType(
) && "unexpected converted const type") ? void (0) : __assert_fail
("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5476, __extension__ __PRETTY_FUNCTION__))
;
5477
5478 APValue V;
5479 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5480 if (!R.isInvalid() && !R.get()->isValueDependent())
5481 Value = V.getInt();
5482 return R;
5483}
5484
5485
5486/// dropPointerConversions - If the given standard conversion sequence
5487/// involves any pointer conversions, remove them. This may change
5488/// the result type of the conversion sequence.
5489static void dropPointerConversion(StandardConversionSequence &SCS) {
5490 if (SCS.Second == ICK_Pointer_Conversion) {
5491 SCS.Second = ICK_Identity;
5492 SCS.Third = ICK_Identity;
5493 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5494 }
5495}
5496
5497/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5498/// convert the expression From to an Objective-C pointer type.
5499static ImplicitConversionSequence
5500TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5501 // Do an implicit conversion to 'id'.
5502 QualType Ty = S.Context.getObjCIdType();
5503 ImplicitConversionSequence ICS
5504 = TryImplicitConversion(S, From, Ty,
5505 // FIXME: Are these flags correct?
5506 /*SuppressUserConversions=*/false,
5507 /*AllowExplicit=*/true,
5508 /*InOverloadResolution=*/false,
5509 /*CStyle=*/false,
5510 /*AllowObjCWritebackConversion=*/false,
5511 /*AllowObjCConversionOnExplicit=*/true);
5512
5513 // Strip off any final conversions to 'id'.
5514 switch (ICS.getKind()) {
5515 case ImplicitConversionSequence::BadConversion:
5516 case ImplicitConversionSequence::AmbiguousConversion:
5517 case ImplicitConversionSequence::EllipsisConversion:
5518 break;
5519
5520 case ImplicitConversionSequence::UserDefinedConversion:
5521 dropPointerConversion(ICS.UserDefined.After);
5522 break;
5523
5524 case ImplicitConversionSequence::StandardConversion:
5525 dropPointerConversion(ICS.Standard);
5526 break;
5527 }
5528
5529 return ICS;
5530}
5531
5532/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5533/// conversion of the expression From to an Objective-C pointer type.
5534/// Returns a valid but null ExprResult if no conversion sequence exists.
5535ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5536 if (checkPlaceholderForOverload(*this, From))
5537 return ExprError();
5538
5539 QualType Ty = Context.getObjCIdType();
5540 ImplicitConversionSequence ICS =
5541 TryContextuallyConvertToObjCPointer(*this, From);
5542 if (!ICS.isBad())
5543 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5544 return ExprResult();
5545}
5546
5547/// Determine whether the provided type is an integral type, or an enumeration
5548/// type of a permitted flavor.
5549bool Sema::ICEConvertDiagnoser::match(QualType T) {
5550 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5551 : T->isIntegralOrUnscopedEnumerationType();
5552}
5553
5554static ExprResult
5555diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5556 Sema::ContextualImplicitConverter &Converter,
5557 QualType T, UnresolvedSetImpl &ViableConversions) {
5558
5559 if (Converter.Suppress)
5560 return ExprError();
5561
5562 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5563 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5564 CXXConversionDecl *Conv =
5565 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5566 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5567 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5568 }
5569 return From;
5570}
5571
5572static bool
5573diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5574 Sema::ContextualImplicitConverter &Converter,
5575 QualType T, bool HadMultipleCandidates,
5576 UnresolvedSetImpl &ExplicitConversions) {
5577 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5578 DeclAccessPair Found = ExplicitConversions[0];
5579 CXXConversionDecl *Conversion =
5580 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5581
5582 // The user probably meant to invoke the given explicit
5583 // conversion; use it.
5584 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5585 std::string TypeStr;
5586 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5587
5588 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5589 << FixItHint::CreateInsertion(From->getLocStart(),
5590 "static_cast<" + TypeStr + ">(")
5591 << FixItHint::CreateInsertion(
5592 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5593 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5594
5595 // If we aren't in a SFINAE context, build a call to the
5596 // explicit conversion function.
5597 if (SemaRef.isSFINAEContext())
5598 return true;
5599
5600 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5601 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5602 HadMultipleCandidates);
5603 if (Result.isInvalid())
5604 return true;
5605 // Record usage of conversion in an implicit cast.
5606 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5607 CK_UserDefinedConversion, Result.get(),
5608 nullptr, Result.get()->getValueKind());
5609 }
5610 return false;
5611}
5612
5613static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5614 Sema::ContextualImplicitConverter &Converter,
5615 QualType T, bool HadMultipleCandidates,
5616 DeclAccessPair &Found) {
5617 CXXConversionDecl *Conversion =
5618 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5619 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5620
5621 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5622 if (!Converter.SuppressConversion) {
5623 if (SemaRef.isSFINAEContext())
5624 return true;
5625
5626 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5627 << From->getSourceRange();
5628 }
5629
5630 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5631 HadMultipleCandidates);
5632 if (Result.isInvalid())
5633 return true;
5634 // Record usage of conversion in an implicit cast.
5635 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5636 CK_UserDefinedConversion, Result.get(),
5637 nullptr, Result.get()->getValueKind());
5638 return false;
5639}
5640
5641static ExprResult finishContextualImplicitConversion(
5642 Sema &SemaRef, SourceLocation Loc, Expr *From,
5643 Sema::ContextualImplicitConverter &Converter) {
5644 if (!Converter.match(From->getType()) && !Converter.Suppress)
5645 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5646 << From->getSourceRange();
5647
5648 return SemaRef.DefaultLvalueConversion(From);
5649}
5650
5651static void
5652collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5653 UnresolvedSetImpl &ViableConversions,
5654 OverloadCandidateSet &CandidateSet) {
5655 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5656 DeclAccessPair FoundDecl = ViableConversions[I];
5657 NamedDecl *D = FoundDecl.getDecl();
5658 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5659 if (isa<UsingShadowDecl>(D))
5660 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5661
5662 CXXConversionDecl *Conv;
5663 FunctionTemplateDecl *ConvTemplate;
5664 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5665 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5666 else
5667 Conv = cast<CXXConversionDecl>(D);
5668
5669 if (ConvTemplate)
5670 SemaRef.AddTemplateConversionCandidate(
5671 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5672 /*AllowObjCConversionOnExplicit=*/false);
5673 else
5674 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5675 ToType, CandidateSet,
5676 /*AllowObjCConversionOnExplicit=*/false);
5677 }
5678}
5679
5680/// Attempt to convert the given expression to a type which is accepted
5681/// by the given converter.
5682///
5683/// This routine will attempt to convert an expression of class type to a
5684/// type accepted by the specified converter. In C++11 and before, the class
5685/// must have a single non-explicit conversion function converting to a matching
5686/// type. In C++1y, there can be multiple such conversion functions, but only
5687/// one target type.
5688///
5689/// \param Loc The source location of the construct that requires the
5690/// conversion.
5691///
5692/// \param From The expression we're converting from.
5693///
5694/// \param Converter Used to control and diagnose the conversion process.
5695///
5696/// \returns The expression, converted to an integral or enumeration type if
5697/// successful.
5698ExprResult Sema::PerformContextualImplicitConversion(
5699 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5700 // We can't perform any more checking for type-dependent expressions.
5701 if (From->isTypeDependent())
5702 return From;
5703
5704 // Process placeholders immediately.
5705 if (From->hasPlaceholderType()) {
5706 ExprResult result = CheckPlaceholderExpr(From);
5707 if (result.isInvalid())
5708 return result;
5709 From = result.get();
5710 }
5711
5712 // If the expression already has a matching type, we're golden.
5713 QualType T = From->getType();
5714 if (Converter.match(T))
5715 return DefaultLvalueConversion(From);
5716
5717 // FIXME: Check for missing '()' if T is a function type?
5718
5719 // We can only perform contextual implicit conversions on objects of class
5720 // type.
5721 const RecordType *RecordTy = T->getAs<RecordType>();
5722 if (!RecordTy || !getLangOpts().CPlusPlus) {
5723 if (!Converter.Suppress)
5724 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5725 return From;
5726 }
5727
5728 // We must have a complete class type.
5729 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5730 ContextualImplicitConverter &Converter;
5731 Expr *From;
5732
5733 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5734 : Converter(Converter), From(From) {}
5735
5736 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5737 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5738 }
5739 } IncompleteDiagnoser(Converter, From);
5740
5741 if (Converter.Suppress ? !isCompleteType(Loc, T)
5742 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5743 return From;
5744
5745 // Look for a conversion to an integral or enumeration type.
5746 UnresolvedSet<4>
5747 ViableConversions; // These are *potentially* viable in C++1y.
5748 UnresolvedSet<4> ExplicitConversions;
5749 const auto &Conversions =
5750 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5751
5752 bool HadMultipleCandidates =
5753 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5754
5755 // To check that there is only one target type, in C++1y:
5756 QualType ToType;
5757 bool HasUniqueTargetType = true;
5758
5759 // Collect explicit or viable (potentially in C++1y) conversions.
5760 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5761 NamedDecl *D = (*I)->getUnderlyingDecl();
5762 CXXConversionDecl *Conversion;
5763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5764 if (ConvTemplate) {
5765 if (getLangOpts().CPlusPlus14)
5766 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5767 else
5768 continue; // C++11 does not consider conversion operator templates(?).
5769 } else
5770 Conversion = cast<CXXConversionDecl>(D);
5771
5772 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5774, __extension__ __PRETTY_FUNCTION__))
5773 "Conversion operator templates are considered potentially "(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5774, __extension__ __PRETTY_FUNCTION__))
5774 "viable in C++1y")(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5774, __extension__ __PRETTY_FUNCTION__))
;
5775
5776 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5777 if (Converter.match(CurToType) || ConvTemplate) {
5778
5779 if (Conversion->isExplicit()) {
5780 // FIXME: For C++1y, do we need this restriction?
5781 // cf. diagnoseNoViableConversion()
5782 if (!ConvTemplate)
5783 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5784 } else {
5785 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5786 if (ToType.isNull())
5787 ToType = CurToType.getUnqualifiedType();
5788 else if (HasUniqueTargetType &&
5789 (CurToType.getUnqualifiedType() != ToType))
5790 HasUniqueTargetType = false;
5791 }
5792 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5793 }
5794 }
5795 }
5796
5797 if (getLangOpts().CPlusPlus14) {
5798 // C++1y [conv]p6:
5799 // ... An expression e of class type E appearing in such a context
5800 // is said to be contextually implicitly converted to a specified
5801 // type T and is well-formed if and only if e can be implicitly
5802 // converted to a type T that is determined as follows: E is searched
5803 // for conversion functions whose return type is cv T or reference to
5804 // cv T such that T is allowed by the context. There shall be
5805 // exactly one such T.
5806
5807 // If no unique T is found:
5808 if (ToType.isNull()) {
5809 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5810 HadMultipleCandidates,
5811 ExplicitConversions))
5812 return ExprError();
5813 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5814 }
5815
5816 // If more than one unique Ts are found:
5817 if (!HasUniqueTargetType)
5818 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5819 ViableConversions);
5820
5821 // If one unique T is found:
5822 // First, build a candidate set from the previously recorded
5823 // potentially viable conversions.
5824 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5825 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5826 CandidateSet);
5827
5828 // Then, perform overload resolution over the candidate set.
5829 OverloadCandidateSet::iterator Best;
5830 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5831 case OR_Success: {
5832 // Apply this conversion.
5833 DeclAccessPair Found =
5834 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5835 if (recordConversion(*this, Loc, From, Converter, T,
5836 HadMultipleCandidates, Found))
5837 return ExprError();
5838 break;
5839 }
5840 case OR_Ambiguous:
5841 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5842 ViableConversions);
5843 case OR_No_Viable_Function:
5844 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5845 HadMultipleCandidates,
5846 ExplicitConversions))
5847 return ExprError();
5848 LLVM_FALLTHROUGH[[clang::fallthrough]];
5849 case OR_Deleted:
5850 // We'll complain below about a non-integral condition type.
5851 break;
5852 }
5853 } else {
5854 switch (ViableConversions.size()) {
5855 case 0: {
5856 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5857 HadMultipleCandidates,
5858 ExplicitConversions))
5859 return ExprError();
5860
5861 // We'll complain below about a non-integral condition type.
5862 break;
5863 }
5864 case 1: {
5865 // Apply this conversion.
5866 DeclAccessPair Found = ViableConversions[0];
5867 if (recordConversion(*this, Loc, From, Converter, T,
5868 HadMultipleCandidates, Found))
5869 return ExprError();
5870 break;
5871 }
5872 default:
5873 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5874 ViableConversions);
5875 }
5876 }
5877
5878 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5879}
5880
5881/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5882/// an acceptable non-member overloaded operator for a call whose
5883/// arguments have types T1 (and, if non-empty, T2). This routine
5884/// implements the check in C++ [over.match.oper]p3b2 concerning
5885/// enumeration types.
5886static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5887 FunctionDecl *Fn,
5888 ArrayRef<Expr *> Args) {
5889 QualType T1 = Args[0]->getType();
5890 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5891
5892 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5893 return true;
5894
5895 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5896 return true;
5897
5898 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5899 if (Proto->getNumParams() < 1)
5900 return false;
5901
5902 if (T1->isEnumeralType()) {
5903 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5904 if (Context.hasSameUnqualifiedType(T1, ArgType))
5905 return true;
5906 }
5907
5908 if (Proto->getNumParams() < 2)
5909 return false;
5910
5911 if (!T2.isNull() && T2->isEnumeralType()) {
5912 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5913 if (Context.hasSameUnqualifiedType(T2, ArgType))
5914 return true;
5915 }
5916
5917 return false;
5918}
5919
5920/// AddOverloadCandidate - Adds the given function to the set of
5921/// candidate functions, using the given function call arguments. If
5922/// @p SuppressUserConversions, then don't allow user-defined
5923/// conversions via constructors or conversion operators.
5924///
5925/// \param PartialOverloading true if we are performing "partial" overloading
5926/// based on an incomplete set of function arguments. This feature is used by
5927/// code completion.
5928void
5929Sema::AddOverloadCandidate(FunctionDecl *Function,
5930 DeclAccessPair FoundDecl,
5931 ArrayRef<Expr *> Args,
5932 OverloadCandidateSet &CandidateSet,
5933 bool SuppressUserConversions,
5934 bool PartialOverloading,
5935 bool AllowExplicit,
5936 ConversionSequenceList EarlyConversions) {
5937 const FunctionProtoType *Proto
5938 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5939 assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Functions without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5939, __extension__ __PRETTY_FUNCTION__))
;
5940 assert(!Function->getDescribedFunctionTemplate() &&(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use Add