Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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-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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp

1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/CXXInheritance.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/DependenceFlags.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeOrdering.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/Optional.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallPtrSet.h"
36#include "llvm/ADT/SmallString.h"
37#include <algorithm>
38#include <cstdlib>
39
40using namespace clang;
41using namespace sema;
42
43using AllowedExplicit = Sema::AllowedExplicit;
44
45static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47 return P->hasAttr<PassObjectSizeAttr>();
48 });
49}
50
51/// A convenience routine for creating a decayed reference to a function.
52static ExprResult
53CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54 const Expr *Base, bool HadMultipleCandidates,
55 SourceLocation Loc = SourceLocation(),
56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58 return ExprError();
59 // If FoundDecl is different from Fn (such as if one is a template
60 // and the other a specialization), make sure DiagnoseUseOfDecl is
61 // called on both.
62 // FIXME: This would be more comprehensively addressed by modifying
63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64 // being used.
65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66 return ExprError();
67 DeclRefExpr *DRE = new (S.Context)
68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69 if (HadMultipleCandidates)
70 DRE->setHadMultipleCandidates(true);
71
72 S.MarkDeclRefReferenced(DRE, Base);
73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75 S.ResolveExceptionSpec(Loc, FPT);
76 DRE->setType(Fn->getType());
77 }
78 }
79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80 CK_FunctionToPointerDecay);
81}
82
83static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle,
87 bool AllowObjCWritebackConversion);
88
89static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90 QualType &ToType,
91 bool InOverloadResolution,
92 StandardConversionSequence &SCS,
93 bool CStyle);
94static OverloadingResult
95IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96 UserDefinedConversionSequence& User,
97 OverloadCandidateSet& Conversions,
98 AllowedExplicit AllowExplicit,
99 bool AllowObjCConversionOnExplicit);
100
101static ImplicitConversionSequence::CompareKind
102CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
106static ImplicitConversionSequence::CompareKind
107CompareQualificationConversions(Sema &S,
108 const StandardConversionSequence& SCS1,
109 const StandardConversionSequence& SCS2);
110
111static ImplicitConversionSequence::CompareKind
112CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113 const StandardConversionSequence& SCS1,
114 const StandardConversionSequence& SCS2);
115
116/// GetConversionRank - Retrieve the implicit conversion rank
117/// corresponding to the given implicit conversion kind.
118ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119 static const ImplicitConversionRank
120 Rank[(int)ICK_Num_Conversion_Kinds] = {
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Promotion,
128 ICR_Promotion,
129 ICR_Promotion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_OCL_Scalar_Widening,
142 ICR_Complex_Real_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Writeback_Conversion,
146 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147 // it was omitted by the patch that added
148 // ICK_Zero_Event_Conversion
149 ICR_C_Conversion,
150 ICR_C_Conversion_Extension
151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
163 "Function pointer conversion",
164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
167 "Complex promotion",
168 "Integral conversion",
169 "Floating conversion",
170 "Complex conversion",
171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
174 "Boolean conversion",
175 "Compatible-types conversion",
176 "Derived-to-base conversion",
177 "Vector conversion",
178 "SVE Vector conversion",
179 "Vector splat",
180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion",
183 "Writeback conversion",
184 "OpenCL Zero Event Conversion",
185 "C specific type conversion",
186 "Incompatible pointer conversion"
187 };
188 return Name[Kind];
189}
190
191/// StandardConversionSequence - Set the standard conversion
192/// sequence to the identity conversion.
193void StandardConversionSequence::setAsIdentityConversion() {
194 First = ICK_Identity;
195 Second = ICK_Identity;
196 Third = ICK_Identity;
197 DeprecatedStringLiteralToCharPtr = false;
198 QualificationIncludesObjCLifetime = false;
199 ReferenceBinding = false;
200 DirectBinding = false;
201 IsLvalueReference = true;
202 BindsToFunctionLvalue = false;
203 BindsToRvalue = false;
204 BindsImplicitObjectArgumentWithoutRefQualifier = false;
205 ObjCLifetimeConversionBinding = false;
206 CopyConstructor = nullptr;
207}
208
209/// getRank - Retrieve the rank of this standard conversion sequence
210/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211/// implicit conversions.
212ImplicitConversionRank StandardConversionSequence::getRank() const {
213 ImplicitConversionRank Rank = ICR_Exact_Match;
214 if (GetConversionRank(First) > Rank)
215 Rank = GetConversionRank(First);
216 if (GetConversionRank(Second) > Rank)
217 Rank = GetConversionRank(Second);
218 if (GetConversionRank(Third) > Rank)
219 Rank = GetConversionRank(Third);
220 return Rank;
221}
222
223/// isPointerConversionToBool - Determines whether this conversion is
224/// a conversion of a pointer or pointer-to-member to bool. This is
225/// used as part of the ranking of standard conversion sequences
226/// (C++ 13.3.3.2p4).
227bool StandardConversionSequence::isPointerConversionToBool() const {
228 // Note that FromType has not necessarily been transformed by the
229 // array-to-pointer or function-to-pointer implicit conversions, so
230 // check for their presence as well as checking whether FromType is
231 // a pointer.
232 if (getToType(1)->isBooleanType() &&
233 (getFromType()->isPointerType() ||
234 getFromType()->isMemberPointerType() ||
235 getFromType()->isObjCObjectPointerType() ||
236 getFromType()->isBlockPointerType() ||
237 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238 return true;
239
240 return false;
241}
242
243/// isPointerConversionToVoidPointer - Determines whether this
244/// conversion is a conversion of a pointer to a void pointer. This is
245/// used as part of the ranking of standard conversion sequences (C++
246/// 13.3.3.2p4).
247bool
248StandardConversionSequence::
249isPointerConversionToVoidPointer(ASTContext& Context) const {
250 QualType FromType = getFromType();
251 QualType ToType = getToType(1);
252
253 // Note that FromType has not necessarily been transformed by the
254 // array-to-pointer implicit conversion, so check for its presence
255 // and redo the conversion to get a pointer.
256 if (First == ICK_Array_To_Pointer)
257 FromType = Context.getArrayDecayedType(FromType);
258
259 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261 return ToPtrType->getPointeeType()->isVoidType();
262
263 return false;
264}
265
266/// Skip any implicit casts which could be either part of a narrowing conversion
267/// or after one in an implicit conversion.
268static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269 const Expr *Converted) {
270 // We can have cleanups wrapping the converted expression; these need to be
271 // preserved so that destructors run if necessary.
272 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273 Expr *Inner =
274 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276 EWC->getObjects());
277 }
278
279 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_BooleanToSignedIntegral:
286 case CK_FloatingToIntegral:
287 case CK_FloatingToBoolean:
288 case CK_FloatingCast:
289 Converted = ICE->getSubExpr();
290 continue;
291
292 default:
293 return Converted;
294 }
295 }
296
297 return Converted;
298}
299
300/// Check if this standard conversion sequence represents a narrowing
301/// conversion, according to C++11 [dcl.init.list]p7.
302///
303/// \param Ctx The AST context.
304/// \param Converted The result of applying this standard conversion sequence.
305/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
306/// value of the expression prior to the narrowing conversion.
307/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
308/// type of the expression prior to the narrowing conversion.
309/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310/// from floating point types to integral types should be ignored.
311NarrowingKind StandardConversionSequence::getNarrowingKind(
312 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 314, __PRETTY_FUNCTION__))
;
315
316 // C++11 [dcl.init.list]p7:
317 // A narrowing conversion is an implicit conversion ...
318 QualType FromType = getToType(0);
319 QualType ToType = getToType(1);
320
321 // A conversion to an enumeration type is narrowing if the conversion to
322 // the underlying type is narrowing. This only arises for expressions of
323 // the form 'Enum{init}'.
324 if (auto *ET = ToType->getAs<EnumType>())
325 ToType = ET->getDecl()->getIntegerType();
326
327 switch (Second) {
328 // 'bool' is an integral type; dispatch to the right place to handle it.
329 case ICK_Boolean_Conversion:
330 if (FromType->isRealFloatingType())
331 goto FloatingIntegralConversion;
332 if (FromType->isIntegralOrUnscopedEnumerationType())
333 goto IntegralConversion;
334 // -- from a pointer type or pointer-to-member type to bool, or
335 return NK_Type_Narrowing;
336
337 // -- from a floating-point type to an integer type, or
338 //
339 // -- from an integer type or unscoped enumeration type to a floating-point
340 // type, except where the source is a constant expression and the actual
341 // value after conversion will fit into the target type and will produce
342 // the original value when converted back to the original type, or
343 case ICK_Floating_Integral:
344 FloatingIntegralConversion:
345 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346 return NK_Type_Narrowing;
347 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348 ToType->isRealFloatingType()) {
349 if (IgnoreFloatToIntegralConversion)
350 return NK_Not_Narrowing;
351 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352 assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 352, __PRETTY_FUNCTION__))
;
353
354 // If it's value-dependent, we can't tell whether it's narrowing.
355 if (Initializer->isValueDependent())
356 return NK_Dependent_Narrowing;
357
358 if (Optional<llvm::APSInt> IntConstantValue =
359 Initializer->getIntegerConstantExpr(Ctx)) {
360 // Convert the integer to the floating type.
361 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363 llvm::APFloat::rmNearestTiesToEven);
364 // And back.
365 llvm::APSInt ConvertedValue = *IntConstantValue;
366 bool ignored;
367 Result.convertToInteger(ConvertedValue,
368 llvm::APFloat::rmTowardZero, &ignored);
369 // If the resulting value is different, this was a narrowing conversion.
370 if (*IntConstantValue != ConvertedValue) {
371 ConstantValue = APValue(*IntConstantValue);
372 ConstantType = Initializer->getType();
373 return NK_Constant_Narrowing;
374 }
375 } else {
376 // Variables are always narrowings.
377 return NK_Variable_Narrowing;
378 }
379 }
380 return NK_Not_Narrowing;
381
382 // -- from long double to double or float, or from double to float, except
383 // where the source is a constant expression and the actual value after
384 // conversion is within the range of values that can be represented (even
385 // if it cannot be represented exactly), or
386 case ICK_Floating_Conversion:
387 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389 // FromType is larger than ToType.
390 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391
392 // If it's value-dependent, we can't tell whether it's narrowing.
393 if (Initializer->isValueDependent())
394 return NK_Dependent_Narrowing;
395
396 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397 // Constant!
398 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 398, __PRETTY_FUNCTION__))
;
399 llvm::APFloat FloatVal = ConstantValue.getFloat();
400 // Convert the source value into the target type.
401 bool ignored;
402 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403 Ctx.getFloatTypeSemantics(ToType),
404 llvm::APFloat::rmNearestTiesToEven, &ignored);
405 // If there was no overflow, the source value is within the range of
406 // values that can be represented.
407 if (ConvertStatus & llvm::APFloat::opOverflow) {
408 ConstantType = Initializer->getType();
409 return NK_Constant_Narrowing;
410 }
411 } else {
412 return NK_Variable_Narrowing;
413 }
414 }
415 return NK_Not_Narrowing;
416
417 // -- from an integer type or unscoped enumeration type to an integer type
418 // that cannot represent all the values of the original type, except where
419 // the source is a constant expression and the actual value after
420 // conversion will fit into the target type and will produce the original
421 // value when converted back to the original type.
422 case ICK_Integral_Conversion:
423 IntegralConversion: {
424 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 424, __PRETTY_FUNCTION__))
;
425 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 425, __PRETTY_FUNCTION__))
;
426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427 const unsigned FromWidth = Ctx.getIntWidth(FromType);
428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429 const unsigned ToWidth = Ctx.getIntWidth(ToType);
430
431 if (FromWidth > ToWidth ||
432 (FromWidth == ToWidth && FromSigned != ToSigned) ||
433 (FromSigned && !ToSigned)) {
434 // Not all values of FromType can be represented in ToType.
435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436
437 // If it's value-dependent, we can't tell whether it's narrowing.
438 if (Initializer->isValueDependent())
439 return NK_Dependent_Narrowing;
440
441 Optional<llvm::APSInt> OptInitializerValue;
442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443 // Such conversions on variables are always narrowing.
444 return NK_Variable_Narrowing;
445 }
446 llvm::APSInt &InitializerValue = *OptInitializerValue;
447 bool Narrowing = false;
448 if (FromWidth < ToWidth) {
449 // Negative -> unsigned is narrowing. Otherwise, more bits is never
450 // narrowing.
451 if (InitializerValue.isSigned() && InitializerValue.isNegative())
452 Narrowing = true;
453 } else {
454 // Add a bit to the InitializerValue so we don't have to worry about
455 // signed vs. unsigned comparisons.
456 InitializerValue = InitializerValue.extend(
457 InitializerValue.getBitWidth() + 1);
458 // Convert the initializer to and from the target width and signed-ness.
459 llvm::APSInt ConvertedValue = InitializerValue;
460 ConvertedValue = ConvertedValue.trunc(ToWidth);
461 ConvertedValue.setIsSigned(ToSigned);
462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463 ConvertedValue.setIsSigned(InitializerValue.isSigned());
464 // If the result is different, this was a narrowing conversion.
465 if (ConvertedValue != InitializerValue)
466 Narrowing = true;
467 }
468 if (Narrowing) {
469 ConstantType = Initializer->getType();
470 ConstantValue = APValue(InitializerValue);
471 return NK_Constant_Narrowing;
472 }
473 }
474 return NK_Not_Narrowing;
475 }
476
477 default:
478 // Other kinds of conversions are not narrowings.
479 return NK_Not_Narrowing;
480 }
481}
482
483/// dump - Print this standard conversion sequence to standard
484/// error. Useful for debugging overloading issues.
485LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
486 raw_ostream &OS = llvm::errs();
487 bool PrintedSomething = false;
488 if (First != ICK_Identity) {
489 OS << GetImplicitConversionName(First);
490 PrintedSomething = true;
491 }
492
493 if (Second != ICK_Identity) {
494 if (PrintedSomething) {
495 OS << " -> ";
496 }
497 OS << GetImplicitConversionName(Second);
498
499 if (CopyConstructor) {
500 OS << " (by copy constructor)";
501 } else if (DirectBinding) {
502 OS << " (direct reference binding)";
503 } else if (ReferenceBinding) {
504 OS << " (reference binding)";
505 }
506 PrintedSomething = true;
507 }
508
509 if (Third != ICK_Identity) {
510 if (PrintedSomething) {
511 OS << " -> ";
512 }
513 OS << GetImplicitConversionName(Third);
514 PrintedSomething = true;
515 }
516
517 if (!PrintedSomething) {
518 OS << "No conversions required";
519 }
520}
521
522/// dump - Print this user-defined conversion sequence to standard
523/// error. Useful for debugging overloading issues.
524void UserDefinedConversionSequence::dump() const {
525 raw_ostream &OS = llvm::errs();
526 if (Before.First || Before.Second || Before.Third) {
527 Before.dump();
528 OS << " -> ";
529 }
530 if (ConversionFunction)
531 OS << '\'' << *ConversionFunction << '\'';
532 else
533 OS << "aggregate initialization";
534 if (After.First || After.Second || After.Third) {
535 OS << " -> ";
536 After.dump();
537 }
538}
539
540/// dump - Print this implicit conversion sequence to standard
541/// error. Useful for debugging overloading issues.
542void ImplicitConversionSequence::dump() const {
543 raw_ostream &OS = llvm::errs();
544 if (isStdInitializerListElement())
545 OS << "Worst std::initializer_list element conversion: ";
546 switch (ConversionKind) {
547 case StandardConversion:
548 OS << "Standard conversion: ";
549 Standard.dump();
550 break;
551 case UserDefinedConversion:
552 OS << "User-defined conversion: ";
553 UserDefined.dump();
554 break;
555 case EllipsisConversion:
556 OS << "Ellipsis conversion";
557 break;
558 case AmbiguousConversion:
559 OS << "Ambiguous conversion";
560 break;
561 case BadConversion:
562 OS << "Bad conversion";
563 break;
564 }
565
566 OS << "\n";
567}
568
569void AmbiguousConversionSequence::construct() {
570 new (&conversions()) ConversionSet();
571}
572
573void AmbiguousConversionSequence::destruct() {
574 conversions().~ConversionSet();
575}
576
577void
578AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579 FromTypePtr = O.FromTypePtr;
580 ToTypePtr = O.ToTypePtr;
581 new (&conversions()) ConversionSet(O.conversions());
582}
583
584namespace {
585 // Structure used by DeductionFailureInfo to store
586 // template argument information.
587 struct DFIArguments {
588 TemplateArgument FirstArg;
589 TemplateArgument SecondArg;
590 };
591 // Structure used by DeductionFailureInfo to store
592 // template parameter and template argument information.
593 struct DFIParamWithArguments : DFIArguments {
594 TemplateParameter Param;
595 };
596 // Structure used by DeductionFailureInfo to store template argument
597 // information and the index of the problematic call argument.
598 struct DFIDeducedMismatchArgs : DFIArguments {
599 TemplateArgumentList *TemplateArgs;
600 unsigned CallArgIndex;
601 };
602 // Structure used by DeductionFailureInfo to store information about
603 // unsatisfied constraints.
604 struct CNSInfo {
605 TemplateArgumentList *TemplateArgs;
606 ConstraintSatisfaction Satisfaction;
607 };
608}
609
610/// Convert from Sema's representation of template deduction information
611/// to the form used in overload-candidate information.
612DeductionFailureInfo
613clang::MakeDeductionFailureInfo(ASTContext &Context,
614 Sema::TemplateDeductionResult TDK,
615 TemplateDeductionInfo &Info) {
616 DeductionFailureInfo Result;
617 Result.Result = static_cast<unsigned>(TDK);
618 Result.HasDiagnostic = false;
619 switch (TDK) {
620 case Sema::TDK_Invalid:
621 case Sema::TDK_InstantiationDepth:
622 case Sema::TDK_TooManyArguments:
623 case Sema::TDK_TooFewArguments:
624 case Sema::TDK_MiscellaneousDeductionFailure:
625 case Sema::TDK_CUDATargetMismatch:
626 Result.Data = nullptr;
627 break;
628
629 case Sema::TDK_Incomplete:
630 case Sema::TDK_InvalidExplicitArguments:
631 Result.Data = Info.Param.getOpaqueValue();
632 break;
633
634 case Sema::TDK_DeducedMismatch:
635 case Sema::TDK_DeducedMismatchNested: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 auto *Saved = new (Context) DFIDeducedMismatchArgs;
638 Saved->FirstArg = Info.FirstArg;
639 Saved->SecondArg = Info.SecondArg;
640 Saved->TemplateArgs = Info.take();
641 Saved->CallArgIndex = Info.CallArgIndex;
642 Result.Data = Saved;
643 break;
644 }
645
646 case Sema::TDK_NonDeducedMismatch: {
647 // FIXME: Should allocate from normal heap so that we can free this later.
648 DFIArguments *Saved = new (Context) DFIArguments;
649 Saved->FirstArg = Info.FirstArg;
650 Saved->SecondArg = Info.SecondArg;
651 Result.Data = Saved;
652 break;
653 }
654
655 case Sema::TDK_IncompletePack:
656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657 case Sema::TDK_Inconsistent:
658 case Sema::TDK_Underqualified: {
659 // FIXME: Should allocate from normal heap so that we can free this later.
660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661 Saved->Param = Info.Param;
662 Saved->FirstArg = Info.FirstArg;
663 Saved->SecondArg = Info.SecondArg;
664 Result.Data = Saved;
665 break;
666 }
667
668 case Sema::TDK_SubstitutionFailure:
669 Result.Data = Info.take();
670 if (Info.hasSFINAEDiagnostic()) {
671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672 SourceLocation(), PartialDiagnostic::NullDiagnostic());
673 Info.takeSFINAEDiagnostic(*Diag);
674 Result.HasDiagnostic = true;
675 }
676 break;
677
678 case Sema::TDK_ConstraintsNotSatisfied: {
679 CNSInfo *Saved = new (Context) CNSInfo;
680 Saved->TemplateArgs = Info.take();
681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682 Result.Data = Saved;
683 break;
684 }
685
686 case Sema::TDK_Success:
687 case Sema::TDK_NonDependentConversionFailure:
688 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 688)
;
689 }
690
691 return Result;
692}
693
694void DeductionFailureInfo::Destroy() {
695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696 case Sema::TDK_Success:
697 case Sema::TDK_Invalid:
698 case Sema::TDK_InstantiationDepth:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
702 case Sema::TDK_InvalidExplicitArguments:
703 case Sema::TDK_CUDATargetMismatch:
704 case Sema::TDK_NonDependentConversionFailure:
705 break;
706
707 case Sema::TDK_IncompletePack:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_DeducedMismatch:
711 case Sema::TDK_DeducedMismatchNested:
712 case Sema::TDK_NonDeducedMismatch:
713 // FIXME: Destroy the data?
714 Data = nullptr;
715 break;
716
717 case Sema::TDK_SubstitutionFailure:
718 // FIXME: Destroy the template argument list?
719 Data = nullptr;
720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721 Diag->~PartialDiagnosticAt();
722 HasDiagnostic = false;
723 }
724 break;
725
726 case Sema::TDK_ConstraintsNotSatisfied:
727 // FIXME: Destroy the template argument list?
728 Data = nullptr;
729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730 Diag->~PartialDiagnosticAt();
731 HasDiagnostic = false;
732 }
733 break;
734
735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 break;
738 }
739}
740
741PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742 if (HasDiagnostic)
743 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744 return nullptr;
745}
746
747TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749 case Sema::TDK_Success:
750 case Sema::TDK_Invalid:
751 case Sema::TDK_InstantiationDepth:
752 case Sema::TDK_TooManyArguments:
753 case Sema::TDK_TooFewArguments:
754 case Sema::TDK_SubstitutionFailure:
755 case Sema::TDK_DeducedMismatch:
756 case Sema::TDK_DeducedMismatchNested:
757 case Sema::TDK_NonDeducedMismatch:
758 case Sema::TDK_CUDATargetMismatch:
759 case Sema::TDK_NonDependentConversionFailure:
760 case Sema::TDK_ConstraintsNotSatisfied:
761 return TemplateParameter();
762
763 case Sema::TDK_Incomplete:
764 case Sema::TDK_InvalidExplicitArguments:
765 return TemplateParameter::getFromOpaqueValue(Data);
766
767 case Sema::TDK_IncompletePack:
768 case Sema::TDK_Inconsistent:
769 case Sema::TDK_Underqualified:
770 return static_cast<DFIParamWithArguments*>(Data)->Param;
771
772 // Unhandled
773 case Sema::TDK_MiscellaneousDeductionFailure:
774 break;
775 }
776
777 return TemplateParameter();
778}
779
780TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782 case Sema::TDK_Success:
783 case Sema::TDK_Invalid:
784 case Sema::TDK_InstantiationDepth:
785 case Sema::TDK_TooManyArguments:
786 case Sema::TDK_TooFewArguments:
787 case Sema::TDK_Incomplete:
788 case Sema::TDK_IncompletePack:
789 case Sema::TDK_InvalidExplicitArguments:
790 case Sema::TDK_Inconsistent:
791 case Sema::TDK_Underqualified:
792 case Sema::TDK_NonDeducedMismatch:
793 case Sema::TDK_CUDATargetMismatch:
794 case Sema::TDK_NonDependentConversionFailure:
795 return nullptr;
796
797 case Sema::TDK_DeducedMismatch:
798 case Sema::TDK_DeducedMismatchNested:
799 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800
801 case Sema::TDK_SubstitutionFailure:
802 return static_cast<TemplateArgumentList*>(Data);
803
804 case Sema::TDK_ConstraintsNotSatisfied:
805 return static_cast<CNSInfo*>(Data)->TemplateArgs;
806
807 // Unhandled
808 case Sema::TDK_MiscellaneousDeductionFailure:
809 break;
810 }
811
812 return nullptr;
813}
814
815const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817 case Sema::TDK_Success:
818 case Sema::TDK_Invalid:
819 case Sema::TDK_InstantiationDepth:
820 case Sema::TDK_Incomplete:
821 case Sema::TDK_TooManyArguments:
822 case Sema::TDK_TooFewArguments:
823 case Sema::TDK_InvalidExplicitArguments:
824 case Sema::TDK_SubstitutionFailure:
825 case Sema::TDK_CUDATargetMismatch:
826 case Sema::TDK_NonDependentConversionFailure:
827 case Sema::TDK_ConstraintsNotSatisfied:
828 return nullptr;
829
830 case Sema::TDK_IncompletePack:
831 case Sema::TDK_Inconsistent:
832 case Sema::TDK_Underqualified:
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
835 case Sema::TDK_NonDeducedMismatch:
836 return &static_cast<DFIArguments*>(Data)->FirstArg;
837
838 // Unhandled
839 case Sema::TDK_MiscellaneousDeductionFailure:
840 break;
841 }
842
843 return nullptr;
844}
845
846const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848 case Sema::TDK_Success:
849 case Sema::TDK_Invalid:
850 case Sema::TDK_InstantiationDepth:
851 case Sema::TDK_Incomplete:
852 case Sema::TDK_IncompletePack:
853 case Sema::TDK_TooManyArguments:
854 case Sema::TDK_TooFewArguments:
855 case Sema::TDK_InvalidExplicitArguments:
856 case Sema::TDK_SubstitutionFailure:
857 case Sema::TDK_CUDATargetMismatch:
858 case Sema::TDK_NonDependentConversionFailure:
859 case Sema::TDK_ConstraintsNotSatisfied:
860 return nullptr;
861
862 case Sema::TDK_Inconsistent:
863 case Sema::TDK_Underqualified:
864 case Sema::TDK_DeducedMismatch:
865 case Sema::TDK_DeducedMismatchNested:
866 case Sema::TDK_NonDeducedMismatch:
867 return &static_cast<DFIArguments*>(Data)->SecondArg;
868
869 // Unhandled
870 case Sema::TDK_MiscellaneousDeductionFailure:
871 break;
872 }
873
874 return nullptr;
875}
876
877llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879 case Sema::TDK_DeducedMismatch:
880 case Sema::TDK_DeducedMismatchNested:
881 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882
883 default:
884 return llvm::None;
885 }
886}
887
888bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889 OverloadedOperatorKind Op) {
890 if (!AllowRewrittenCandidates)
891 return false;
892 return Op == OO_EqualEqual || Op == OO_Spaceship;
893}
894
895bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896 ASTContext &Ctx, const FunctionDecl *FD) {
897 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898 return false;
899 // Don't bother adding a reversed candidate that can never be a better
900 // match than the non-reversed version.
901 return FD->getNumParams() != 2 ||
902 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903 FD->getParamDecl(1)->getType()) ||
904 FD->hasAttr<EnableIfAttr>();
905}
906
907void OverloadCandidateSet::destroyCandidates() {
908 for (iterator i = begin(), e = end(); i != e; ++i) {
909 for (auto &C : i->Conversions)
910 C.~ImplicitConversionSequence();
911 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912 i->DeductionFailure.Destroy();
913 }
914}
915
916void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917 destroyCandidates();
918 SlabAllocator.Reset();
919 NumInlineBytesUsed = 0;
920 Candidates.clear();
921 Functions.clear();
922 Kind = CSK;
923}
924
925namespace {
926 class UnbridgedCastsSet {
927 struct Entry {
928 Expr **Addr;
929 Expr *Saved;
930 };
931 SmallVector<Entry, 2> Entries;
932
933 public:
934 void save(Sema &S, Expr *&E) {
935 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 935, __PRETTY_FUNCTION__))
;
936 Entry entry = { &E, E };
937 Entries.push_back(entry);
938 E = S.stripARCUnbridgedCast(E);
939 }
940
941 void restore() {
942 for (SmallVectorImpl<Entry>::iterator
943 i = Entries.begin(), e = Entries.end(); i != e; ++i)
944 *i->Addr = i->Saved;
945 }
946 };
947}
948
949/// checkPlaceholderForOverload - Do any interesting placeholder-like
950/// preprocessing on the given expression.
951///
952/// \param unbridgedCasts a collection to which to add unbridged casts;
953/// without this, they will be immediately diagnosed as errors
954///
955/// Return true on unrecoverable error.
956static bool
957checkPlaceholderForOverload(Sema &S, Expr *&E,
958 UnbridgedCastsSet *unbridgedCasts = nullptr) {
959 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
960 // We can't handle overloaded expressions here because overload
961 // resolution might reasonably tweak them.
962 if (placeholder->getKind() == BuiltinType::Overload) return false;
963
964 // If the context potentially accepts unbridged ARC casts, strip
965 // the unbridged cast and add it to the collection for later restoration.
966 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967 unbridgedCasts) {
968 unbridgedCasts->save(S, E);
969 return false;
970 }
971
972 // Go ahead and check everything else.
973 ExprResult result = S.CheckPlaceholderExpr(E);
974 if (result.isInvalid())
975 return true;
976
977 E = result.get();
978 return false;
979 }
980
981 // Nothing to do.
982 return false;
983}
984
985/// checkArgPlaceholdersForOverload - Check a set of call operands for
986/// placeholders.
987static bool checkArgPlaceholdersForOverload(Sema &S,
988 MultiExprArg Args,
989 UnbridgedCastsSet &unbridged) {
990 for (unsigned i = 0, e = Args.size(); i != e; ++i)
991 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992 return true;
993
994 return false;
995}
996
997/// Determine whether the given New declaration is an overload of the
998/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999/// New and Old cannot be overloaded, e.g., if New has the same signature as
1000/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001/// functions (or function templates) at all. When it does return Ovl_Match or
1002/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004/// declaration.
1005///
1006/// Example: Given the following input:
1007///
1008/// void f(int, float); // #1
1009/// void f(int, int); // #2
1010/// int f(int, int); // #3
1011///
1012/// When we process #1, there is no previous declaration of "f", so IsOverload
1013/// will not be used.
1014///
1015/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016/// the parameter types, we see that #1 and #2 are overloaded (since they have
1017/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018/// unchanged.
1019///
1020/// When we process #3, Old is an overload set containing #1 and #2. We compare
1021/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023/// functions are not part of the signature), IsOverload returns Ovl_Match and
1024/// MatchedDecl will be set to point to the FunctionDecl for #2.
1025///
1026/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027/// by a using declaration. The rules for whether to hide shadow declarations
1028/// ignore some properties which otherwise figure into a function template's
1029/// signature.
1030Sema::OverloadKind
1031Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032 NamedDecl *&Match, bool NewIsUsingDecl) {
1033 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034 I != E; ++I) {
1035 NamedDecl *OldD = *I;
1036
1037 bool OldIsUsingDecl = false;
1038 if (isa<UsingShadowDecl>(OldD)) {
1039 OldIsUsingDecl = true;
1040
1041 // We can always introduce two using declarations into the same
1042 // context, even if they have identical signatures.
1043 if (NewIsUsingDecl) continue;
1044
1045 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046 }
1047
1048 // A using-declaration does not conflict with another declaration
1049 // if one of them is hidden.
1050 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1051 continue;
1052
1053 // If either declaration was introduced by a using declaration,
1054 // we'll need to use slightly different rules for matching.
1055 // Essentially, these rules are the normal rules, except that
1056 // function templates hide function templates with different
1057 // return types or template parameter lists.
1058 bool UseMemberUsingDeclRules =
1059 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1060 !New->getFriendObjectKind();
1061
1062 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1065 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066 continue;
1067 }
1068
1069 if (!isa<FunctionTemplateDecl>(OldD) &&
1070 !shouldLinkPossiblyHiddenDecl(*I, New))
1071 continue;
1072
1073 Match = *I;
1074 return Ovl_Match;
1075 }
1076
1077 // Builtins that have custom typechecking or have a reference should
1078 // not be overloadable or redeclarable.
1079 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080 Match = *I;
1081 return Ovl_NonFunction;
1082 }
1083 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1084 // We can overload with these, which can show up when doing
1085 // redeclaration checks for UsingDecls.
1086 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1086, __PRETTY_FUNCTION__))
;
1087 } else if (isa<TagDecl>(OldD)) {
1088 // We can always overload with tags by hiding them.
1089 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090 // Optimistically assume that an unresolved using decl will
1091 // overload; if it doesn't, we'll have to diagnose during
1092 // template instantiation.
1093 //
1094 // Exception: if the scope is dependent and this is not a class
1095 // member, the using declaration can only introduce an enumerator.
1096 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097 Match = *I;
1098 return Ovl_NonFunction;
1099 }
1100 } else {
1101 // (C++ 13p1):
1102 // Only function declarations can be overloaded; object and type
1103 // declarations cannot be overloaded.
1104 Match = *I;
1105 return Ovl_NonFunction;
1106 }
1107 }
1108
1109 // C++ [temp.friend]p1:
1110 // For a friend function declaration that is not a template declaration:
1111 // -- if the name of the friend is a qualified or unqualified template-id,
1112 // [...], otherwise
1113 // -- if the name of the friend is a qualified-id and a matching
1114 // non-template function is found in the specified class or namespace,
1115 // the friend declaration refers to that function, otherwise,
1116 // -- if the name of the friend is a qualified-id and a matching function
1117 // template is found in the specified class or namespace, the friend
1118 // declaration refers to the deduced specialization of that function
1119 // template, otherwise
1120 // -- the name shall be an unqualified-id [...]
1121 // If we get here for a qualified friend declaration, we've just reached the
1122 // third bullet. If the type of the friend is dependent, skip this lookup
1123 // until instantiation.
1124 if (New->getFriendObjectKind() && New->getQualifier() &&
1125 !New->getDescribedFunctionTemplate() &&
1126 !New->getDependentSpecializationInfo() &&
1127 !New->getType()->isDependentType()) {
1128 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129 TemplateSpecResult.addAllDecls(Old);
1130 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131 /*QualifiedFriend*/true)) {
1132 New->setInvalidDecl();
1133 return Ovl_Overload;
1134 }
1135
1136 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137 return Ovl_Match;
1138 }
1139
1140 return Ovl_Overload;
1141}
1142
1143bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145 bool ConsiderRequiresClauses) {
1146 // C++ [basic.start.main]p2: This function shall not be overloaded.
1147 if (New->isMain())
1148 return false;
1149
1150 // MSVCRT user defined entry points cannot be overloaded.
1151 if (New->isMSVCRTEntryPoint())
1152 return false;
1153
1154 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156
1157 // C++ [temp.fct]p2:
1158 // A function template can be overloaded with other function templates
1159 // and with normal (non-template) functions.
1160 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161 return true;
1162
1163 // Is the function New an overload of the function Old?
1164 QualType OldQType = Context.getCanonicalType(Old->getType());
1165 QualType NewQType = Context.getCanonicalType(New->getType());
1166
1167 // Compare the signatures (C++ 1.3.10) of the two functions to
1168 // determine whether they are overloads. If we find any mismatch
1169 // in the signature, they are overloads.
1170
1171 // If either of these functions is a K&R-style function (no
1172 // prototype), then we consider them to have matching signatures.
1173 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175 return false;
1176
1177 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179
1180 // The signature of a function includes the types of its
1181 // parameters (C++ 1.3.10), which includes the presence or absence
1182 // of the ellipsis; see C++ DR 357).
1183 if (OldQType != NewQType &&
1184 (OldType->getNumParams() != NewType->getNumParams() ||
1185 OldType->isVariadic() != NewType->isVariadic() ||
1186 !FunctionParamTypesAreEqual(OldType, NewType)))
1187 return true;
1188
1189 // C++ [temp.over.link]p4:
1190 // The signature of a function template consists of its function
1191 // signature, its return type and its template parameter list. The names
1192 // of the template parameters are significant only for establishing the
1193 // relationship between the template parameters and the rest of the
1194 // signature.
1195 //
1196 // We check the return type and template parameter lists for function
1197 // templates first; the remaining checks follow.
1198 //
1199 // However, we don't consider either of these when deciding whether
1200 // a member introduced by a shadow declaration is hidden.
1201 if (!UseMemberUsingDeclRules && NewTemplate &&
1202 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203 OldTemplate->getTemplateParameters(),
1204 false, TPL_TemplateMatch) ||
1205 !Context.hasSameType(Old->getDeclaredReturnType(),
1206 New->getDeclaredReturnType())))
1207 return true;
1208
1209 // If the function is a class member, its signature includes the
1210 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211 //
1212 // As part of this, also check whether one of the member functions
1213 // is static, in which case they are not overloads (C++
1214 // 13.1p2). While not part of the definition of the signature,
1215 // this check is important to determine whether these functions
1216 // can be overloaded.
1217 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219 if (OldMethod && NewMethod &&
1220 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1221 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222 if (!UseMemberUsingDeclRules &&
1223 (OldMethod->getRefQualifier() == RQ_None ||
1224 NewMethod->getRefQualifier() == RQ_None)) {
1225 // C++0x [over.load]p2:
1226 // - Member function declarations with the same name and the same
1227 // parameter-type-list as well as member function template
1228 // declarations with the same name, the same parameter-type-list, and
1229 // the same template parameter lists cannot be overloaded if any of
1230 // them, but not all, have a ref-qualifier (8.3.5).
1231 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234 }
1235 return true;
1236 }
1237
1238 // We may not have applied the implicit const for a constexpr member
1239 // function yet (because we haven't yet resolved whether this is a static
1240 // or non-static member function). Add it now, on the assumption that this
1241 // is a redeclaration of OldMethod.
1242 auto OldQuals = OldMethod->getMethodQualifiers();
1243 auto NewQuals = NewMethod->getMethodQualifiers();
1244 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1245 !isa<CXXConstructorDecl>(NewMethod))
1246 NewQuals.addConst();
1247 // We do not allow overloading based off of '__restrict'.
1248 OldQuals.removeRestrict();
1249 NewQuals.removeRestrict();
1250 if (OldQuals != NewQuals)
1251 return true;
1252 }
1253
1254 // Though pass_object_size is placed on parameters and takes an argument, we
1255 // consider it to be a function-level modifier for the sake of function
1256 // identity. Either the function has one or more parameters with
1257 // pass_object_size or it doesn't.
1258 if (functionHasPassObjectSizeParams(New) !=
1259 functionHasPassObjectSizeParams(Old))
1260 return true;
1261
1262 // enable_if attributes are an order-sensitive part of the signature.
1263 for (specific_attr_iterator<EnableIfAttr>
1264 NewI = New->specific_attr_begin<EnableIfAttr>(),
1265 NewE = New->specific_attr_end<EnableIfAttr>(),
1266 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267 OldE = Old->specific_attr_end<EnableIfAttr>();
1268 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1269 if (NewI == NewE || OldI == OldE)
1270 return true;
1271 llvm::FoldingSetNodeID NewID, OldID;
1272 NewI->getCond()->Profile(NewID, Context, true);
1273 OldI->getCond()->Profile(OldID, Context, true);
1274 if (NewID != OldID)
1275 return true;
1276 }
1277
1278 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1279 // Don't allow overloading of destructors. (In theory we could, but it
1280 // would be a giant change to clang.)
1281 if (!isa<CXXDestructorDecl>(New)) {
1282 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283 OldTarget = IdentifyCUDATarget(Old);
1284 if (NewTarget != CFT_InvalidTarget) {
1285 assert((OldTarget != CFT_InvalidTarget) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287
1288 // Allow overloading of functions with same signature and different CUDA
1289 // target attributes.
1290 if (NewTarget != OldTarget)
1291 return true;
1292 }
1293 }
1294 }
1295
1296 if (ConsiderRequiresClauses) {
1297 Expr *NewRC = New->getTrailingRequiresClause(),
1298 *OldRC = Old->getTrailingRequiresClause();
1299 if ((NewRC != nullptr) != (OldRC != nullptr))
1300 // RC are most certainly different - these are overloads.
1301 return true;
1302
1303 if (NewRC) {
1304 llvm::FoldingSetNodeID NewID, OldID;
1305 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307 if (NewID != OldID)
1308 // RCs are not equivalent - these are overloads.
1309 return true;
1310 }
1311 }
1312
1313 // The signatures match; this is not an overload.
1314 return false;
1315}
1316
1317/// Tries a user-defined conversion from From to ToType.
1318///
1319/// Produces an implicit conversion sequence for when a standard conversion
1320/// is not an option. See TryImplicitConversion for more information.
1321static ImplicitConversionSequence
1322TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323 bool SuppressUserConversions,
1324 AllowedExplicit AllowExplicit,
1325 bool InOverloadResolution,
1326 bool CStyle,
1327 bool AllowObjCWritebackConversion,
1328 bool AllowObjCConversionOnExplicit) {
1329 ImplicitConversionSequence ICS;
1330
1331 if (SuppressUserConversions) {
1332 // We're not in the case above, so there is no conversion that
1333 // we can perform.
1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335 return ICS;
1336 }
1337
1338 // Attempt user-defined conversion.
1339 OverloadCandidateSet Conversions(From->getExprLoc(),
1340 OverloadCandidateSet::CSK_Normal);
1341 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342 Conversions, AllowExplicit,
1343 AllowObjCConversionOnExplicit)) {
1344 case OR_Success:
1345 case OR_Deleted:
1346 ICS.setUserDefined();
1347 // C++ [over.ics.user]p4:
1348 // A conversion of an expression of class type to the same class
1349 // type is given Exact Match rank, and a conversion of an
1350 // expression of class type to a base class of that type is
1351 // given Conversion rank, in spite of the fact that a copy
1352 // constructor (i.e., a user-defined conversion function) is
1353 // called for those cases.
1354 if (CXXConstructorDecl *Constructor
1355 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356 QualType FromCanon
1357 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358 QualType ToCanon
1359 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360 if (Constructor->isCopyConstructor() &&
1361 (FromCanon == ToCanon ||
1362 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363 // Turn this into a "standard" conversion sequence, so that it
1364 // gets ranked with standard conversion sequences.
1365 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366 ICS.setStandard();
1367 ICS.Standard.setAsIdentityConversion();
1368 ICS.Standard.setFromType(From->getType());
1369 ICS.Standard.setAllToTypes(ToType);
1370 ICS.Standard.CopyConstructor = Constructor;
1371 ICS.Standard.FoundCopyConstructor = Found;
1372 if (ToCanon != FromCanon)
1373 ICS.Standard.Second = ICK_Derived_To_Base;
1374 }
1375 }
1376 break;
1377
1378 case OR_Ambiguous:
1379 ICS.setAmbiguous();
1380 ICS.Ambiguous.setFromType(From->getType());
1381 ICS.Ambiguous.setToType(ToType);
1382 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383 Cand != Conversions.end(); ++Cand)
1384 if (Cand->Best)
1385 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386 break;
1387
1388 // Fall through.
1389 case OR_No_Viable_Function:
1390 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391 break;
1392 }
1393
1394 return ICS;
1395}
1396
1397/// TryImplicitConversion - Attempt to perform an implicit conversion
1398/// from the given expression (Expr) to the given type (ToType). This
1399/// function returns an implicit conversion sequence that can be used
1400/// to perform the initialization. Given
1401///
1402/// void f(float f);
1403/// void g(int i) { f(i); }
1404///
1405/// this routine would produce an implicit conversion sequence to
1406/// describe the initialization of f from i, which will be a standard
1407/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409//
1410/// Note that this routine only determines how the conversion can be
1411/// performed; it does not actually perform the conversion. As such,
1412/// it will not produce any diagnostics if no conversion is available,
1413/// but will instead return an implicit conversion sequence of kind
1414/// "BadConversion".
1415///
1416/// If @p SuppressUserConversions, then user-defined conversions are
1417/// not permitted.
1418/// If @p AllowExplicit, then explicit user-defined conversions are
1419/// permitted.
1420///
1421/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422/// writeback conversion, which allows __autoreleasing id* parameters to
1423/// be initialized with __strong id* or __weak id* arguments.
1424static ImplicitConversionSequence
1425TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426 bool SuppressUserConversions,
1427 AllowedExplicit AllowExplicit,
1428 bool InOverloadResolution,
1429 bool CStyle,
1430 bool AllowObjCWritebackConversion,
1431 bool AllowObjCConversionOnExplicit) {
1432 ImplicitConversionSequence ICS;
1433 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435 ICS.setStandard();
1436 return ICS;
1437 }
1438
1439 if (!S.getLangOpts().CPlusPlus) {
1440 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441 return ICS;
1442 }
1443
1444 // C++ [over.ics.user]p4:
1445 // A conversion of an expression of class type to the same class
1446 // type is given Exact Match rank, and a conversion of an
1447 // expression of class type to a base class of that type is
1448 // given Conversion rank, in spite of the fact that a copy/move
1449 // constructor (i.e., a user-defined conversion function) is
1450 // called for those cases.
1451 QualType FromType = From->getType();
1452 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1453 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1454 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1455 ICS.setStandard();
1456 ICS.Standard.setAsIdentityConversion();
1457 ICS.Standard.setFromType(FromType);
1458 ICS.Standard.setAllToTypes(ToType);
1459
1460 // We don't actually check at this point whether there is a valid
1461 // copy/move constructor, since overloading just assumes that it
1462 // exists. When we actually perform initialization, we'll find the
1463 // appropriate constructor to copy the returned object, if needed.
1464 ICS.Standard.CopyConstructor = nullptr;
1465
1466 // Determine whether this is considered a derived-to-base conversion.
1467 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468 ICS.Standard.Second = ICK_Derived_To_Base;
1469
1470 return ICS;
1471 }
1472
1473 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474 AllowExplicit, InOverloadResolution, CStyle,
1475 AllowObjCWritebackConversion,
1476 AllowObjCConversionOnExplicit);
1477}
1478
1479ImplicitConversionSequence
1480Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481 bool SuppressUserConversions,
1482 AllowedExplicit AllowExplicit,
1483 bool InOverloadResolution,
1484 bool CStyle,
1485 bool AllowObjCWritebackConversion) {
1486 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487 AllowExplicit, InOverloadResolution, CStyle,
1488 AllowObjCWritebackConversion,
1489 /*AllowObjCConversionOnExplicit=*/false);
1490}
1491
1492/// PerformImplicitConversion - Perform an implicit conversion of the
1493/// expression From to the type ToType. Returns the
1494/// converted expression. Flavor is the kind of conversion we're
1495/// performing, used in the error message. If @p AllowExplicit,
1496/// explicit user-defined conversions are permitted.
1497ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498 AssignmentAction Action,
1499 bool AllowExplicit) {
1500 if (checkPlaceholderForOverload(*this, From))
1501 return ExprError();
1502
1503 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504 bool AllowObjCWritebackConversion
1505 = getLangOpts().ObjCAutoRefCount &&
1506 (Action == AA_Passing || Action == AA_Sending);
1507 if (getLangOpts().ObjC)
1508 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509 From->getType(), From);
1510 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511 *this, From, ToType,
1512 /*SuppressUserConversions=*/false,
1513 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1514 /*InOverloadResolution=*/false,
1515 /*CStyle=*/false, AllowObjCWritebackConversion,
1516 /*AllowObjCConversionOnExplicit=*/false);
1517 return PerformImplicitConversion(From, ToType, ICS, Action);
1518}
1519
1520/// Determine whether the conversion from FromType to ToType is a valid
1521/// conversion that strips "noexcept" or "noreturn" off the nested function
1522/// type.
1523bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524 QualType &ResultTy) {
1525 if (Context.hasSameUnqualifiedType(FromType, ToType))
1526 return false;
1527
1528 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529 // or F(t noexcept) -> F(t)
1530 // where F adds one of the following at most once:
1531 // - a pointer
1532 // - a member pointer
1533 // - a block pointer
1534 // Changes here need matching changes in FindCompositePointerType.
1535 CanQualType CanTo = Context.getCanonicalType(ToType);
1536 CanQualType CanFrom = Context.getCanonicalType(FromType);
1537 Type::TypeClass TyClass = CanTo->getTypeClass();
1538 if (TyClass != CanFrom->getTypeClass()) return false;
1539 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1540 if (TyClass == Type::Pointer) {
1541 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543 } else if (TyClass == Type::BlockPointer) {
1544 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546 } else if (TyClass == Type::MemberPointer) {
1547 auto ToMPT = CanTo.castAs<MemberPointerType>();
1548 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549 // A function pointer conversion cannot change the class of the function.
1550 if (ToMPT->getClass() != FromMPT->getClass())
1551 return false;
1552 CanTo = ToMPT->getPointeeType();
1553 CanFrom = FromMPT->getPointeeType();
1554 } else {
1555 return false;
1556 }
1557
1558 TyClass = CanTo->getTypeClass();
1559 if (TyClass != CanFrom->getTypeClass()) return false;
1560 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1561 return false;
1562 }
1563
1564 const auto *FromFn = cast<FunctionType>(CanFrom);
1565 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566
1567 const auto *ToFn = cast<FunctionType>(CanTo);
1568 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569
1570 bool Changed = false;
1571
1572 // Drop 'noreturn' if not present in target type.
1573 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1574 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575 Changed = true;
1576 }
1577
1578 // Drop 'noexcept' if not present in target type.
1579 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1582 FromFn = cast<FunctionType>(
1583 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584 EST_None)
1585 .getTypePtr());
1586 Changed = true;
1587 }
1588
1589 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590 // only if the ExtParameterInfo lists of the two function prototypes can be
1591 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593 bool CanUseToFPT, CanUseFromFPT;
1594 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595 CanUseFromFPT, NewParamInfos) &&
1596 CanUseToFPT && !CanUseFromFPT) {
1597 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598 ExtInfo.ExtParameterInfos =
1599 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1600 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601 FromFPT->getParamTypes(), ExtInfo);
1602 FromFn = QT->getAs<FunctionType>();
1603 Changed = true;
1604 }
1605 }
1606
1607 if (!Changed)
1608 return false;
1609
1610 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1610, __PRETTY_FUNCTION__))
;
1611 if (QualType(FromFn, 0) != CanTo) return false;
1612
1613 ResultTy = ToType;
1614 return true;
1615}
1616
1617/// Determine whether the conversion from FromType to ToType is a valid
1618/// vector conversion.
1619///
1620/// \param ICK Will be set to the vector conversion kind, if this is a vector
1621/// conversion.
1622static bool IsVectorConversion(Sema &S, QualType FromType,
1623 QualType ToType, ImplicitConversionKind &ICK) {
1624 // We need at least one of these types to be a vector type to have a vector
1625 // conversion.
1626 if (!ToType->isVectorType() && !FromType->isVectorType())
1627 return false;
1628
1629 // Identical types require no conversions.
1630 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631 return false;
1632
1633 // There are no conversions between extended vector types, only identity.
1634 if (ToType->isExtVectorType()) {
1635 // There are no conversions between extended vector types other than the
1636 // identity conversion.
1637 if (FromType->isExtVectorType())
1638 return false;
1639
1640 // Vector splat from any arithmetic type to a vector.
1641 if (FromType->isArithmeticType()) {
1642 ICK = ICK_Vector_Splat;
1643 return true;
1644 }
1645 }
1646
1647 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1648 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1649 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1650 ICK = ICK_SVE_Vector_Conversion;
1651 return true;
1652 }
1653
1654 // We can perform the conversion between vector types in the following cases:
1655 // 1)vector types are equivalent AltiVec and GCC vector types
1656 // 2)lax vector conversions are permitted and the vector types are of the
1657 // same size
1658 // 3)the destination type does not have the ARM MVE strict-polymorphism
1659 // attribute, which inhibits lax vector conversion for overload resolution
1660 // only
1661 if (ToType->isVectorType() && FromType->isVectorType()) {
1662 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1663 (S.isLaxVectorConversion(FromType, ToType) &&
1664 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1665 ICK = ICK_Vector_Conversion;
1666 return true;
1667 }
1668 }
1669
1670 return false;
1671}
1672
1673static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1674 bool InOverloadResolution,
1675 StandardConversionSequence &SCS,
1676 bool CStyle);
1677
1678/// IsStandardConversion - Determines whether there is a standard
1679/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1680/// expression From to the type ToType. Standard conversion sequences
1681/// only consider non-class types; for conversions that involve class
1682/// types, use TryImplicitConversion. If a conversion exists, SCS will
1683/// contain the standard conversion sequence required to perform this
1684/// conversion and this routine will return true. Otherwise, this
1685/// routine will return false and the value of SCS is unspecified.
1686static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1687 bool InOverloadResolution,
1688 StandardConversionSequence &SCS,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion) {
1691 QualType FromType = From->getType();
1692
1693 // Standard conversions (C++ [conv])
1694 SCS.setAsIdentityConversion();
1695 SCS.IncompatibleObjC = false;
1696 SCS.setFromType(FromType);
1697 SCS.CopyConstructor = nullptr;
1698
1699 // There are no standard conversions for class types in C++, so
1700 // abort early. When overloading in C, however, we do permit them.
1701 if (S.getLangOpts().CPlusPlus &&
1702 (FromType->isRecordType() || ToType->isRecordType()))
1703 return false;
1704
1705 // The first conversion can be an lvalue-to-rvalue conversion,
1706 // array-to-pointer conversion, or function-to-pointer conversion
1707 // (C++ 4p1).
1708
1709 if (FromType == S.Context.OverloadTy) {
1710 DeclAccessPair AccessPair;
1711 if (FunctionDecl *Fn
1712 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1713 AccessPair)) {
1714 // We were able to resolve the address of the overloaded function,
1715 // so we can convert to the type of that function.
1716 FromType = Fn->getType();
1717 SCS.setFromType(FromType);
1718
1719 // we can sometimes resolve &foo<int> regardless of ToType, so check
1720 // if the type matches (identity) or we are converting to bool
1721 if (!S.Context.hasSameUnqualifiedType(
1722 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1723 QualType resultTy;
1724 // if the function type matches except for [[noreturn]], it's ok
1725 if (!S.IsFunctionConversion(FromType,
1726 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1727 // otherwise, only a boolean conversion is standard
1728 if (!ToType->isBooleanType())
1729 return false;
1730 }
1731
1732 // Check if the "from" expression is taking the address of an overloaded
1733 // function and recompute the FromType accordingly. Take advantage of the
1734 // fact that non-static member functions *must* have such an address-of
1735 // expression.
1736 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1737 if (Method && !Method->isStatic()) {
1738 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1739, __PRETTY_FUNCTION__))
1739 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1739, __PRETTY_FUNCTION__))
;
1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
1741 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
1742 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
;
1743 const Type *ClassType
1744 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1745 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1746 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
1748 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
1749 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
;
1750 FromType = S.Context.getPointerType(FromType);
1751 }
1752
1753 // Check that we've computed the proper type after overload resolution.
1754 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1755 // be calling it from within an NDEBUG block.
1756 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
1757 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
;
1759 } else {
1760 return false;
1761 }
1762 }
1763 // Lvalue-to-rvalue conversion (C++11 4.1):
1764 // A glvalue (3.10) of a non-function, non-array type T can
1765 // be converted to a prvalue.
1766 bool argIsLValue = From->isGLValue();
1767 if (argIsLValue &&
1768 !FromType->isFunctionType() && !FromType->isArrayType() &&
1769 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1770 SCS.First = ICK_Lvalue_To_Rvalue;
1771
1772 // C11 6.3.2.1p2:
1773 // ... if the lvalue has atomic type, the value has the non-atomic version
1774 // of the type of the lvalue ...
1775 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1776 FromType = Atomic->getValueType();
1777
1778 // If T is a non-class type, the type of the rvalue is the
1779 // cv-unqualified version of T. Otherwise, the type of the rvalue
1780 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1781 // just strip the qualifiers because they don't matter.
1782 FromType = FromType.getUnqualifiedType();
1783 } else if (FromType->isArrayType()) {
1784 // Array-to-pointer conversion (C++ 4.2)
1785 SCS.First = ICK_Array_To_Pointer;
1786
1787 // An lvalue or rvalue of type "array of N T" or "array of unknown
1788 // bound of T" can be converted to an rvalue of type "pointer to
1789 // T" (C++ 4.2p1).
1790 FromType = S.Context.getArrayDecayedType(FromType);
1791
1792 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1793 // This conversion is deprecated in C++03 (D.4)
1794 SCS.DeprecatedStringLiteralToCharPtr = true;
1795
1796 // For the purpose of ranking in overload resolution
1797 // (13.3.3.1.1), this conversion is considered an
1798 // array-to-pointer conversion followed by a qualification
1799 // conversion (4.4). (C++ 4.2p2)
1800 SCS.Second = ICK_Identity;
1801 SCS.Third = ICK_Qualification;
1802 SCS.QualificationIncludesObjCLifetime = false;
1803 SCS.setAllToTypes(FromType);
1804 return true;
1805 }
1806 } else if (FromType->isFunctionType() && argIsLValue) {
1807 // Function-to-pointer conversion (C++ 4.3).
1808 SCS.First = ICK_Function_To_Pointer;
1809
1810 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1811 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1812 if (!S.checkAddressOfFunctionIsAvailable(FD))
1813 return false;
1814
1815 // An lvalue of function type T can be converted to an rvalue of
1816 // type "pointer to T." The result is a pointer to the
1817 // function. (C++ 4.3p1).
1818 FromType = S.Context.getPointerType(FromType);
1819 } else {
1820 // We don't require any conversions for the first step.
1821 SCS.First = ICK_Identity;
1822 }
1823 SCS.setToType(0, FromType);
1824
1825 // The second conversion can be an integral promotion, floating
1826 // point promotion, integral conversion, floating point conversion,
1827 // floating-integral conversion, pointer conversion,
1828 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1829 // For overloading in C, this can also be a "compatible-type"
1830 // conversion.
1831 bool IncompatibleObjC = false;
1832 ImplicitConversionKind SecondICK = ICK_Identity;
1833 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1834 // The unqualified versions of the types are the same: there's no
1835 // conversion to do.
1836 SCS.Second = ICK_Identity;
1837 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1838 // Integral promotion (C++ 4.5).
1839 SCS.Second = ICK_Integral_Promotion;
1840 FromType = ToType.getUnqualifiedType();
1841 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1842 // Floating point promotion (C++ 4.6).
1843 SCS.Second = ICK_Floating_Promotion;
1844 FromType = ToType.getUnqualifiedType();
1845 } else if (S.IsComplexPromotion(FromType, ToType)) {
1846 // Complex promotion (Clang extension)
1847 SCS.Second = ICK_Complex_Promotion;
1848 FromType = ToType.getUnqualifiedType();
1849 } else if (ToType->isBooleanType() &&
1850 (FromType->isArithmeticType() ||
1851 FromType->isAnyPointerType() ||
1852 FromType->isBlockPointerType() ||
1853 FromType->isMemberPointerType())) {
1854 // Boolean conversions (C++ 4.12).
1855 SCS.Second = ICK_Boolean_Conversion;
1856 FromType = S.Context.BoolTy;
1857 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1858 ToType->isIntegralType(S.Context)) {
1859 // Integral conversions (C++ 4.7).
1860 SCS.Second = ICK_Integral_Conversion;
1861 FromType = ToType.getUnqualifiedType();
1862 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1863 // Complex conversions (C99 6.3.1.6)
1864 SCS.Second = ICK_Complex_Conversion;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1867 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1868 // Complex-real conversions (C99 6.3.1.7)
1869 SCS.Second = ICK_Complex_Real;
1870 FromType = ToType.getUnqualifiedType();
1871 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1872 // FIXME: disable conversions between long double and __float128 if
1873 // their representation is different until there is back end support
1874 // We of course allow this conversion if long double is really double.
1875
1876 // Conversions between bfloat and other floats are not permitted.
1877 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1878 return false;
1879 if (&S.Context.getFloatTypeSemantics(FromType) !=
1880 &S.Context.getFloatTypeSemantics(ToType)) {
1881 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1882 ToType == S.Context.LongDoubleTy) ||
1883 (FromType == S.Context.LongDoubleTy &&
1884 ToType == S.Context.Float128Ty));
1885 if (Float128AndLongDouble &&
1886 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1887 &llvm::APFloat::PPCDoubleDouble()))
1888 return false;
1889 }
1890 // Floating point conversions (C++ 4.8).
1891 SCS.Second = ICK_Floating_Conversion;
1892 FromType = ToType.getUnqualifiedType();
1893 } else if ((FromType->isRealFloatingType() &&
1894 ToType->isIntegralType(S.Context)) ||
1895 (FromType->isIntegralOrUnscopedEnumerationType() &&
1896 ToType->isRealFloatingType())) {
1897 // Conversions between bfloat and int are not permitted.
1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1899 return false;
1900
1901 // Floating-integral conversions (C++ 4.9).
1902 SCS.Second = ICK_Floating_Integral;
1903 FromType = ToType.getUnqualifiedType();
1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1905 SCS.Second = ICK_Block_Pointer_Conversion;
1906 } else if (AllowObjCWritebackConversion &&
1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1908 SCS.Second = ICK_Writeback_Conversion;
1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1910 FromType, IncompatibleObjC)) {
1911 // Pointer conversions (C++ 4.10).
1912 SCS.Second = ICK_Pointer_Conversion;
1913 SCS.IncompatibleObjC = IncompatibleObjC;
1914 FromType = FromType.getUnqualifiedType();
1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1916 InOverloadResolution, FromType)) {
1917 // Pointer to member conversions (4.11).
1918 SCS.Second = ICK_Pointer_Member;
1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1920 SCS.Second = SecondICK;
1921 FromType = ToType.getUnqualifiedType();
1922 } else if (!S.getLangOpts().CPlusPlus &&
1923 S.Context.typesAreCompatible(ToType, FromType)) {
1924 // Compatible conversions (Clang extension for C function overloading)
1925 SCS.Second = ICK_Compatible_Conversion;
1926 FromType = ToType.getUnqualifiedType();
1927 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1928 InOverloadResolution,
1929 SCS, CStyle)) {
1930 SCS.Second = ICK_TransparentUnionConversion;
1931 FromType = ToType;
1932 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1933 CStyle)) {
1934 // tryAtomicConversion has updated the standard conversion sequence
1935 // appropriately.
1936 return true;
1937 } else if (ToType->isEventT() &&
1938 From->isIntegerConstantExpr(S.getASTContext()) &&
1939 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1940 SCS.Second = ICK_Zero_Event_Conversion;
1941 FromType = ToType;
1942 } else if (ToType->isQueueT() &&
1943 From->isIntegerConstantExpr(S.getASTContext()) &&
1944 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1945 SCS.Second = ICK_Zero_Queue_Conversion;
1946 FromType = ToType;
1947 } else if (ToType->isSamplerT() &&
1948 From->isIntegerConstantExpr(S.getASTContext())) {
1949 SCS.Second = ICK_Compatible_Conversion;
1950 FromType = ToType;
1951 } else {
1952 // No second conversion required.
1953 SCS.Second = ICK_Identity;
1954 }
1955 SCS.setToType(1, FromType);
1956
1957 // The third conversion can be a function pointer conversion or a
1958 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1959 bool ObjCLifetimeConversion;
1960 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1961 // Function pointer conversions (removing 'noexcept') including removal of
1962 // 'noreturn' (Clang extension).
1963 SCS.Third = ICK_Function_Conversion;
1964 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1965 ObjCLifetimeConversion)) {
1966 SCS.Third = ICK_Qualification;
1967 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1968 FromType = ToType;
1969 } else {
1970 // No conversion required
1971 SCS.Third = ICK_Identity;
1972 }
1973
1974 // C++ [over.best.ics]p6:
1975 // [...] Any difference in top-level cv-qualification is
1976 // subsumed by the initialization itself and does not constitute
1977 // a conversion. [...]
1978 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1979 QualType CanonTo = S.Context.getCanonicalType(ToType);
1980 if (CanonFrom.getLocalUnqualifiedType()
1981 == CanonTo.getLocalUnqualifiedType() &&
1982 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1983 FromType = ToType;
1984 CanonFrom = CanonTo;
1985 }
1986
1987 SCS.setToType(2, FromType);
1988
1989 if (CanonFrom == CanonTo)
1990 return true;
1991
1992 // If we have not converted the argument type to the parameter type,
1993 // this is a bad conversion sequence, unless we're resolving an overload in C.
1994 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1995 return false;
1996
1997 ExprResult ER = ExprResult{From};
1998 Sema::AssignConvertType Conv =
1999 S.CheckSingleAssignmentConstraints(ToType, ER,
2000 /*Diagnose=*/false,
2001 /*DiagnoseCFAudited=*/false,
2002 /*ConvertRHS=*/false);
2003 ImplicitConversionKind SecondConv;
2004 switch (Conv) {
2005 case Sema::Compatible:
2006 SecondConv = ICK_C_Only_Conversion;
2007 break;
2008 // For our purposes, discarding qualifiers is just as bad as using an
2009 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2010 // qualifiers, as well.
2011 case Sema::CompatiblePointerDiscardsQualifiers:
2012 case Sema::IncompatiblePointer:
2013 case Sema::IncompatiblePointerSign:
2014 SecondConv = ICK_Incompatible_Pointer_Conversion;
2015 break;
2016 default:
2017 return false;
2018 }
2019
2020 // First can only be an lvalue conversion, so we pretend that this was the
2021 // second conversion. First should already be valid from earlier in the
2022 // function.
2023 SCS.Second = SecondConv;
2024 SCS.setToType(1, ToType);
2025
2026 // Third is Identity, because Second should rank us worse than any other
2027 // conversion. This could also be ICK_Qualification, but it's simpler to just
2028 // lump everything in with the second conversion, and we don't gain anything
2029 // from making this ICK_Qualification.
2030 SCS.Third = ICK_Identity;
2031 SCS.setToType(2, ToType);
2032 return true;
2033}
2034
2035static bool
2036IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2037 QualType &ToType,
2038 bool InOverloadResolution,
2039 StandardConversionSequence &SCS,
2040 bool CStyle) {
2041
2042 const RecordType *UT = ToType->getAsUnionType();
2043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2044 return false;
2045 // The field to initialize within the transparent union.
2046 RecordDecl *UD = UT->getDecl();
2047 // It's compatible if the expression matches any of the fields.
2048 for (const auto *it : UD->fields()) {
2049 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2050 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2051 ToType = it->getType();
2052 return true;
2053 }
2054 }
2055 return false;
2056}
2057
2058/// IsIntegralPromotion - Determines whether the conversion from the
2059/// expression From (whose potentially-adjusted type is FromType) to
2060/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2061/// sets PromotedType to the promoted type.
2062bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2063 const BuiltinType *To = ToType->getAs<BuiltinType>();
2064 // All integers are built-in.
2065 if (!To) {
2066 return false;
2067 }
2068
2069 // An rvalue of type char, signed char, unsigned char, short int, or
2070 // unsigned short int can be converted to an rvalue of type int if
2071 // int can represent all the values of the source type; otherwise,
2072 // the source rvalue can be converted to an rvalue of type unsigned
2073 // int (C++ 4.5p1).
2074 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2075 !FromType->isEnumeralType()) {
2076 if (// We can promote any signed, promotable integer type to an int
2077 (FromType->isSignedIntegerType() ||
2078 // We can promote any unsigned integer type whose size is
2079 // less than int to an int.
2080 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2081 return To->getKind() == BuiltinType::Int;
2082 }
2083
2084 return To->getKind() == BuiltinType::UInt;
2085 }
2086
2087 // C++11 [conv.prom]p3:
2088 // A prvalue of an unscoped enumeration type whose underlying type is not
2089 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2090 // following types that can represent all the values of the enumeration
2091 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2092 // unsigned int, long int, unsigned long int, long long int, or unsigned
2093 // long long int. If none of the types in that list can represent all the
2094 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2095 // type can be converted to an rvalue a prvalue of the extended integer type
2096 // with lowest integer conversion rank (4.13) greater than the rank of long
2097 // long in which all the values of the enumeration can be represented. If
2098 // there are two such extended types, the signed one is chosen.
2099 // C++11 [conv.prom]p4:
2100 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2101 // can be converted to a prvalue of its underlying type. Moreover, if
2102 // integral promotion can be applied to its underlying type, a prvalue of an
2103 // unscoped enumeration type whose underlying type is fixed can also be
2104 // converted to a prvalue of the promoted underlying type.
2105 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2106 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2107 // provided for a scoped enumeration.
2108 if (FromEnumType->getDecl()->isScoped())
2109 return false;
2110
2111 // We can perform an integral promotion to the underlying type of the enum,
2112 // even if that's not the promoted type. Note that the check for promoting
2113 // the underlying type is based on the type alone, and does not consider
2114 // the bitfield-ness of the actual source expression.
2115 if (FromEnumType->getDecl()->isFixed()) {
2116 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2117 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2118 IsIntegralPromotion(nullptr, Underlying, ToType);
2119 }
2120
2121 // We have already pre-calculated the promotion type, so this is trivial.
2122 if (ToType->isIntegerType() &&
2123 isCompleteType(From->getBeginLoc(), FromType))
2124 return Context.hasSameUnqualifiedType(
2125 ToType, FromEnumType->getDecl()->getPromotionType());
2126
2127 // C++ [conv.prom]p5:
2128 // If the bit-field has an enumerated type, it is treated as any other
2129 // value of that type for promotion purposes.
2130 //
2131 // ... so do not fall through into the bit-field checks below in C++.
2132 if (getLangOpts().CPlusPlus)
2133 return false;
2134 }
2135
2136 // C++0x [conv.prom]p2:
2137 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2138 // to an rvalue a prvalue of the first of the following types that can
2139 // represent all the values of its underlying type: int, unsigned int,
2140 // long int, unsigned long int, long long int, or unsigned long long int.
2141 // If none of the types in that list can represent all the values of its
2142 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2143 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2144 // type.
2145 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2146 ToType->isIntegerType()) {
2147 // Determine whether the type we're converting from is signed or
2148 // unsigned.
2149 bool FromIsSigned = FromType->isSignedIntegerType();
2150 uint64_t FromSize = Context.getTypeSize(FromType);
2151
2152 // The types we'll try to promote to, in the appropriate
2153 // order. Try each of these types.
2154 QualType PromoteTypes[6] = {
2155 Context.IntTy, Context.UnsignedIntTy,
2156 Context.LongTy, Context.UnsignedLongTy ,
2157 Context.LongLongTy, Context.UnsignedLongLongTy
2158 };
2159 for (int Idx = 0; Idx < 6; ++Idx) {
2160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2161 if (FromSize < ToSize ||
2162 (FromSize == ToSize &&
2163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2164 // We found the type that we can promote to. If this is the
2165 // type we wanted, we have a promotion. Otherwise, no
2166 // promotion.
2167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2168 }
2169 }
2170 }
2171
2172 // An rvalue for an integral bit-field (9.6) can be converted to an
2173 // rvalue of type int if int can represent all the values of the
2174 // bit-field; otherwise, it can be converted to unsigned int if
2175 // unsigned int can represent all the values of the bit-field. If
2176 // the bit-field is larger yet, no integral promotion applies to
2177 // it. If the bit-field has an enumerated type, it is treated as any
2178 // other value of that type for promotion purposes (C++ 4.5p3).
2179 // FIXME: We should delay checking of bit-fields until we actually perform the
2180 // conversion.
2181 //
2182 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2183 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2184 // bit-fields and those whose underlying type is larger than int) for GCC
2185 // compatibility.
2186 if (From) {
2187 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2188 Optional<llvm::APSInt> BitWidth;
2189 if (FromType->isIntegralType(Context) &&
2190 (BitWidth =
2191 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2192 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2193 ToSize = Context.getTypeSize(ToType);
2194
2195 // Are we promoting to an int from a bitfield that fits in an int?
2196 if (*BitWidth < ToSize ||
2197 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2198 return To->getKind() == BuiltinType::Int;
2199 }
2200
2201 // Are we promoting to an unsigned int from an unsigned bitfield
2202 // that fits into an unsigned int?
2203 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2204 return To->getKind() == BuiltinType::UInt;
2205 }
2206
2207 return false;
2208 }
2209 }
2210 }
2211
2212 // An rvalue of type bool can be converted to an rvalue of type int,
2213 // with false becoming zero and true becoming one (C++ 4.5p4).
2214 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2215 return true;
2216 }
2217
2218 return false;
2219}
2220
2221/// IsFloatingPointPromotion - Determines whether the conversion from
2222/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2223/// returns true and sets PromotedType to the promoted type.
2224bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2227 /// An rvalue of type float can be converted to an rvalue of type
2228 /// double. (C++ 4.6p1).
2229 if (FromBuiltin->getKind() == BuiltinType::Float &&
2230 ToBuiltin->getKind() == BuiltinType::Double)
2231 return true;
2232
2233 // C99 6.3.1.5p1:
2234 // When a float is promoted to double or long double, or a
2235 // double is promoted to long double [...].
2236 if (!getLangOpts().CPlusPlus &&
2237 (FromBuiltin->getKind() == BuiltinType::Float ||
2238 FromBuiltin->getKind() == BuiltinType::Double) &&
2239 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2240 ToBuiltin->getKind() == BuiltinType::Float128))
2241 return true;
2242
2243 // Half can be promoted to float.
2244 if (!getLangOpts().NativeHalfType &&
2245 FromBuiltin->getKind() == BuiltinType::Half &&
2246 ToBuiltin->getKind() == BuiltinType::Float)
2247 return true;
2248 }
2249
2250 return false;
2251}
2252
2253/// Determine if a conversion is a complex promotion.
2254///
2255/// A complex promotion is defined as a complex -> complex conversion
2256/// where the conversion between the underlying real types is a
2257/// floating-point or integral promotion.
2258bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2260 if (!FromComplex)
2261 return false;
2262
2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2264 if (!ToComplex)
2265 return false;
2266
2267 return IsFloatingPointPromotion(FromComplex->getElementType(),
2268 ToComplex->getElementType()) ||
2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2270 ToComplex->getElementType());
2271}
2272
2273/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2274/// the pointer type FromPtr to a pointer to type ToPointee, with the
2275/// same type qualifiers as FromPtr has on its pointee type. ToType,
2276/// if non-empty, will be a pointer to ToType that may or may not have
2277/// the right set of qualifiers on its pointee.
2278///
2279static QualType
2280BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2281 QualType ToPointee, QualType ToType,
2282 ASTContext &Context,
2283 bool StripObjCLifetime = false) {
2284 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
2286 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
;
2287
2288 /// Conversions to 'id' subsume cv-qualifier conversions.
2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2290 return ToType.getUnqualifiedType();
2291
2292 QualType CanonFromPointee
2293 = Context.getCanonicalType(FromPtr->getPointeeType());
2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2295 Qualifiers Quals = CanonFromPointee.getQualifiers();
2296
2297 if (StripObjCLifetime)
2298 Quals.removeObjCLifetime();
2299
2300 // Exact qualifier match -> return the pointer type we're converting to.
2301 if (CanonToPointee.getLocalQualifiers() == Quals) {
2302 // ToType is exactly what we need. Return it.
2303 if (!ToType.isNull())
2304 return ToType.getUnqualifiedType();
2305
2306 // Build a pointer to ToPointee. It has the right qualifiers
2307 // already.
2308 if (isa<ObjCObjectPointerType>(ToType))
2309 return Context.getObjCObjectPointerType(ToPointee);
2310 return Context.getPointerType(ToPointee);
2311 }
2312
2313 // Just build a canonical type that has the right qualifiers.
2314 QualType QualifiedCanonToPointee
2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2316
2317 if (isa<ObjCObjectPointerType>(ToType))
2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2319 return Context.getPointerType(QualifiedCanonToPointee);
2320}
2321
2322static bool isNullPointerConstantForConversion(Expr *Expr,
2323 bool InOverloadResolution,
2324 ASTContext &Context) {
2325 // Handle value-dependent integral null pointer constants correctly.
2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2329 return !InOverloadResolution;
2330
2331 return Expr->isNullPointerConstant(Context,
2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2333 : Expr::NPC_ValueDependentIsNull);
2334}
2335
2336/// IsPointerConversion - Determines whether the conversion of the
2337/// expression From, which has the (possibly adjusted) type FromType,
2338/// can be converted to the type ToType via a pointer conversion (C++
2339/// 4.10). If so, returns true and places the converted type (that
2340/// might differ from ToType in its cv-qualifiers at some level) into
2341/// ConvertedType.
2342///
2343/// This routine also supports conversions to and from block pointers
2344/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2345/// pointers to interfaces. FIXME: Once we've determined the
2346/// appropriate overloading rules for Objective-C, we may want to
2347/// split the Objective-C checks into a different routine; however,
2348/// GCC seems to consider all of these conversions to be pointer
2349/// conversions, so for now they live here. IncompatibleObjC will be
2350/// set if the conversion is an allowed Objective-C conversion that
2351/// should result in a warning.
2352bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2353 bool InOverloadResolution,
2354 QualType& ConvertedType,
2355 bool &IncompatibleObjC) {
2356 IncompatibleObjC = false;
2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2358 IncompatibleObjC))
2359 return true;
2360
2361 // Conversion from a null pointer constant to any Objective-C pointer type.
2362 if (ToType->isObjCObjectPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // Blocks: Block pointers can be converted to void*.
2369 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2371 ConvertedType = ToType;
2372 return true;
2373 }
2374 // Blocks: A null pointer constant can be converted to a block
2375 // pointer type.
2376 if (ToType->isBlockPointerType() &&
2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2378 ConvertedType = ToType;
2379 return true;
2380 }
2381
2382 // If the left-hand-side is nullptr_t, the right side can be a null
2383 // pointer constant.
2384 if (ToType->isNullPtrType() &&
2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386 ConvertedType = ToType;
2387 return true;
2388 }
2389
2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2391 if (!ToTypePtr)
2392 return false;
2393
2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2396 ConvertedType = ToType;
2397 return true;
2398 }
2399
2400 // Beyond this point, both types need to be pointers
2401 // , including objective-c pointers.
2402 QualType ToPointeeType = ToTypePtr->getPointeeType();
2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2404 !getLangOpts().ObjCAutoRefCount) {
2405 ConvertedType = BuildSimilarlyQualifiedPointerType(
2406 FromType->getAs<ObjCObjectPointerType>(),
2407 ToPointeeType,
2408 ToType, Context);
2409 return true;
2410 }
2411 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2412 if (!FromTypePtr)
2413 return false;
2414
2415 QualType FromPointeeType = FromTypePtr->getPointeeType();
2416
2417 // If the unqualified pointee types are the same, this can't be a
2418 // pointer conversion, so don't do all of the work below.
2419 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2420 return false;
2421
2422 // An rvalue of type "pointer to cv T," where T is an object type,
2423 // can be converted to an rvalue of type "pointer to cv void" (C++
2424 // 4.10p2).
2425 if (FromPointeeType->isIncompleteOrObjectType() &&
2426 ToPointeeType->isVoidType()) {
2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428 ToPointeeType,
2429 ToType, Context,
2430 /*StripObjCLifetime=*/true);
2431 return true;
2432 }
2433
2434 // MSVC allows implicit function to void* type conversion.
2435 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2436 ToPointeeType->isVoidType()) {
2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438 ToPointeeType,
2439 ToType, Context);
2440 return true;
2441 }
2442
2443 // When we're overloading in C, we allow a special kind of pointer
2444 // conversion for compatible-but-not-identical pointee types.
2445 if (!getLangOpts().CPlusPlus &&
2446 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2447 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2448 ToPointeeType,
2449 ToType, Context);
2450 return true;
2451 }
2452
2453 // C++ [conv.ptr]p3:
2454 //
2455 // An rvalue of type "pointer to cv D," where D is a class type,
2456 // can be converted to an rvalue of type "pointer to cv B," where
2457 // B is a base class (clause 10) of D. If B is an inaccessible
2458 // (clause 11) or ambiguous (10.2) base class of D, a program that
2459 // necessitates this conversion is ill-formed. The result of the
2460 // conversion is a pointer to the base class sub-object of the
2461 // derived class object. The null pointer value is converted to
2462 // the null pointer value of the destination type.
2463 //
2464 // Note that we do not check for ambiguity or inaccessibility
2465 // here. That is handled by CheckPointerConversion.
2466 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2467 ToPointeeType->isRecordType() &&
2468 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2469 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2470 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2471 ToPointeeType,
2472 ToType, Context);
2473 return true;
2474 }
2475
2476 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2477 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2478 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2479 ToPointeeType,
2480 ToType, Context);
2481 return true;
2482 }
2483
2484 return false;
2485}
2486
2487/// Adopt the given qualifiers for the given type.
2488static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2489 Qualifiers TQs = T.getQualifiers();
2490
2491 // Check whether qualifiers already match.
2492 if (TQs == Qs)
2493 return T;
2494
2495 if (Qs.compatiblyIncludes(TQs))
2496 return Context.getQualifiedType(T, Qs);
2497
2498 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2499}
2500
2501/// isObjCPointerConversion - Determines whether this is an
2502/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2503/// with the same arguments and return values.
2504bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2505 QualType& ConvertedType,
2506 bool &IncompatibleObjC) {
2507 if (!getLangOpts().ObjC)
2508 return false;
2509
2510 // The set of qualifiers on the type we're converting from.
2511 Qualifiers FromQualifiers = FromType.getQualifiers();
2512
2513 // First, we handle all conversions on ObjC object pointer types.
2514 const ObjCObjectPointerType* ToObjCPtr =
2515 ToType->getAs<ObjCObjectPointerType>();
2516 const ObjCObjectPointerType *FromObjCPtr =
2517 FromType->getAs<ObjCObjectPointerType>();
2518
2519 if (ToObjCPtr && FromObjCPtr) {
2520 // If the pointee types are the same (ignoring qualifications),
2521 // then this is not a pointer conversion.
2522 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2523 FromObjCPtr->getPointeeType()))
2524 return false;
2525
2526 // Conversion between Objective-C pointers.
2527 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2528 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2529 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2530 if (getLangOpts().CPlusPlus && LHS && RHS &&
2531 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2532 FromObjCPtr->getPointeeType()))
2533 return false;
2534 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2535 ToObjCPtr->getPointeeType(),
2536 ToType, Context);
2537 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2538 return true;
2539 }
2540
2541 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2542 // Okay: this is some kind of implicit downcast of Objective-C
2543 // interfaces, which is permitted. However, we're going to
2544 // complain about it.
2545 IncompatibleObjC = true;
2546 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2547 ToObjCPtr->getPointeeType(),
2548 ToType, Context);
2549 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2550 return true;
2551 }
2552 }
2553 // Beyond this point, both types need to be C pointers or block pointers.
2554 QualType ToPointeeType;
2555 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2556 ToPointeeType = ToCPtr->getPointeeType();
2557 else if (const BlockPointerType *ToBlockPtr =
2558 ToType->getAs<BlockPointerType>()) {
2559 // Objective C++: We're able to convert from a pointer to any object
2560 // to a block pointer type.
2561 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2562 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2563 return true;
2564 }
2565 ToPointeeType = ToBlockPtr->getPointeeType();
2566 }
2567 else if (FromType->getAs<BlockPointerType>() &&
2568 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2569 // Objective C++: We're able to convert from a block pointer type to a
2570 // pointer to any object.
2571 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2572 return true;
2573 }
2574 else
2575 return false;
2576
2577 QualType FromPointeeType;
2578 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2579 FromPointeeType = FromCPtr->getPointeeType();
2580 else if (const BlockPointerType *FromBlockPtr =
2581 FromType->getAs<BlockPointerType>())
2582 FromPointeeType = FromBlockPtr->getPointeeType();
2583 else
2584 return false;
2585
2586 // If we have pointers to pointers, recursively check whether this
2587 // is an Objective-C conversion.
2588 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2589 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2590 IncompatibleObjC)) {
2591 // We always complain about this conversion.
2592 IncompatibleObjC = true;
2593 ConvertedType = Context.getPointerType(ConvertedType);
2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595 return true;
2596 }
2597 // Allow conversion of pointee being objective-c pointer to another one;
2598 // as in I* to id.
2599 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2600 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2601 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2602 IncompatibleObjC)) {
2603
2604 ConvertedType = Context.getPointerType(ConvertedType);
2605 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2606 return true;
2607 }
2608
2609 // If we have pointers to functions or blocks, check whether the only
2610 // differences in the argument and result types are in Objective-C
2611 // pointer conversions. If so, we permit the conversion (but
2612 // complain about it).
2613 const FunctionProtoType *FromFunctionType
2614 = FromPointeeType->getAs<FunctionProtoType>();
2615 const FunctionProtoType *ToFunctionType
2616 = ToPointeeType->getAs<FunctionProtoType>();
2617 if (FromFunctionType && ToFunctionType) {
2618 // If the function types are exactly the same, this isn't an
2619 // Objective-C pointer conversion.
2620 if (Context.getCanonicalType(FromPointeeType)
2621 == Context.getCanonicalType(ToPointeeType))
2622 return false;
2623
2624 // Perform the quick checks that will tell us whether these
2625 // function types are obviously different.
2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2628 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2629 return false;
2630
2631 bool HasObjCConversion = false;
2632 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2633 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2634 // Okay, the types match exactly. Nothing to do.
2635 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2636 ToFunctionType->getReturnType(),
2637 ConvertedType, IncompatibleObjC)) {
2638 // Okay, we have an Objective-C pointer conversion.
2639 HasObjCConversion = true;
2640 } else {
2641 // Function types are too different. Abort.
2642 return false;
2643 }
2644
2645 // Check argument types.
2646 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2647 ArgIdx != NumArgs; ++ArgIdx) {
2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2650 if (Context.getCanonicalType(FromArgType)
2651 == Context.getCanonicalType(ToArgType)) {
2652 // Okay, the types match exactly. Nothing to do.
2653 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2654 ConvertedType, IncompatibleObjC)) {
2655 // Okay, we have an Objective-C pointer conversion.
2656 HasObjCConversion = true;
2657 } else {
2658 // Argument types are too different. Abort.
2659 return false;
2660 }
2661 }
2662
2663 if (HasObjCConversion) {
2664 // We had an Objective-C conversion. Allow this pointer
2665 // conversion, but complain about it.
2666 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2667 IncompatibleObjC = true;
2668 return true;
2669 }
2670 }
2671
2672 return false;
2673}
2674
2675/// Determine whether this is an Objective-C writeback conversion,
2676/// used for parameter passing when performing automatic reference counting.
2677///
2678/// \param FromType The type we're converting form.
2679///
2680/// \param ToType The type we're converting to.
2681///
2682/// \param ConvertedType The type that will be produced after applying
2683/// this conversion.
2684bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2685 QualType &ConvertedType) {
2686 if (!getLangOpts().ObjCAutoRefCount ||
2687 Context.hasSameUnqualifiedType(FromType, ToType))
2688 return false;
2689
2690 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2691 QualType ToPointee;
2692 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2693 ToPointee = ToPointer->getPointeeType();
2694 else
2695 return false;
2696
2697 Qualifiers ToQuals = ToPointee.getQualifiers();
2698 if (!ToPointee->isObjCLifetimeType() ||
2699 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2700 !ToQuals.withoutObjCLifetime().empty())
2701 return false;
2702
2703 // Argument must be a pointer to __strong to __weak.
2704 QualType FromPointee;
2705 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2706 FromPointee = FromPointer->getPointeeType();
2707 else
2708 return false;
2709
2710 Qualifiers FromQuals = FromPointee.getQualifiers();
2711 if (!FromPointee->isObjCLifetimeType() ||
2712 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2713 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2714 return false;
2715
2716 // Make sure that we have compatible qualifiers.
2717 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2718 if (!ToQuals.compatiblyIncludes(FromQuals))
2719 return false;
2720
2721 // Remove qualifiers from the pointee type we're converting from; they
2722 // aren't used in the compatibility check belong, and we'll be adding back
2723 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2724 FromPointee = FromPointee.getUnqualifiedType();
2725
2726 // The unqualified form of the pointee types must be compatible.
2727 ToPointee = ToPointee.getUnqualifiedType();
2728 bool IncompatibleObjC;
2729 if (Context.typesAreCompatible(FromPointee, ToPointee))
2730 FromPointee = ToPointee;
2731 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2732 IncompatibleObjC))
2733 return false;
2734
2735 /// Construct the type we're converting to, which is a pointer to
2736 /// __autoreleasing pointee.
2737 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2738 ConvertedType = Context.getPointerType(FromPointee);
2739 return true;
2740}
2741
2742bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2743 QualType& ConvertedType) {
2744 QualType ToPointeeType;
2745 if (const BlockPointerType *ToBlockPtr =
2746 ToType->getAs<BlockPointerType>())
2747 ToPointeeType = ToBlockPtr->getPointeeType();
2748 else
2749 return false;
2750
2751 QualType FromPointeeType;
2752 if (const BlockPointerType *FromBlockPtr =
2753 FromType->getAs<BlockPointerType>())
2754 FromPointeeType = FromBlockPtr->getPointeeType();
2755 else
2756 return false;
2757 // We have pointer to blocks, check whether the only
2758 // differences in the argument and result types are in Objective-C
2759 // pointer conversions. If so, we permit the conversion.
2760
2761 const FunctionProtoType *FromFunctionType
2762 = FromPointeeType->getAs<FunctionProtoType>();
2763 const FunctionProtoType *ToFunctionType
2764 = ToPointeeType->getAs<FunctionProtoType>();
2765
2766 if (!FromFunctionType || !ToFunctionType)
2767 return false;
2768
2769 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2770 return true;
2771
2772 // Perform the quick checks that will tell us whether these
2773 // function types are obviously different.
2774 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2775 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2776 return false;
2777
2778 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2779 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2780 if (FromEInfo != ToEInfo)
2781 return false;
2782
2783 bool IncompatibleObjC = false;
2784 if (Context.hasSameType(FromFunctionType->getReturnType(),
2785 ToFunctionType->getReturnType())) {
2786 // Okay, the types match exactly. Nothing to do.
2787 } else {
2788 QualType RHS = FromFunctionType->getReturnType();
2789 QualType LHS = ToFunctionType->getReturnType();
2790 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2791 !RHS.hasQualifiers() && LHS.hasQualifiers())
2792 LHS = LHS.getUnqualifiedType();
2793
2794 if (Context.hasSameType(RHS,LHS)) {
2795 // OK exact match.
2796 } else if (isObjCPointerConversion(RHS, LHS,
2797 ConvertedType, IncompatibleObjC)) {
2798 if (IncompatibleObjC)
2799 return false;
2800 // Okay, we have an Objective-C pointer conversion.
2801 }
2802 else
2803 return false;
2804 }
2805
2806 // Check argument types.
2807 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2808 ArgIdx != NumArgs; ++ArgIdx) {
2809 IncompatibleObjC = false;
2810 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2811 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2812 if (Context.hasSameType(FromArgType, ToArgType)) {
2813 // Okay, the types match exactly. Nothing to do.
2814 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2815 ConvertedType, IncompatibleObjC)) {
2816 if (IncompatibleObjC)
2817 return false;
2818 // Okay, we have an Objective-C pointer conversion.
2819 } else
2820 // Argument types are too different. Abort.
2821 return false;
2822 }
2823
2824 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2825 bool CanUseToFPT, CanUseFromFPT;
2826 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2827 CanUseToFPT, CanUseFromFPT,
2828 NewParamInfos))
2829 return false;
2830
2831 ConvertedType = ToType;
2832 return true;
2833}
2834
2835enum {
2836 ft_default,
2837 ft_different_class,
2838 ft_parameter_arity,
2839 ft_parameter_mismatch,
2840 ft_return_type,
2841 ft_qualifer_mismatch,
2842 ft_noexcept
2843};
2844
2845/// Attempts to get the FunctionProtoType from a Type. Handles
2846/// MemberFunctionPointers properly.
2847static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2848 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2849 return FPT;
2850
2851 if (auto *MPT = FromType->getAs<MemberPointerType>())
2852 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2853
2854 return nullptr;
2855}
2856
2857/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2858/// function types. Catches different number of parameter, mismatch in
2859/// parameter types, and different return types.
2860void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2861 QualType FromType, QualType ToType) {
2862 // If either type is not valid, include no extra info.
2863 if (FromType.isNull() || ToType.isNull()) {
2864 PDiag << ft_default;
2865 return;
2866 }
2867
2868 // Get the function type from the pointers.
2869 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2870 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2871 *ToMember = ToType->castAs<MemberPointerType>();
2872 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2873 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2874 << QualType(FromMember->getClass(), 0);
2875 return;
2876 }
2877 FromType = FromMember->getPointeeType();
2878 ToType = ToMember->getPointeeType();
2879 }
2880
2881 if (FromType->isPointerType())
2882 FromType = FromType->getPointeeType();
2883 if (ToType->isPointerType())
2884 ToType = ToType->getPointeeType();
2885
2886 // Remove references.
2887 FromType = FromType.getNonReferenceType();
2888 ToType = ToType.getNonReferenceType();
2889
2890 // Don't print extra info for non-specialized template functions.
2891 if (FromType->isInstantiationDependentType() &&
2892 !FromType->getAs<TemplateSpecializationType>()) {
2893 PDiag << ft_default;
2894 return;
2895 }
2896
2897 // No extra info for same types.
2898 if (Context.hasSameType(FromType, ToType)) {
2899 PDiag << ft_default;
2900 return;
2901 }
2902
2903 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2904 *ToFunction = tryGetFunctionProtoType(ToType);
2905
2906 // Both types need to be function types.
2907 if (!FromFunction || !ToFunction) {
2908 PDiag << ft_default;
2909 return;
2910 }
2911
2912 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2913 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2914 << FromFunction->getNumParams();
2915 return;
2916 }
2917
2918 // Handle different parameter types.
2919 unsigned ArgPos;
2920 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2921 PDiag << ft_parameter_mismatch << ArgPos + 1
2922 << ToFunction->getParamType(ArgPos)
2923 << FromFunction->getParamType(ArgPos);
2924 return;
2925 }
2926
2927 // Handle different return type.
2928 if (!Context.hasSameType(FromFunction->getReturnType(),
2929 ToFunction->getReturnType())) {
2930 PDiag << ft_return_type << ToFunction->getReturnType()
2931 << FromFunction->getReturnType();
2932 return;
2933 }
2934
2935 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2936 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2937 << FromFunction->getMethodQuals();
2938 return;
2939 }
2940
2941 // Handle exception specification differences on canonical type (in C++17
2942 // onwards).
2943 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2944 ->isNothrow() !=
2945 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2946 ->isNothrow()) {
2947 PDiag << ft_noexcept;
2948 return;
2949 }
2950
2951 // Unable to find a difference, so add no extra info.
2952 PDiag << ft_default;
2953}
2954
2955/// FunctionParamTypesAreEqual - This routine checks two function proto types
2956/// for equality of their argument types. Caller has already checked that
2957/// they have same number of arguments. If the parameters are different,
2958/// ArgPos will have the parameter index of the first different parameter.
2959bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2960 const FunctionProtoType *NewType,
2961 unsigned *ArgPos) {
2962 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2963 N = NewType->param_type_begin(),
2964 E = OldType->param_type_end();
2965 O && (O != E); ++O, ++N) {
2966 // Ignore address spaces in pointee type. This is to disallow overloading
2967 // on __ptr32/__ptr64 address spaces.
2968 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2969 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2970
2971 if (!Context.hasSameType(Old, New)) {
2972 if (ArgPos)
2973 *ArgPos = O - OldType->param_type_begin();
2974 return false;
2975 }
2976 }
2977 return true;
2978}
2979
2980/// CheckPointerConversion - Check the pointer conversion from the
2981/// expression From to the type ToType. This routine checks for
2982/// ambiguous or inaccessible derived-to-base pointer
2983/// conversions for which IsPointerConversion has already returned
2984/// true. It returns true and produces a diagnostic if there was an
2985/// error, or returns false otherwise.
2986bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2987 CastKind &Kind,
2988 CXXCastPath& BasePath,
2989 bool IgnoreBaseAccess,
2990 bool Diagnose) {
2991 QualType FromType = From->getType();
2992 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2993
2994 Kind = CK_BitCast;
2995
2996 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2997 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2998 Expr::NPCK_ZeroExpression) {
2999 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3000 DiagRuntimeBehavior(From->getExprLoc(), From,
3001 PDiag(diag::warn_impcast_bool_to_null_pointer)
3002 << ToType << From->getSourceRange());
3003 else if (!isUnevaluatedContext())
3004 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3005 << ToType << From->getSourceRange();
3006 }
3007 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3008 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3009 QualType FromPointeeType = FromPtrType->getPointeeType(),
3010 ToPointeeType = ToPtrType->getPointeeType();
3011
3012 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3013 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3014 // We must have a derived-to-base conversion. Check an
3015 // ambiguous or inaccessible conversion.
3016 unsigned InaccessibleID = 0;
3017 unsigned AmbiguousID = 0;
3018 if (Diagnose) {
3019 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3020 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3021 }
3022 if (CheckDerivedToBaseConversion(
3023 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3024 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3025 &BasePath, IgnoreBaseAccess))
3026 return true;
3027
3028 // The conversion was successful.
3029 Kind = CK_DerivedToBase;
3030 }
3031
3032 if (Diagnose && !IsCStyleOrFunctionalCast &&
3033 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3034 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3035, __PRETTY_FUNCTION__))
3035 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3035, __PRETTY_FUNCTION__))
;
3036 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3037 << From->getSourceRange();
3038 }
3039 }
3040 } else if (const ObjCObjectPointerType *ToPtrType =
3041 ToType->getAs<ObjCObjectPointerType>()) {
3042 if (const ObjCObjectPointerType *FromPtrType =
3043 FromType->getAs<ObjCObjectPointerType>()) {
3044 // Objective-C++ conversions are always okay.
3045 // FIXME: We should have a different class of conversions for the
3046 // Objective-C++ implicit conversions.
3047 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3048 return false;
3049 } else if (FromType->isBlockPointerType()) {
3050 Kind = CK_BlockPointerToObjCPointerCast;
3051 } else {
3052 Kind = CK_CPointerToObjCPointerCast;
3053 }
3054 } else if (ToType->isBlockPointerType()) {
3055 if (!FromType->isBlockPointerType())
3056 Kind = CK_AnyPointerToBlockPointerCast;
3057 }
3058
3059 // We shouldn't fall into this case unless it's valid for other
3060 // reasons.
3061 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3062 Kind = CK_NullToPointer;
3063
3064 return false;
3065}
3066
3067/// IsMemberPointerConversion - Determines whether the conversion of the
3068/// expression From, which has the (possibly adjusted) type FromType, can be
3069/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3070/// If so, returns true and places the converted type (that might differ from
3071/// ToType in its cv-qualifiers at some level) into ConvertedType.
3072bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3073 QualType ToType,
3074 bool InOverloadResolution,
3075 QualType &ConvertedType) {
3076 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3077 if (!ToTypePtr)
3078 return false;
3079
3080 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3081 if (From->isNullPointerConstant(Context,
3082 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3083 : Expr::NPC_ValueDependentIsNull)) {
3084 ConvertedType = ToType;
3085 return true;
3086 }
3087
3088 // Otherwise, both types have to be member pointers.
3089 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3090 if (!FromTypePtr)
3091 return false;
3092
3093 // A pointer to member of B can be converted to a pointer to member of D,
3094 // where D is derived from B (C++ 4.11p2).
3095 QualType FromClass(FromTypePtr->getClass(), 0);
3096 QualType ToClass(ToTypePtr->getClass(), 0);
3097
3098 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3099 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3100 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3101 ToClass.getTypePtr());
3102 return true;
3103 }
3104
3105 return false;
3106}
3107
3108/// CheckMemberPointerConversion - Check the member pointer conversion from the
3109/// expression From to the type ToType. This routine checks for ambiguous or
3110/// virtual or inaccessible base-to-derived member pointer conversions
3111/// for which IsMemberPointerConversion has already returned true. It returns
3112/// true and produces a diagnostic if there was an error, or returns false
3113/// otherwise.
3114bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3115 CastKind &Kind,
3116 CXXCastPath &BasePath,
3117 bool IgnoreBaseAccess) {
3118 QualType FromType = From->getType();
3119 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3120 if (!FromPtrType) {
3121 // This must be a null pointer to member pointer conversion
3122 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
3123 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
3124 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
;
3125 Kind = CK_NullToMemberPointer;
3126 return false;
3127 }
3128
3129 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3130 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
3131 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132
3133 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3134 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3135
3136 // FIXME: What about dependent types?
3137 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3137, __PRETTY_FUNCTION__))
;
3138 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3138, __PRETTY_FUNCTION__))
;
3139
3140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3141 /*DetectVirtual=*/true);
3142 bool DerivationOkay =
3143 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3144 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3145, __PRETTY_FUNCTION__))
3145 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146 (void)DerivationOkay;
3147
3148 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3149 getUnqualifiedType())) {
3150 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3151 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3152 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3153 return true;
3154 }
3155
3156 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3157 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3158 << FromClass << ToClass << QualType(VBase, 0)
3159 << From->getSourceRange();
3160 return true;
3161 }
3162
3163 if (!IgnoreBaseAccess)
3164 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3165 Paths.front(),
3166 diag::err_downcast_from_inaccessible_base);
3167
3168 // Must be a base to derived member conversion.
3169 BuildBasePathArray(Paths, BasePath);
3170 Kind = CK_BaseToDerivedMemberPointer;
3171 return false;
3172}
3173
3174/// Determine whether the lifetime conversion between the two given
3175/// qualifiers sets is nontrivial.
3176static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3177 Qualifiers ToQuals) {
3178 // Converting anything to const __unsafe_unretained is trivial.
3179 if (ToQuals.hasConst() &&
3180 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3181 return false;
3182
3183 return true;
3184}
3185
3186/// Perform a single iteration of the loop for checking if a qualification
3187/// conversion is valid.
3188///
3189/// Specifically, check whether any change between the qualifiers of \p
3190/// FromType and \p ToType is permissible, given knowledge about whether every
3191/// outer layer is const-qualified.
3192static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3193 bool CStyle, bool IsTopLevel,
3194 bool &PreviousToQualsIncludeConst,
3195 bool &ObjCLifetimeConversion) {
3196 Qualifiers FromQuals = FromType.getQualifiers();
3197 Qualifiers ToQuals = ToType.getQualifiers();
3198
3199 // Ignore __unaligned qualifier if this type is void.
3200 if (ToType.getUnqualifiedType()->isVoidType())
3201 FromQuals.removeUnaligned();
3202
3203 // Objective-C ARC:
3204 // Check Objective-C lifetime conversions.
3205 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3206 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3207 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3208 ObjCLifetimeConversion = true;
3209 FromQuals.removeObjCLifetime();
3210 ToQuals.removeObjCLifetime();
3211 } else {
3212 // Qualification conversions cannot cast between different
3213 // Objective-C lifetime qualifiers.
3214 return false;
3215 }
3216 }
3217
3218 // Allow addition/removal of GC attributes but not changing GC attributes.
3219 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3220 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3221 FromQuals.removeObjCGCAttr();
3222 ToQuals.removeObjCGCAttr();
3223 }
3224
3225 // -- for every j > 0, if const is in cv 1,j then const is in cv
3226 // 2,j, and similarly for volatile.
3227 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3228 return false;
3229
3230 // If address spaces mismatch:
3231 // - in top level it is only valid to convert to addr space that is a
3232 // superset in all cases apart from C-style casts where we allow
3233 // conversions between overlapping address spaces.
3234 // - in non-top levels it is not a valid conversion.
3235 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3236 (!IsTopLevel ||
3237 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3238 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3239 return false;
3240
3241 // -- if the cv 1,j and cv 2,j are different, then const is in
3242 // every cv for 0 < k < j.
3243 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3244 !PreviousToQualsIncludeConst)
3245 return false;
3246
3247 // Keep track of whether all prior cv-qualifiers in the "to" type
3248 // include const.
3249 PreviousToQualsIncludeConst =
3250 PreviousToQualsIncludeConst && ToQuals.hasConst();
3251 return true;
3252}
3253
3254/// IsQualificationConversion - Determines whether the conversion from
3255/// an rvalue of type FromType to ToType is a qualification conversion
3256/// (C++ 4.4).
3257///
3258/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3259/// when the qualification conversion involves a change in the Objective-C
3260/// object lifetime.
3261bool
3262Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3263 bool CStyle, bool &ObjCLifetimeConversion) {
3264 FromType = Context.getCanonicalType(FromType);
3265 ToType = Context.getCanonicalType(ToType);
3266 ObjCLifetimeConversion = false;
3267
3268 // If FromType and ToType are the same type, this is not a
3269 // qualification conversion.
3270 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3271 return false;
3272
3273 // (C++ 4.4p4):
3274 // A conversion can add cv-qualifiers at levels other than the first
3275 // in multi-level pointers, subject to the following rules: [...]
3276 bool PreviousToQualsIncludeConst = true;
3277 bool UnwrappedAnyPointer = false;
3278 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3279 if (!isQualificationConversionStep(
3280 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3281 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3282 return false;
3283 UnwrappedAnyPointer = true;
3284 }
3285
3286 // We are left with FromType and ToType being the pointee types
3287 // after unwrapping the original FromType and ToType the same number
3288 // of times. If we unwrapped any pointers, and if FromType and
3289 // ToType have the same unqualified type (since we checked
3290 // qualifiers above), then this is a qualification conversion.
3291 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3292}
3293
3294/// - Determine whether this is a conversion from a scalar type to an
3295/// atomic type.
3296///
3297/// If successful, updates \c SCS's second and third steps in the conversion
3298/// sequence to finish the conversion.
3299static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3300 bool InOverloadResolution,
3301 StandardConversionSequence &SCS,
3302 bool CStyle) {
3303 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3304 if (!ToAtomic)
3305 return false;
3306
3307 StandardConversionSequence InnerSCS;
3308 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3309 InOverloadResolution, InnerSCS,
3310 CStyle, /*AllowObjCWritebackConversion=*/false))
3311 return false;
3312
3313 SCS.Second = InnerSCS.Second;
3314 SCS.setToType(1, InnerSCS.getToType(1));
3315 SCS.Third = InnerSCS.Third;
3316 SCS.QualificationIncludesObjCLifetime
3317 = InnerSCS.QualificationIncludesObjCLifetime;
3318 SCS.setToType(2, InnerSCS.getToType(2));
3319 return true;
3320}
3321
3322static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3323 CXXConstructorDecl *Constructor,
3324 QualType Type) {
3325 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3326 if (CtorType->getNumParams() > 0) {
3327 QualType FirstArg = CtorType->getParamType(0);
3328 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3329 return true;
3330 }
3331 return false;
3332}
3333
3334static OverloadingResult
3335IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3336 CXXRecordDecl *To,
3337 UserDefinedConversionSequence &User,
3338 OverloadCandidateSet &CandidateSet,
3339 bool AllowExplicit) {
3340 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3341 for (auto *D : S.LookupConstructors(To)) {
3342 auto Info = getConstructorInfo(D);
3343 if (!Info)
3344 continue;
3345
3346 bool Usable = !Info.Constructor->isInvalidDecl() &&
3347 S.isInitListConstructor(Info.Constructor);
3348 if (Usable) {
3349 // If the first argument is (a reference to) the target type,
3350 // suppress conversions.
3351 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3352 S.Context, Info.Constructor, ToType);
3353 if (Info.ConstructorTmpl)
3354 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3355 /*ExplicitArgs*/ nullptr, From,
3356 CandidateSet, SuppressUserConversions,
3357 /*PartialOverloading*/ false,
3358 AllowExplicit);
3359 else
3360 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3361 CandidateSet, SuppressUserConversions,
3362 /*PartialOverloading*/ false, AllowExplicit);
3363 }
3364 }
3365
3366 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3367
3368 OverloadCandidateSet::iterator Best;
3369 switch (auto Result =
3370 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3371 case OR_Deleted:
3372 case OR_Success: {
3373 // Record the standard conversion we used and the conversion function.
3374 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3375 QualType ThisType = Constructor->getThisType();
3376 // Initializer lists don't have conversions as such.
3377 User.Before.setAsIdentityConversion();
3378 User.HadMultipleCandidates = HadMultipleCandidates;
3379 User.ConversionFunction = Constructor;
3380 User.FoundConversionFunction = Best->FoundDecl;
3381 User.After.setAsIdentityConversion();
3382 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3383 User.After.setAllToTypes(ToType);
3384 return Result;
3385 }
3386
3387 case OR_No_Viable_Function:
3388 return OR_No_Viable_Function;
3389 case OR_Ambiguous:
3390 return OR_Ambiguous;
3391 }
3392
3393 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3393)
;
3394}
3395
3396/// Determines whether there is a user-defined conversion sequence
3397/// (C++ [over.ics.user]) that converts expression From to the type
3398/// ToType. If such a conversion exists, User will contain the
3399/// user-defined conversion sequence that performs such a conversion
3400/// and this routine will return true. Otherwise, this routine returns
3401/// false and User is unspecified.
3402///
3403/// \param AllowExplicit true if the conversion should consider C++0x
3404/// "explicit" conversion functions as well as non-explicit conversion
3405/// functions (C++0x [class.conv.fct]p2).
3406///
3407/// \param AllowObjCConversionOnExplicit true if the conversion should
3408/// allow an extra Objective-C pointer conversion on uses of explicit
3409/// constructors. Requires \c AllowExplicit to also be set.
3410static OverloadingResult
3411IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3412 UserDefinedConversionSequence &User,
3413 OverloadCandidateSet &CandidateSet,
3414 AllowedExplicit AllowExplicit,
3415 bool AllowObjCConversionOnExplicit) {
3416 assert(AllowExplicit != AllowedExplicit::None ||((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3417, __PRETTY_FUNCTION__))
3417 !AllowObjCConversionOnExplicit)((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3417, __PRETTY_FUNCTION__))
;
3418 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3419
3420 // Whether we will only visit constructors.
3421 bool ConstructorsOnly = false;
3422
3423 // If the type we are conversion to is a class type, enumerate its
3424 // constructors.
3425 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3426 // C++ [over.match.ctor]p1:
3427 // When objects of class type are direct-initialized (8.5), or
3428 // copy-initialized from an expression of the same or a
3429 // derived class type (8.5), overload resolution selects the
3430 // constructor. [...] For copy-initialization, the candidate
3431 // functions are all the converting constructors (12.3.1) of
3432 // that class. The argument list is the expression-list within
3433 // the parentheses of the initializer.
3434 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3435 (From->getType()->getAs<RecordType>() &&
3436 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3437 ConstructorsOnly = true;
3438
3439 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3440 // We're not going to find any constructors.
3441 } else if (CXXRecordDecl *ToRecordDecl
3442 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3443
3444 Expr **Args = &From;
3445 unsigned NumArgs = 1;
3446 bool ListInitializing = false;
3447 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3448 // But first, see if there is an init-list-constructor that will work.
3449 OverloadingResult Result = IsInitializerListConstructorConversion(
3450 S, From, ToType, ToRecordDecl, User, CandidateSet,
3451 AllowExplicit == AllowedExplicit::All);
3452 if (Result != OR_No_Viable_Function)
3453 return Result;
3454 // Never mind.
3455 CandidateSet.clear(
3456 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3457
3458 // If we're list-initializing, we pass the individual elements as
3459 // arguments, not the entire list.
3460 Args = InitList->getInits();
3461 NumArgs = InitList->getNumInits();
3462 ListInitializing = true;
3463 }
3464
3465 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3466 auto Info = getConstructorInfo(D);
3467 if (!Info)
3468 continue;
3469
3470 bool Usable = !Info.Constructor->isInvalidDecl();
3471 if (!ListInitializing)
3472 Usable = Usable && Info.Constructor->isConvertingConstructor(
3473 /*AllowExplicit*/ true);
3474 if (Usable) {
3475 bool SuppressUserConversions = !ConstructorsOnly;
3476 if (SuppressUserConversions && ListInitializing) {
3477 SuppressUserConversions = false;
3478 if (NumArgs == 1) {
3479 // If the first argument is (a reference to) the target type,
3480 // suppress conversions.
3481 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3482 S.Context, Info.Constructor, ToType);
3483 }
3484 }
3485 if (Info.ConstructorTmpl)
3486 S.AddTemplateOverloadCandidate(
3487 Info.ConstructorTmpl, Info.FoundDecl,
3488 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3489 CandidateSet, SuppressUserConversions,
3490 /*PartialOverloading*/ false,
3491 AllowExplicit == AllowedExplicit::All);
3492 else
3493 // Allow one user-defined conversion when user specifies a
3494 // From->ToType conversion via an static cast (c-style, etc).
3495 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3496 llvm::makeArrayRef(Args, NumArgs),
3497 CandidateSet, SuppressUserConversions,
3498 /*PartialOverloading*/ false,
3499 AllowExplicit == AllowedExplicit::All);
3500 }
3501 }
3502 }
3503 }
3504
3505 // Enumerate conversion functions, if we're allowed to.
3506 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3507 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3508 // No conversion functions from incomplete types.
3509 } else if (const RecordType *FromRecordType =
3510 From->getType()->getAs<RecordType>()) {
3511 if (CXXRecordDecl *FromRecordDecl
3512 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3513 // Add all of the conversion functions as candidates.
3514 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3515 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3516 DeclAccessPair FoundDecl = I.getPair();
3517 NamedDecl *D = FoundDecl.getDecl();
3518 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3519 if (isa<UsingShadowDecl>(D))
3520 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3521
3522 CXXConversionDecl *Conv;
3523 FunctionTemplateDecl *ConvTemplate;
3524 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3525 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3526 else
3527 Conv = cast<CXXConversionDecl>(D);
3528
3529 if (ConvTemplate)
3530 S.AddTemplateConversionCandidate(
3531 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3532 CandidateSet, AllowObjCConversionOnExplicit,
3533 AllowExplicit != AllowedExplicit::None);
3534 else
3535 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3536 CandidateSet, AllowObjCConversionOnExplicit,
3537 AllowExplicit != AllowedExplicit::None);
3538 }
3539 }
3540 }
3541
3542 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3543
3544 OverloadCandidateSet::iterator Best;
3545 switch (auto Result =
3546 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3547 case OR_Success:
3548 case OR_Deleted:
3549 // Record the standard conversion we used and the conversion function.
3550 if (CXXConstructorDecl *Constructor
3551 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3552 // C++ [over.ics.user]p1:
3553 // If the user-defined conversion is specified by a
3554 // constructor (12.3.1), the initial standard conversion
3555 // sequence converts the source type to the type required by
3556 // the argument of the constructor.
3557 //
3558 QualType ThisType = Constructor->getThisType();
3559 if (isa<InitListExpr>(From)) {
3560 // Initializer lists don't have conversions as such.
3561 User.Before.setAsIdentityConversion();
3562 } else {
3563 if (Best->Conversions[0].isEllipsis())
3564 User.EllipsisConversion = true;
3565 else {
3566 User.Before = Best->Conversions[0].Standard;
3567 User.EllipsisConversion = false;
3568 }
3569 }
3570 User.HadMultipleCandidates = HadMultipleCandidates;
3571 User.ConversionFunction = Constructor;
3572 User.FoundConversionFunction = Best->FoundDecl;
3573 User.After.setAsIdentityConversion();
3574 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3575 User.After.setAllToTypes(ToType);
3576 return Result;
3577 }
3578 if (CXXConversionDecl *Conversion
3579 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3580 // C++ [over.ics.user]p1:
3581 //
3582 // [...] If the user-defined conversion is specified by a
3583 // conversion function (12.3.2), the initial standard
3584 // conversion sequence converts the source type to the
3585 // implicit object parameter of the conversion function.
3586 User.Before = Best->Conversions[0].Standard;
3587 User.HadMultipleCandidates = HadMultipleCandidates;
3588 User.ConversionFunction = Conversion;
3589 User.FoundConversionFunction = Best->FoundDecl;
3590 User.EllipsisConversion = false;
3591
3592 // C++ [over.ics.user]p2:
3593 // The second standard conversion sequence converts the
3594 // result of the user-defined conversion to the target type
3595 // for the sequence. Since an implicit conversion sequence
3596 // is an initialization, the special rules for
3597 // initialization by user-defined conversion apply when
3598 // selecting the best user-defined conversion for a
3599 // user-defined conversion sequence (see 13.3.3 and
3600 // 13.3.3.1).
3601 User.After = Best->FinalConversion;
3602 return Result;
3603 }
3604 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3604)
;
3605
3606 case OR_No_Viable_Function:
3607 return OR_No_Viable_Function;
3608
3609 case OR_Ambiguous:
3610 return OR_Ambiguous;
3611 }
3612
3613 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 3613)
;
3614}
3615
3616bool
3617Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3618 ImplicitConversionSequence ICS;
3619 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3620 OverloadCandidateSet::CSK_Normal);
3621 OverloadingResult OvResult =
3622 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3623 CandidateSet, AllowedExplicit::None, false);
3624
3625 if (!(OvResult == OR_Ambiguous ||
3626 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3627 return false;
3628
3629 auto Cands = CandidateSet.CompleteCandidates(
3630 *this,
3631 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3632 From);
3633 if (OvResult == OR_Ambiguous)
3634 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3635 << From->getType() << ToType << From->getSourceRange();
3636 else { // OR_No_Viable_Function && !CandidateSet.empty()
3637 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3638 diag::err_typecheck_nonviable_condition_incomplete,
3639 From->getType(), From->getSourceRange()))
3640 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3641 << false << From->getType() << From->getSourceRange() << ToType;
3642 }
3643
3644 CandidateSet.NoteCandidates(
3645 *this, From, Cands);
3646 return true;
3647}
3648
3649// Helper for compareConversionFunctions that gets the FunctionType that the
3650// conversion-operator return value 'points' to, or nullptr.
3651static const FunctionType *
3652getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3653 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3654 const PointerType *RetPtrTy =
3655 ConvFuncTy->getReturnType()->getAs<PointerType>();
3656
3657 if (!RetPtrTy)
3658 return nullptr;
3659
3660 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3661}
3662
3663/// Compare the user-defined conversion functions or constructors
3664/// of two user-defined conversion sequences to determine whether any ordering
3665/// is possible.
3666static ImplicitConversionSequence::CompareKind
3667compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3668 FunctionDecl *Function2) {
3669 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3670 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3671 if (!Conv1 || !Conv2)
3672 return ImplicitConversionSequence::Indistinguishable;
3673
3674 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3675 return ImplicitConversionSequence::Indistinguishable;
3676
3677 // Objective-C++:
3678 // If both conversion functions are implicitly-declared conversions from
3679 // a lambda closure type to a function pointer and a block pointer,
3680 // respectively, always prefer the conversion to a function pointer,
3681 // because the function pointer is more lightweight and is more likely
3682 // to keep code working.
3683 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3684 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3685 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3686 if (Block1 != Block2)
3687 return Block1 ? ImplicitConversionSequence::Worse
3688 : ImplicitConversionSequence::Better;
3689 }
3690
3691 // In order to support multiple calling conventions for the lambda conversion
3692 // operator (such as when the free and member function calling convention is
3693 // different), prefer the 'free' mechanism, followed by the calling-convention
3694 // of operator(). The latter is in place to support the MSVC-like solution of
3695 // defining ALL of the possible conversions in regards to calling-convention.
3696 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3697 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3698
3699 if (Conv1FuncRet && Conv2FuncRet &&
3700 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3701 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3702 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3703
3704 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3705 const FunctionProtoType *CallOpProto =
3706 CallOp->getType()->getAs<FunctionProtoType>();
3707
3708 CallingConv CallOpCC =
3709 CallOp->getType()->getAs<FunctionType>()->getCallConv();
3710 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3711 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3712 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3713 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3714
3715 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3716 for (CallingConv CC : PrefOrder) {
3717 if (Conv1CC == CC)
3718 return ImplicitConversionSequence::Better;
3719 if (Conv2CC == CC)
3720 return ImplicitConversionSequence::Worse;
3721 }
3722 }
3723
3724 return ImplicitConversionSequence::Indistinguishable;
3725}
3726
3727static bool hasDeprecatedStringLiteralToCharPtrConversion(
3728 const ImplicitConversionSequence &ICS) {
3729 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3730 (ICS.isUserDefined() &&
3731 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3732}
3733
3734/// CompareImplicitConversionSequences - Compare two implicit
3735/// conversion sequences to determine whether one is better than the
3736/// other or if they are indistinguishable (C++ 13.3.3.2).
3737static ImplicitConversionSequence::CompareKind
3738CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3739 const ImplicitConversionSequence& ICS1,
3740 const ImplicitConversionSequence& ICS2)
3741{
3742 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3743 // conversion sequences (as defined in 13.3.3.1)
3744 // -- a standard conversion sequence (13.3.3.1.1) is a better
3745 // conversion sequence than a user-defined conversion sequence or
3746 // an ellipsis conversion sequence, and
3747 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3748 // conversion sequence than an ellipsis conversion sequence
3749 // (13.3.3.1.3).
3750 //
3751 // C++0x [over.best.ics]p10:
3752 // For the purpose of ranking implicit conversion sequences as
3753 // described in 13.3.3.2, the ambiguous conversion sequence is
3754 // treated as a user-defined sequence that is indistinguishable
3755 // from any other user-defined conversion sequence.
3756
3757 // String literal to 'char *' conversion has been deprecated in C++03. It has
3758 // been removed from C++11. We still accept this conversion, if it happens at
3759 // the best viable function. Otherwise, this conversion is considered worse
3760 // than ellipsis conversion. Consider this as an extension; this is not in the
3761 // standard. For example:
3762 //
3763 // int &f(...); // #1
3764 // void f(char*); // #2
3765 // void g() { int &r = f("foo"); }
3766 //
3767 // In C++03, we pick #2 as the best viable function.
3768 // In C++11, we pick #1 as the best viable function, because ellipsis
3769 // conversion is better than string-literal to char* conversion (since there
3770 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3771 // convert arguments, #2 would be the best viable function in C++11.
3772 // If the best viable function has this conversion, a warning will be issued
3773 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3774
3775 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3776 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3777 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3778 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3779 ? ImplicitConversionSequence::Worse
3780 : ImplicitConversionSequence::Better;
3781
3782 if (ICS1.getKindRank() < ICS2.getKindRank())
3783 return ImplicitConversionSequence::Better;
3784 if (ICS2.getKindRank() < ICS1.getKindRank())
3785 return ImplicitConversionSequence::Worse;
3786
3787 // The following checks require both conversion sequences to be of
3788 // the same kind.
3789 if (ICS1.getKind() != ICS2.getKind())
3790 return ImplicitConversionSequence::Indistinguishable;
3791
3792 ImplicitConversionSequence::CompareKind Result =
3793 ImplicitConversionSequence::Indistinguishable;
3794
3795 // Two implicit conversion sequences of the same form are
3796 // indistinguishable conversion sequences unless one of the
3797 // following rules apply: (C++ 13.3.3.2p3):
3798
3799 // List-initialization sequence L1 is a better conversion sequence than
3800 // list-initialization sequence L2 if:
3801 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3802 // if not that,
3803 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3804 // and N1 is smaller than N2.,
3805 // even if one of the other rules in this paragraph would otherwise apply.
3806 if (!ICS1.isBad()) {
3807 if (ICS1.isStdInitializerListElement() &&
3808 !ICS2.isStdInitializerListElement())
3809 return ImplicitConversionSequence::Better;
3810 if (!ICS1.isStdInitializerListElement() &&
3811 ICS2.isStdInitializerListElement())
3812 return ImplicitConversionSequence::Worse;
3813 }
3814
3815 if (ICS1.isStandard())
3816 // Standard conversion sequence S1 is a better conversion sequence than
3817 // standard conversion sequence S2 if [...]
3818 Result = CompareStandardConversionSequences(S, Loc,
3819 ICS1.Standard, ICS2.Standard);
3820 else if (ICS1.isUserDefined()) {
3821 // User-defined conversion sequence U1 is a better conversion
3822 // sequence than another user-defined conversion sequence U2 if
3823 // they contain the same user-defined conversion function or
3824 // constructor and if the second standard conversion sequence of
3825 // U1 is better than the second standard conversion sequence of
3826 // U2 (C++ 13.3.3.2p3).
3827 if (ICS1.UserDefined.ConversionFunction ==
3828 ICS2.UserDefined.ConversionFunction)
3829 Result = CompareStandardConversionSequences(S, Loc,
3830 ICS1.UserDefined.After,
3831 ICS2.UserDefined.After);
3832 else
3833 Result = compareConversionFunctions(S,
3834 ICS1.UserDefined.ConversionFunction,
3835 ICS2.UserDefined.ConversionFunction);
3836 }
3837
3838 return Result;
3839}
3840
3841// Per 13.3.3.2p3, compare the given standard conversion sequences to
3842// determine if one is a proper subset of the other.
3843static ImplicitConversionSequence::CompareKind
3844compareStandardConversionSubsets(ASTContext &Context,
3845 const StandardConversionSequence& SCS1,
3846 const StandardConversionSequence& SCS2) {
3847 ImplicitConversionSequence::CompareKind Result
3848 = ImplicitConversionSequence::Indistinguishable;
3849
3850 // the identity conversion sequence is considered to be a subsequence of
3851 // any non-identity conversion sequence
3852 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3853 return ImplicitConversionSequence::Better;
3854 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3855 return ImplicitConversionSequence::Worse;
3856
3857 if (SCS1.Second != SCS2.Second) {
3858 if (SCS1.Second == ICK_Identity)
3859 Result = ImplicitConversionSequence::Better;
3860 else if (SCS2.Second == ICK_Identity)
3861 Result = ImplicitConversionSequence::Worse;
3862 else
3863 return ImplicitConversionSequence::Indistinguishable;
3864 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3865 return ImplicitConversionSequence::Indistinguishable;
3866
3867 if (SCS1.Third == SCS2.Third) {
3868 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3869 : ImplicitConversionSequence::Indistinguishable;
3870 }
3871
3872 if (SCS1.Third == ICK_Identity)
3873 return Result == ImplicitConversionSequence::Worse
3874 ? ImplicitConversionSequence::Indistinguishable
3875 : ImplicitConversionSequence::Better;
3876
3877 if (SCS2.Third == ICK_Identity)
3878 return Result == ImplicitConversionSequence::Better
3879 ? ImplicitConversionSequence::Indistinguishable
3880 : ImplicitConversionSequence::Worse;
3881
3882 return ImplicitConversionSequence::Indistinguishable;
3883}
3884
3885/// Determine whether one of the given reference bindings is better
3886/// than the other based on what kind of bindings they are.
3887static bool
3888isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3889 const StandardConversionSequence &SCS2) {
3890 // C++0x [over.ics.rank]p3b4:
3891 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3892 // implicit object parameter of a non-static member function declared
3893 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3894 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3895 // lvalue reference to a function lvalue and S2 binds an rvalue
3896 // reference*.
3897 //
3898 // FIXME: Rvalue references. We're going rogue with the above edits,
3899 // because the semantics in the current C++0x working paper (N3225 at the
3900 // time of this writing) break the standard definition of std::forward
3901 // and std::reference_wrapper when dealing with references to functions.
3902 // Proposed wording changes submitted to CWG for consideration.
3903 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3904 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3905 return false;
3906
3907 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3908 SCS2.IsLvalueReference) ||
3909 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3910 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3911}
3912
3913enum class FixedEnumPromotion {
3914 None,
3915 ToUnderlyingType,
3916 ToPromotedUnderlyingType
3917};
3918
3919/// Returns kind of fixed enum promotion the \a SCS uses.
3920static FixedEnumPromotion
3921getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3922
3923 if (SCS.Second != ICK_Integral_Promotion)
28
Assuming field 'Second' is equal to ICK_Integral_Promotion
29
Taking false branch
3924 return FixedEnumPromotion::None;
3925
3926 QualType FromType = SCS.getFromType();
3927 if (!FromType->isEnumeralType())
30
Calling 'Type::isEnumeralType'
33
Returning from 'Type::isEnumeralType'
34
Taking false branch
3928 return FixedEnumPromotion::None;
3929
3930 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
35
Assuming the object is not a 'EnumType'
36
Called C++ object pointer is null
3931 if (!Enum->isFixed())
3932 return FixedEnumPromotion::None;
3933
3934 QualType UnderlyingType = Enum->getIntegerType();
3935 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3936 return FixedEnumPromotion::ToUnderlyingType;
3937
3938 return FixedEnumPromotion::ToPromotedUnderlyingType;
3939}
3940
3941/// CompareStandardConversionSequences - Compare two standard
3942/// conversion sequences to determine whether one is better than the
3943/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3944static ImplicitConversionSequence::CompareKind
3945CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3946 const StandardConversionSequence& SCS1,
3947 const StandardConversionSequence& SCS2)
3948{
3949 // Standard conversion sequence S1 is a better conversion sequence
3950 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3951
3952 // -- S1 is a proper subsequence of S2 (comparing the conversion
3953 // sequences in the canonical form defined by 13.3.3.1.1,
3954 // excluding any Lvalue Transformation; the identity conversion
3955 // sequence is considered to be a subsequence of any
3956 // non-identity conversion sequence) or, if not that,
3957 if (ImplicitConversionSequence::CompareKind CK
22.1
'CK' is 0
22.1
'CK' is 0
23
Taking false branch
3958 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3959 return CK; 3960 3961 // -- the rank of S1 is better than the rank of S2 (by the rules 3962 // defined below), or, if not that, 3963 ImplicitConversionRank Rank1 = SCS1.getRank(); 3964 ImplicitConversionRank Rank2 = SCS2.getRank(); 3965 if (Rank1
23.1
'Rank1' is >= 'Rank2'
23.1
'Rank1' is >= 'Rank2'
< Rank2)
24
Taking false branch
3966 return ImplicitConversionSequence::Better; 3967 else if (Rank2
24.1
'Rank2' is >= 'Rank1'
24.1
'Rank2' is >= 'Rank1'
< Rank1)
25
Taking false branch
3968 return ImplicitConversionSequence::Worse; 3969 3970 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3971 // are indistinguishable unless one of the following rules 3972 // applies: 3973 3974 // A conversion that is not a conversion of a pointer, or 3975 // pointer to member, to bool is better than another conversion 3976 // that is such a conversion. 3977 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
26
Taking false branch
3978 return SCS2.isPointerConversionToBool() 3979 ? ImplicitConversionSequence::Better 3980 : ImplicitConversionSequence::Worse; 3981 3982 // C++14 [over.ics.rank]p4b2: 3983 // This is retroactively applied to C++11 by CWG 1601. 3984 // 3985 // A conversion that promotes an enumeration whose underlying type is fixed 3986 // to its underlying type is better than one that promotes to the promoted 3987 // underlying type, if the two are different. 3988 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
27
Calling 'getFixedEnumPromtion'
3989 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3990 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3991 FEP1 != FEP2) 3992 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3993 ? ImplicitConversionSequence::Better 3994 : ImplicitConversionSequence::Worse; 3995 3996 // C++ [over.ics.rank]p4b2: 3997 // 3998 // If class B is derived directly or indirectly from class A, 3999 // conversion of B* to A* is better than conversion of B* to 4000 // void*, and conversion of A* to void* is better than conversion 4001 // of B* to void*. 4002 bool SCS1ConvertsToVoid 4003 = SCS1.isPointerConversionToVoidPointer(S.Context); 4004 bool SCS2ConvertsToVoid 4005 = SCS2.isPointerConversionToVoidPointer(S.Context); 4006 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4007 // Exactly one of the conversion sequences is a conversion to 4008 // a void pointer; it's the worse conversion. 4009 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4010 : ImplicitConversionSequence::Worse; 4011 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4012 // Neither conversion sequence converts to a void pointer; compare 4013 // their derived-to-base conversions. 4014 if (ImplicitConversionSequence::CompareKind DerivedCK 4015 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4016 return DerivedCK; 4017 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4018 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4019 // Both conversion sequences are conversions to void 4020 // pointers. Compare the source types to determine if there's an 4021 // inheritance relationship in their sources. 4022 QualType FromType1 = SCS1.getFromType(); 4023 QualType FromType2 = SCS2.getFromType(); 4024 4025 // Adjust the types we're converting from via the array-to-pointer 4026 // conversion, if we need to. 4027 if (SCS1.First == ICK_Array_To_Pointer) 4028 FromType1 = S.Context.getArrayDecayedType(FromType1); 4029 if (SCS2.First == ICK_Array_To_Pointer) 4030 FromType2 = S.Context.getArrayDecayedType(FromType2); 4031 4032 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4033 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4034 4035 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4036 return ImplicitConversionSequence::Better; 4037 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4038 return ImplicitConversionSequence::Worse; 4039 4040 // Objective-C++: If one interface is more specific than the 4041 // other, it is the better one. 4042 const ObjCObjectPointerType* FromObjCPtr1 4043 = FromType1->getAs<ObjCObjectPointerType>(); 4044 const ObjCObjectPointerType* FromObjCPtr2 4045 = FromType2->getAs<ObjCObjectPointerType>(); 4046 if (FromObjCPtr1 && FromObjCPtr2) { 4047 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4048 FromObjCPtr2); 4049 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4050 FromObjCPtr1); 4051 if (AssignLeft != AssignRight) { 4052 return AssignLeft? ImplicitConversionSequence::Better 4053 : ImplicitConversionSequence::Worse; 4054 } 4055 } 4056 } 4057 4058 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4059 // Check for a better reference binding based on the kind of bindings. 4060 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4061 return ImplicitConversionSequence::Better; 4062 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4063 return ImplicitConversionSequence::Worse; 4064 } 4065 4066 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4067 // bullet 3). 4068 if (ImplicitConversionSequence::CompareKind QualCK 4069 = CompareQualificationConversions(S, SCS1, SCS2)) 4070 return QualCK; 4071 4072 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4073 // C++ [over.ics.rank]p3b4: 4074 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4075 // which the references refer are the same type except for 4076 // top-level cv-qualifiers, and the type to which the reference 4077 // initialized by S2 refers is more cv-qualified than the type 4078 // to which the reference initialized by S1 refers. 4079 QualType T1 = SCS1.getToType(2); 4080 QualType T2 = SCS2.getToType(2); 4081 T1 = S.Context.getCanonicalType(T1); 4082 T2 = S.Context.getCanonicalType(T2); 4083 Qualifiers T1Quals, T2Quals; 4084 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4085 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4086 if (UnqualT1 == UnqualT2) { 4087 // Objective-C++ ARC: If the references refer to objects with different 4088 // lifetimes, prefer bindings that don't change lifetime. 4089 if (SCS1.ObjCLifetimeConversionBinding != 4090 SCS2.ObjCLifetimeConversionBinding) { 4091 return SCS1.ObjCLifetimeConversionBinding 4092 ? ImplicitConversionSequence::Worse 4093 : ImplicitConversionSequence::Better; 4094 } 4095 4096 // If the type is an array type, promote the element qualifiers to the 4097 // type for comparison. 4098 if (isa<ArrayType>(T1) && T1Quals) 4099 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4100 if (isa<ArrayType>(T2) && T2Quals) 4101 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4102 if (T2.isMoreQualifiedThan(T1)) 4103 return ImplicitConversionSequence::Better; 4104 if (T1.isMoreQualifiedThan(T2)) 4105 return ImplicitConversionSequence::Worse; 4106 } 4107 } 4108 4109 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4110 // floating-to-integral conversion if the integral conversion 4111 // is between types of the same size. 4112 // For example: 4113 // void f(float); 4114 // void f(int); 4115 // int main { 4116 // long a; 4117 // f(a); 4118 // } 4119 // Here, MSVC will call f(int) instead of generating a compile error 4120 // as clang will do in standard mode. 4121 if (S.getLangOpts().MSVCCompat && 4122 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4123 SCS1.Second == ICK_Integral_Conversion && 4124 SCS2.Second == ICK_Floating_Integral && 4125 S.Context.getTypeSize(SCS1.getFromType()) == 4126 S.Context.getTypeSize(SCS1.getToType(2))) 4127 return ImplicitConversionSequence::Better; 4128 4129 // Prefer a compatible vector conversion over a lax vector conversion 4130 // For example: 4131 // 4132 // typedef float __v4sf __attribute__((__vector_size__(16))); 4133 // void f(vector float); 4134 // void f(vector signed int); 4135 // int main() { 4136 // __v4sf a; 4137 // f(a); 4138 // } 4139 // Here, we'd like to choose f(vector float) and not 4140 // report an ambiguous call error 4141 if (SCS1.Second == ICK_Vector_Conversion && 4142 SCS2.Second == ICK_Vector_Conversion) { 4143 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4144 SCS1.getFromType(), SCS1.getToType(2)); 4145 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4146 SCS2.getFromType(), SCS2.getToType(2)); 4147 4148 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4149 return SCS1IsCompatibleVectorConversion 4150 ? ImplicitConversionSequence::Better 4151 : ImplicitConversionSequence::Worse; 4152 } 4153 4154 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4155 SCS2.Second == ICK_SVE_Vector_Conversion) { 4156 bool SCS1IsCompatibleSVEVectorConversion = 4157 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4158 bool SCS2IsCompatibleSVEVectorConversion = 4159 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4160 4161 if (SCS1IsCompatibleSVEVectorConversion != 4162 SCS2IsCompatibleSVEVectorConversion) 4163 return SCS1IsCompatibleSVEVectorConversion 4164 ? ImplicitConversionSequence::Better 4165 : ImplicitConversionSequence::Worse; 4166 } 4167 4168 return ImplicitConversionSequence::Indistinguishable; 4169} 4170 4171/// CompareQualificationConversions - Compares two standard conversion 4172/// sequences to determine whether they can be ranked based on their 4173/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4174static ImplicitConversionSequence::CompareKind 4175CompareQualificationConversions(Sema &S, 4176 const StandardConversionSequence& SCS1, 4177 const StandardConversionSequence& SCS2) { 4178 // C++ 13.3.3.2p3: 4179 // -- S1 and S2 differ only in their qualification conversion and 4180 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4181 // cv-qualification signature of type T1 is a proper subset of 4182 // the cv-qualification signature of type T2, and S1 is not the 4183 // deprecated string literal array-to-pointer conversion (4.2). 4184 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4185 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4186 return ImplicitConversionSequence::Indistinguishable; 4187 4188 // FIXME: the example in the standard doesn't use a qualification 4189 // conversion (!) 4190 QualType T1 = SCS1.getToType(2); 4191 QualType T2 = SCS2.getToType(2); 4192 T1 = S.Context.getCanonicalType(T1); 4193 T2 = S.Context.getCanonicalType(T2); 4194 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4194, __PRETTY_FUNCTION__))
; 4195 Qualifiers T1Quals, T2Quals; 4196 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4197 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4198 4199 // If the types are the same, we won't learn anything by unwrapping 4200 // them. 4201 if (UnqualT1 == UnqualT2) 4202 return ImplicitConversionSequence::Indistinguishable; 4203 4204 ImplicitConversionSequence::CompareKind Result 4205 = ImplicitConversionSequence::Indistinguishable; 4206 4207 // Objective-C++ ARC: 4208 // Prefer qualification conversions not involving a change in lifetime 4209 // to qualification conversions that do not change lifetime. 4210 if (SCS1.QualificationIncludesObjCLifetime != 4211 SCS2.QualificationIncludesObjCLifetime) { 4212 Result = SCS1.QualificationIncludesObjCLifetime 4213 ? ImplicitConversionSequence::Worse 4214 : ImplicitConversionSequence::Better; 4215 } 4216 4217 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4218 // Within each iteration of the loop, we check the qualifiers to 4219 // determine if this still looks like a qualification 4220 // conversion. Then, if all is well, we unwrap one more level of 4221 // pointers or pointers-to-members and do it all again 4222 // until there are no more pointers or pointers-to-members left 4223 // to unwrap. This essentially mimics what 4224 // IsQualificationConversion does, but here we're checking for a 4225 // strict subset of qualifiers. 4226 if (T1.getQualifiers().withoutObjCLifetime() == 4227 T2.getQualifiers().withoutObjCLifetime()) 4228 // The qualifiers are the same, so this doesn't tell us anything 4229 // about how the sequences rank. 4230 // ObjC ownership quals are omitted above as they interfere with 4231 // the ARC overload rule. 4232 ; 4233 else if (T2.isMoreQualifiedThan(T1)) { 4234 // T1 has fewer qualifiers, so it could be the better sequence. 4235 if (Result == ImplicitConversionSequence::Worse) 4236 // Neither has qualifiers that are a subset of the other's 4237 // qualifiers. 4238 return ImplicitConversionSequence::Indistinguishable; 4239 4240 Result = ImplicitConversionSequence::Better; 4241 } else if (T1.isMoreQualifiedThan(T2)) { 4242 // T2 has fewer qualifiers, so it could be the better sequence. 4243 if (Result == ImplicitConversionSequence::Better) 4244 // Neither has qualifiers that are a subset of the other's 4245 // qualifiers. 4246 return ImplicitConversionSequence::Indistinguishable; 4247 4248 Result = ImplicitConversionSequence::Worse; 4249 } else { 4250 // Qualifiers are disjoint. 4251 return ImplicitConversionSequence::Indistinguishable; 4252 } 4253 4254 // If the types after this point are equivalent, we're done. 4255 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4256 break; 4257 } 4258 4259 // Check that the winning standard conversion sequence isn't using 4260 // the deprecated string literal array to pointer conversion. 4261 switch (Result) { 4262 case ImplicitConversionSequence::Better: 4263 if (SCS1.DeprecatedStringLiteralToCharPtr) 4264 Result = ImplicitConversionSequence::Indistinguishable; 4265 break; 4266 4267 case ImplicitConversionSequence::Indistinguishable: 4268 break; 4269 4270 case ImplicitConversionSequence::Worse: 4271 if (SCS2.DeprecatedStringLiteralToCharPtr) 4272 Result = ImplicitConversionSequence::Indistinguishable; 4273 break; 4274 } 4275 4276 return Result; 4277} 4278 4279/// CompareDerivedToBaseConversions - Compares two standard conversion 4280/// sequences to determine whether they can be ranked based on their 4281/// various kinds of derived-to-base conversions (C++ 4282/// [over.ics.rank]p4b3). As part of these checks, we also look at 4283/// conversions between Objective-C interface types. 4284static ImplicitConversionSequence::CompareKind 4285CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4286 const StandardConversionSequence& SCS1, 4287 const StandardConversionSequence& SCS2) { 4288 QualType FromType1 = SCS1.getFromType(); 4289 QualType ToType1 = SCS1.getToType(1); 4290 QualType FromType2 = SCS2.getFromType(); 4291 QualType ToType2 = SCS2.getToType(1); 4292 4293 // Adjust the types we're converting from via the array-to-pointer 4294 // conversion, if we need to. 4295 if (SCS1.First == ICK_Array_To_Pointer) 4296 FromType1 = S.Context.getArrayDecayedType(FromType1); 4297 if (SCS2.First == ICK_Array_To_Pointer) 4298 FromType2 = S.Context.getArrayDecayedType(FromType2); 4299 4300 // Canonicalize all of the types. 4301 FromType1 = S.Context.getCanonicalType(FromType1); 4302 ToType1 = S.Context.getCanonicalType(ToType1); 4303 FromType2 = S.Context.getCanonicalType(FromType2); 4304 ToType2 = S.Context.getCanonicalType(ToType2); 4305 4306 // C++ [over.ics.rank]p4b3: 4307 // 4308 // If class B is derived directly or indirectly from class A and 4309 // class C is derived directly or indirectly from B, 4310 // 4311 // Compare based on pointer conversions. 4312 if (SCS1.Second == ICK_Pointer_Conversion && 4313 SCS2.Second == ICK_Pointer_Conversion && 4314 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4315 FromType1->isPointerType() && FromType2->isPointerType() && 4316 ToType1->isPointerType() && ToType2->isPointerType()) { 4317 QualType FromPointee1 = 4318 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4319 QualType ToPointee1 = 4320 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4321 QualType FromPointee2 = 4322 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4323 QualType ToPointee2 = 4324 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4325 4326 // -- conversion of C* to B* is better than conversion of C* to A*, 4327 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4328 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4329 return ImplicitConversionSequence::Better; 4330 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4331 return ImplicitConversionSequence::Worse; 4332 } 4333 4334 // -- conversion of B* to A* is better than conversion of C* to A*, 4335 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4336 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4337 return ImplicitConversionSequence::Better; 4338 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4339 return ImplicitConversionSequence::Worse; 4340 } 4341 } else if (SCS1.Second == ICK_Pointer_Conversion && 4342 SCS2.Second == ICK_Pointer_Conversion) { 4343 const ObjCObjectPointerType *FromPtr1 4344 = FromType1->getAs<ObjCObjectPointerType>(); 4345 const ObjCObjectPointerType *FromPtr2 4346 = FromType2->getAs<ObjCObjectPointerType>(); 4347 const ObjCObjectPointerType *ToPtr1 4348 = ToType1->getAs<ObjCObjectPointerType>(); 4349 const ObjCObjectPointerType *ToPtr2 4350 = ToType2->getAs<ObjCObjectPointerType>(); 4351 4352 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4353 // Apply the same conversion ranking rules for Objective-C pointer types 4354 // that we do for C++ pointers to class types. However, we employ the 4355 // Objective-C pseudo-subtyping relationship used for assignment of 4356 // Objective-C pointer types. 4357 bool FromAssignLeft 4358 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4359 bool FromAssignRight 4360 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4361 bool ToAssignLeft 4362 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4363 bool ToAssignRight 4364 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4365 4366 // A conversion to an a non-id object pointer type or qualified 'id' 4367 // type is better than a conversion to 'id'. 4368 if (ToPtr1->isObjCIdType() && 4369 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4370 return ImplicitConversionSequence::Worse; 4371 if (ToPtr2->isObjCIdType() && 4372 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4373 return ImplicitConversionSequence::Better; 4374 4375 // A conversion to a non-id object pointer type is better than a 4376 // conversion to a qualified 'id' type 4377 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4378 return ImplicitConversionSequence::Worse; 4379 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4380 return ImplicitConversionSequence::Better; 4381 4382 // A conversion to an a non-Class object pointer type or qualified 'Class' 4383 // type is better than a conversion to 'Class'. 4384 if (ToPtr1->isObjCClassType() && 4385 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4386 return ImplicitConversionSequence::Worse; 4387 if (ToPtr2->isObjCClassType() && 4388 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4389 return ImplicitConversionSequence::Better; 4390 4391 // A conversion to a non-Class object pointer type is better than a 4392 // conversion to a qualified 'Class' type. 4393 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4394 return ImplicitConversionSequence::Worse; 4395 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4396 return ImplicitConversionSequence::Better; 4397 4398 // -- "conversion of C* to B* is better than conversion of C* to A*," 4399 if (S.Context.hasSameType(FromType1, FromType2) && 4400 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4401 (ToAssignLeft != ToAssignRight)) { 4402 if (FromPtr1->isSpecialized()) { 4403 // "conversion of B<A> * to B * is better than conversion of B * to 4404 // C *. 4405 bool IsFirstSame = 4406 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4407 bool IsSecondSame = 4408 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4409 if (IsFirstSame) { 4410 if (!IsSecondSame) 4411 return ImplicitConversionSequence::Better; 4412 } else if (IsSecondSame) 4413 return ImplicitConversionSequence::Worse; 4414 } 4415 return ToAssignLeft? ImplicitConversionSequence::Worse 4416 : ImplicitConversionSequence::Better; 4417 } 4418 4419 // -- "conversion of B* to A* is better than conversion of C* to A*," 4420 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4421 (FromAssignLeft != FromAssignRight)) 4422 return FromAssignLeft? ImplicitConversionSequence::Better 4423 : ImplicitConversionSequence::Worse; 4424 } 4425 } 4426 4427 // Ranking of member-pointer types. 4428 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4429 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4430 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4431 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4432 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4433 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4434 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4435 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4436 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4437 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4438 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4439 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4440 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4441 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4442 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4443 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4444 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4445 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4446 return ImplicitConversionSequence::Worse; 4447 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4448 return ImplicitConversionSequence::Better; 4449 } 4450 // conversion of B::* to C::* is better than conversion of A::* to C::* 4451 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4452 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4453 return ImplicitConversionSequence::Better; 4454 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4455 return ImplicitConversionSequence::Worse; 4456 } 4457 } 4458 4459 if (SCS1.Second == ICK_Derived_To_Base) { 4460 // -- conversion of C to B is better than conversion of C to A, 4461 // -- binding of an expression of type C to a reference of type 4462 // B& is better than binding an expression of type C to a 4463 // reference of type A&, 4464 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4465 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4466 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4467 return ImplicitConversionSequence::Better; 4468 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4469 return ImplicitConversionSequence::Worse; 4470 } 4471 4472 // -- conversion of B to A is better than conversion of C to A. 4473 // -- binding of an expression of type B to a reference of type 4474 // A& is better than binding an expression of type C to a 4475 // reference of type A&, 4476 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4477 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4478 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4479 return ImplicitConversionSequence::Better; 4480 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4481 return ImplicitConversionSequence::Worse; 4482 } 4483 } 4484 4485 return ImplicitConversionSequence::Indistinguishable; 4486} 4487 4488/// Determine whether the given type is valid, e.g., it is not an invalid 4489/// C++ class. 4490static bool isTypeValid(QualType T) { 4491 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4492 return !Record->isInvalidDecl(); 4493 4494 return true; 4495} 4496 4497static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4498 if (!T.getQualifiers().hasUnaligned()) 4499 return T; 4500 4501 Qualifiers Q; 4502 T = Ctx.getUnqualifiedArrayType(T, Q); 4503 Q.removeUnaligned(); 4504 return Ctx.getQualifiedType(T, Q); 4505} 4506 4507/// CompareReferenceRelationship - Compare the two types T1 and T2 to 4508/// determine whether they are reference-compatible, 4509/// reference-related, or incompatible, for use in C++ initialization by 4510/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4511/// type, and the first type (T1) is the pointee type of the reference 4512/// type being initialized. 4513Sema::ReferenceCompareResult 4514Sema::CompareReferenceRelationship(SourceLocation Loc, 4515 QualType OrigT1, QualType OrigT2, 4516 ReferenceConversions *ConvOut) { 4517 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4518, __PRETTY_FUNCTION__))
4518 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4518, __PRETTY_FUNCTION__))
; 4519 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4519, __PRETTY_FUNCTION__))
; 4520 4521 QualType T1 = Context.getCanonicalType(OrigT1); 4522 QualType T2 = Context.getCanonicalType(OrigT2); 4523 Qualifiers T1Quals, T2Quals; 4524 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4525 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4526 4527 ReferenceConversions ConvTmp; 4528 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4529 Conv = ReferenceConversions(); 4530 4531 // C++2a [dcl.init.ref]p4: 4532 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4533 // reference-related to "cv2 T2" if T1 is similar to T2, or 4534 // T1 is a base class of T2. 4535 // "cv1 T1" is reference-compatible with "cv2 T2" if 4536 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4537 // "pointer to cv1 T1" via a standard conversion sequence. 4538 4539 // Check for standard conversions we can apply to pointers: derived-to-base 4540 // conversions, ObjC pointer conversions, and function pointer conversions. 4541 // (Qualification conversions are checked last.) 4542 QualType ConvertedT2; 4543 if (UnqualT1 == UnqualT2) { 4544 // Nothing to do. 4545 } else if (isCompleteType(Loc, OrigT2) && 4546 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4547 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4548 Conv |= ReferenceConversions::DerivedToBase; 4549 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4550 UnqualT2->isObjCObjectOrInterfaceType() && 4551 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4552 Conv |= ReferenceConversions::ObjC; 4553 else if (UnqualT2->isFunctionType() && 4554 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4555 Conv |= ReferenceConversions::Function; 4556 // No need to check qualifiers; function types don't have them. 4557 return Ref_Compatible; 4558 } 4559 bool ConvertedReferent = Conv != 0; 4560 4561 // We can have a qualification conversion. Compute whether the types are 4562 // similar at the same time. 4563 bool PreviousToQualsIncludeConst = true; 4564 bool TopLevel = true; 4565 do { 4566 if (T1 == T2) 4567 break; 4568 4569 // We will need a qualification conversion. 4570 Conv |= ReferenceConversions::Qualification; 4571 4572 // Track whether we performed a qualification conversion anywhere other 4573 // than the top level. This matters for ranking reference bindings in 4574 // overload resolution. 4575 if (!TopLevel) 4576 Conv |= ReferenceConversions::NestedQualification; 4577 4578 // MS compiler ignores __unaligned qualifier for references; do the same. 4579 T1 = withoutUnaligned(Context, T1); 4580 T2 = withoutUnaligned(Context, T2); 4581 4582 // If we find a qualifier mismatch, the types are not reference-compatible, 4583 // but are still be reference-related if they're similar. 4584 bool ObjCLifetimeConversion = false; 4585 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4586 PreviousToQualsIncludeConst, 4587 ObjCLifetimeConversion)) 4588 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4589 ? Ref_Related 4590 : Ref_Incompatible; 4591 4592 // FIXME: Should we track this for any level other than the first? 4593 if (ObjCLifetimeConversion) 4594 Conv |= ReferenceConversions::ObjCLifetime; 4595 4596 TopLevel = false; 4597 } while (Context.UnwrapSimilarTypes(T1, T2)); 4598 4599 // At this point, if the types are reference-related, we must either have the 4600 // same inner type (ignoring qualifiers), or must have already worked out how 4601 // to convert the referent. 4602 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4603 ? Ref_Compatible 4604 : Ref_Incompatible; 4605} 4606 4607/// Look for a user-defined conversion to a value reference-compatible 4608/// with DeclType. Return true if something definite is found. 4609static bool 4610FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4611 QualType DeclType, SourceLocation DeclLoc, 4612 Expr *Init, QualType T2, bool AllowRvalues, 4613 bool AllowExplicit) { 4614 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4614, __PRETTY_FUNCTION__))
; 4615 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4616 4617 OverloadCandidateSet CandidateSet( 4618 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4619 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4620 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4621 NamedDecl *D = *I; 4622 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4623 if (isa<UsingShadowDecl>(D)) 4624 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4625 4626 FunctionTemplateDecl *ConvTemplate 4627 = dyn_cast<FunctionTemplateDecl>(D); 4628 CXXConversionDecl *Conv; 4629 if (ConvTemplate) 4630 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4631 else 4632 Conv = cast<CXXConversionDecl>(D); 4633 4634 if (AllowRvalues) { 4635 // If we are initializing an rvalue reference, don't permit conversion 4636 // functions that return lvalues. 4637 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4638 const ReferenceType *RefType 4639 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4640 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4641 continue; 4642 } 4643 4644 if (!ConvTemplate && 4645 S.CompareReferenceRelationship( 4646 DeclLoc, 4647 Conv->getConversionType() 4648 .getNonReferenceType() 4649 .getUnqualifiedType(), 4650 DeclType.getNonReferenceType().getUnqualifiedType()) == 4651 Sema::Ref_Incompatible) 4652 continue; 4653 } else { 4654 // If the conversion function doesn't return a reference type, 4655 // it can't be considered for this conversion. An rvalue reference 4656 // is only acceptable if its referencee is a function type. 4657 4658 const ReferenceType *RefType = 4659 Conv->getConversionType()->getAs<ReferenceType>(); 4660 if (!RefType || 4661 (!RefType->isLValueReferenceType() && 4662 !RefType->getPointeeType()->isFunctionType())) 4663 continue; 4664 } 4665 4666 if (ConvTemplate) 4667 S.AddTemplateConversionCandidate( 4668 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4669 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4670 else 4671 S.AddConversionCandidate( 4672 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4673 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4674 } 4675 4676 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4677 4678 OverloadCandidateSet::iterator Best; 4679 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4680 case OR_Success: 4681 // C++ [over.ics.ref]p1: 4682 // 4683 // [...] If the parameter binds directly to the result of 4684 // applying a conversion function to the argument 4685 // expression, the implicit conversion sequence is a 4686 // user-defined conversion sequence (13.3.3.1.2), with the 4687 // second standard conversion sequence either an identity 4688 // conversion or, if the conversion function returns an 4689 // entity of a type that is a derived class of the parameter 4690 // type, a derived-to-base Conversion. 4691 if (!Best->FinalConversion.DirectBinding) 4692 return false; 4693 4694 ICS.setUserDefined(); 4695 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4696 ICS.UserDefined.After = Best->FinalConversion; 4697 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4698 ICS.UserDefined.ConversionFunction = Best->Function; 4699 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4700 ICS.UserDefined.EllipsisConversion = false; 4701 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4703, __PRETTY_FUNCTION__))
4702 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4703, __PRETTY_FUNCTION__))
4703 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4703, __PRETTY_FUNCTION__))
; 4704 return true; 4705 4706 case OR_Ambiguous: 4707 ICS.setAmbiguous(); 4708 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4709 Cand != CandidateSet.end(); ++Cand) 4710 if (Cand->Best) 4711 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4712 return true; 4713 4714 case OR_No_Viable_Function: 4715 case OR_Deleted: 4716 // There was no suitable conversion, or we found a deleted 4717 // conversion; continue with other checks. 4718 return false; 4719 } 4720 4721 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4721)
; 4722} 4723 4724/// Compute an implicit conversion sequence for reference 4725/// initialization. 4726static ImplicitConversionSequence 4727TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4728 SourceLocation DeclLoc, 4729 bool SuppressUserConversions, 4730 bool AllowExplicit) { 4731 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 4731, __PRETTY_FUNCTION__))
; 4732 4733 // Most paths end in a failed conversion. 4734 ImplicitConversionSequence ICS; 4735 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4736 4737 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4738 QualType T2 = Init->getType(); 4739 4740 // If the initializer is the address of an overloaded function, try 4741 // to resolve the overloaded function. If all goes well, T2 is the 4742 // type of the resulting function. 4743 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4744 DeclAccessPair Found; 4745 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4746 false, Found)) 4747 T2 = Fn->getType(); 4748 } 4749 4750 // Compute some basic properties of the types and the initializer. 4751 bool isRValRef = DeclType->isRValueReferenceType(); 4752 Expr::Classification InitCategory = Init->Classify(S.Context); 4753 4754 Sema::ReferenceConversions RefConv; 4755 Sema::ReferenceCompareResult RefRelationship = 4756 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4757 4758 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4759 ICS.setStandard(); 4760 ICS.Standard.First = ICK_Identity; 4761 // FIXME: A reference binding can be a function conversion too. We should 4762 // consider that when ordering reference-to-function bindings. 4763 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4764 ? ICK_Derived_To_Base 4765 : (RefConv & Sema::ReferenceConversions::ObjC) 4766 ? ICK_Compatible_Conversion 4767 : ICK_Identity; 4768 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4769 // a reference binding that performs a non-top-level qualification 4770 // conversion as a qualification conversion, not as an identity conversion. 4771 ICS.Standard.Third = (RefConv & 4772 Sema::ReferenceConversions::NestedQualification) 4773 ? ICK_Qualification 4774 : ICK_Identity; 4775 ICS.Standard.setFromType(T2); 4776 ICS.Standard.setToType(0, T2); 4777 ICS.Standard.setToType(1, T1); 4778 ICS.Standard.setToType(2, T1); 4779 ICS.Standard.ReferenceBinding = true; 4780 ICS.Standard.DirectBinding = BindsDirectly; 4781 ICS.Standard.IsLvalueReference = !isRValRef; 4782 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4783 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4784 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4785 ICS.Standard.ObjCLifetimeConversionBinding = 4786 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4787 ICS.Standard.CopyConstructor = nullptr; 4788 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4789 }; 4790 4791 // C++0x [dcl.init.ref]p5: 4792 // A reference to type "cv1 T1" is initialized by an expression 4793 // of type "cv2 T2" as follows: 4794 4795 // -- If reference is an lvalue reference and the initializer expression 4796 if (!isRValRef) { 4797 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4798 // reference-compatible with "cv2 T2," or 4799 // 4800 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4801 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4802 // C++ [over.ics.ref]p1: 4803 // When a parameter of reference type binds directly (8.5.3) 4804 // to an argument expression, the implicit conversion sequence 4805 // is the identity conversion, unless the argument expression 4806 // has a type that is a derived class of the parameter type, 4807 // in which case the implicit conversion sequence is a 4808 // derived-to-base Conversion (13.3.3.1). 4809 SetAsReferenceBinding(/*BindsDirectly=*/true); 4810 4811 // Nothing more to do: the inaccessibility/ambiguity check for 4812 // derived-to-base conversions is suppressed when we're 4813 // computing the implicit conversion sequence (C++ 4814 // [over.best.ics]p2). 4815 return ICS; 4816 } 4817 4818 // -- has a class type (i.e., T2 is a class type), where T1 is 4819 // not reference-related to T2, and can be implicitly 4820 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4821 // is reference-compatible with "cv3 T3" 92) (this 4822 // conversion is selected by enumerating the applicable 4823 // conversion functions (13.3.1.6) and choosing the best 4824 // one through overload resolution (13.3)), 4825 if (!SuppressUserConversions && T2->isRecordType() && 4826 S.isCompleteType(DeclLoc, T2) && 4827 RefRelationship == Sema::Ref_Incompatible) { 4828 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4829 Init, T2, /*AllowRvalues=*/false, 4830 AllowExplicit)) 4831 return ICS; 4832 } 4833 } 4834 4835 // -- Otherwise, the reference shall be an lvalue reference to a 4836 // non-volatile const type (i.e., cv1 shall be const), or the reference 4837 // shall be an rvalue reference. 4838 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4839 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4840 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4841 return ICS; 4842 } 4843 4844 // -- If the initializer expression 4845 // 4846 // -- is an xvalue, class prvalue, array prvalue or function 4847 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4848 if (RefRelationship == Sema::Ref_Compatible && 4849 (InitCategory.isXValue() || 4850 (InitCategory.isPRValue() && 4851 (T2->isRecordType() || T2->isArrayType())) || 4852 (InitCategory.isLValue() && T2->isFunctionType()))) { 4853 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4854 // binding unless we're binding to a class prvalue. 4855 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4856 // allow the use of rvalue references in C++98/03 for the benefit of 4857 // standard library implementors; therefore, we need the xvalue check here. 4858 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4859 !(InitCategory.isPRValue() || T2->isRecordType())); 4860 return ICS; 4861 } 4862 4863 // -- has a class type (i.e., T2 is a class type), where T1 is not 4864 // reference-related to T2, and can be implicitly converted to 4865 // an xvalue, class prvalue, or function lvalue of type 4866 // "cv3 T3", where "cv1 T1" is reference-compatible with 4867 // "cv3 T3", 4868 // 4869 // then the reference is bound to the value of the initializer 4870 // expression in the first case and to the result of the conversion 4871 // in the second case (or, in either case, to an appropriate base 4872 // class subobject). 4873 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4874 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4875 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4876 Init, T2, /*AllowRvalues=*/true, 4877 AllowExplicit)) { 4878 // In the second case, if the reference is an rvalue reference 4879 // and the second standard conversion sequence of the 4880 // user-defined conversion sequence includes an lvalue-to-rvalue 4881 // conversion, the program is ill-formed. 4882 if (ICS.isUserDefined() && isRValRef && 4883 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4884 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4885 4886 return ICS; 4887 } 4888 4889 // A temporary of function type cannot be created; don't even try. 4890 if (T1->isFunctionType()) 4891 return ICS; 4892 4893 // -- Otherwise, a temporary of type "cv1 T1" is created and 4894 // initialized from the initializer expression using the 4895 // rules for a non-reference copy initialization (8.5). The 4896 // reference is then bound to the temporary. If T1 is 4897 // reference-related to T2, cv1 must be the same 4898 // cv-qualification as, or greater cv-qualification than, 4899 // cv2; otherwise, the program is ill-formed. 4900 if (RefRelationship == Sema::Ref_Related) { 4901 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4902 // we would be reference-compatible or reference-compatible with 4903 // added qualification. But that wasn't the case, so the reference 4904 // initialization fails. 4905 // 4906 // Note that we only want to check address spaces and cvr-qualifiers here. 4907 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4908 Qualifiers T1Quals = T1.getQualifiers(); 4909 Qualifiers T2Quals = T2.getQualifiers(); 4910 T1Quals.removeObjCGCAttr(); 4911 T1Quals.removeObjCLifetime(); 4912 T2Quals.removeObjCGCAttr(); 4913 T2Quals.removeObjCLifetime(); 4914 // MS compiler ignores __unaligned qualifier for references; do the same. 4915 T1Quals.removeUnaligned(); 4916 T2Quals.removeUnaligned(); 4917 if (!T1Quals.compatiblyIncludes(T2Quals)) 4918 return ICS; 4919 } 4920 4921 // If at least one of the types is a class type, the types are not 4922 // related, and we aren't allowed any user conversions, the 4923 // reference binding fails. This case is important for breaking 4924 // recursion, since TryImplicitConversion below will attempt to 4925 // create a temporary through the use of a copy constructor. 4926 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4927 (T1->isRecordType() || T2->isRecordType())) 4928 return ICS; 4929 4930 // If T1 is reference-related to T2 and the reference is an rvalue 4931 // reference, the initializer expression shall not be an lvalue. 4932 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4933 Init->Classify(S.Context).isLValue()) { 4934 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4935 return ICS; 4936 } 4937 4938 // C++ [over.ics.ref]p2: 4939 // When a parameter of reference type is not bound directly to 4940 // an argument expression, the conversion sequence is the one 4941 // required to convert the argument expression to the 4942 // underlying type of the reference according to 4943 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4944 // to copy-initializing a temporary of the underlying type with 4945 // the argument expression. Any difference in top-level 4946 // cv-qualification is subsumed by the initialization itself 4947 // and does not constitute a conversion. 4948 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4949 AllowedExplicit::None, 4950 /*InOverloadResolution=*/false, 4951 /*CStyle=*/false, 4952 /*AllowObjCWritebackConversion=*/false, 4953 /*AllowObjCConversionOnExplicit=*/false); 4954 4955 // Of course, that's still a reference binding. 4956 if (ICS.isStandard()) { 4957 ICS.Standard.ReferenceBinding = true; 4958 ICS.Standard.IsLvalueReference = !isRValRef; 4959 ICS.Standard.BindsToFunctionLvalue = false; 4960 ICS.Standard.BindsToRvalue = true; 4961 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4962 ICS.Standard.ObjCLifetimeConversionBinding = false; 4963 } else if (ICS.isUserDefined()) { 4964 const ReferenceType *LValRefType = 4965 ICS.UserDefined.ConversionFunction->getReturnType() 4966 ->getAs<LValueReferenceType>(); 4967 4968 // C++ [over.ics.ref]p3: 4969 // Except for an implicit object parameter, for which see 13.3.1, a 4970 // standard conversion sequence cannot be formed if it requires [...] 4971 // binding an rvalue reference to an lvalue other than a function 4972 // lvalue. 4973 // Note that the function case is not possible here. 4974 if (isRValRef && LValRefType) { 4975 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4976 return ICS; 4977 } 4978 4979 ICS.UserDefined.After.ReferenceBinding = true; 4980 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4981 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4982 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4983 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4984 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4985 } 4986 4987 return ICS; 4988} 4989 4990static ImplicitConversionSequence 4991TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4992 bool SuppressUserConversions, 4993 bool InOverloadResolution, 4994 bool AllowObjCWritebackConversion, 4995 bool AllowExplicit = false); 4996 4997/// TryListConversion - Try to copy-initialize a value of type ToType from the 4998/// initializer list From. 4999static ImplicitConversionSequence 5000TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5001 bool SuppressUserConversions, 5002 bool InOverloadResolution, 5003 bool AllowObjCWritebackConversion) { 5004 // C++11 [over.ics.list]p1: 5005 // When an argument is an initializer list, it is not an expression and 5006 // special rules apply for converting it to a parameter type. 5007 5008 ImplicitConversionSequence Result; 5009 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5010 5011 // We need a complete type for what follows. Incomplete types can never be 5012 // initialized from init lists. 5013 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 5014 return Result; 5015 5016 // Per DR1467: 5017 // If the parameter type is a class X and the initializer list has a single 5018 // element of type cv U, where U is X or a class derived from X, the 5019 // implicit conversion sequence is the one required to convert the element 5020 // to the parameter type. 5021 // 5022 // Otherwise, if the parameter type is a character array [... ] 5023 // and the initializer list has a single element that is an 5024 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5025 // implicit conversion sequence is the identity conversion. 5026 if (From->getNumInits() == 1) { 5027 if (ToType->isRecordType()) { 5028 QualType InitType = From->getInit(0)->getType(); 5029 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5030 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5031 return TryCopyInitialization(S, From->getInit(0), ToType, 5032 SuppressUserConversions, 5033 InOverloadResolution, 5034 AllowObjCWritebackConversion); 5035 } 5036 5037 if (const auto *AT = S.Context.getAsArrayType(ToType)) { 5038 if (S.IsStringInit(From->getInit(0), AT)) { 5039 InitializedEntity Entity = 5040 InitializedEntity::InitializeParameter(S.Context, ToType, 5041 /*Consumed=*/false); 5042 if (S.CanPerformCopyInitialization(Entity, From)) { 5043 Result.setStandard(); 5044 Result.Standard.setAsIdentityConversion(); 5045 Result.Standard.setFromType(ToType); 5046 Result.Standard.setAllToTypes(ToType); 5047 return Result; 5048 } 5049 } 5050 } 5051 } 5052 5053 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5054 // C++11 [over.ics.list]p2: 5055 // If the parameter type is std::initializer_list<X> or "array of X" and 5056 // all the elements can be implicitly converted to X, the implicit 5057 // conversion sequence is the worst conversion necessary to convert an 5058 // element of the list to X. 5059 // 5060 // C++14 [over.ics.list]p3: 5061 // Otherwise, if the parameter type is "array of N X", if the initializer 5062 // list has exactly N elements or if it has fewer than N elements and X is 5063 // default-constructible, and if all the elements of the initializer list 5064 // can be implicitly converted to X, the implicit conversion sequence is 5065 // the worst conversion necessary to convert an element of the list to X. 5066 // 5067 // FIXME: We're missing a lot of these checks. 5068 bool toStdInitializerList = false; 5069 QualType X; 5070 if (ToType->isArrayType()) 5071 X = S.Context.getAsArrayType(ToType)->getElementType(); 5072 else 5073 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5074 if (!X.isNull()) { 5075 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5076 Expr *Init = From->getInit(i); 5077 ImplicitConversionSequence ICS = 5078 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5079 InOverloadResolution, 5080 AllowObjCWritebackConversion); 5081 // If a single element isn't convertible, fail. 5082 if (ICS.isBad()) { 5083 Result = ICS; 5084 break; 5085 } 5086 // Otherwise, look for the worst conversion. 5087 if (Result.isBad() || CompareImplicitConversionSequences( 5088 S, From->getBeginLoc(), ICS, Result) == 5089 ImplicitConversionSequence::Worse) 5090 Result = ICS; 5091 } 5092 5093 // For an empty list, we won't have computed any conversion sequence. 5094 // Introduce the identity conversion sequence. 5095 if (From->getNumInits() == 0) { 5096 Result.setStandard(); 5097 Result.Standard.setAsIdentityConversion(); 5098 Result.Standard.setFromType(ToType); 5099 Result.Standard.setAllToTypes(ToType); 5100 } 5101 5102 Result.setStdInitializerListElement(toStdInitializerList); 5103 return Result; 5104 } 5105 5106 // C++14 [over.ics.list]p4: 5107 // C++11 [over.ics.list]p3: 5108 // Otherwise, if the parameter is a non-aggregate class X and overload 5109 // resolution chooses a single best constructor [...] the implicit 5110 // conversion sequence is a user-defined conversion sequence. If multiple 5111 // constructors are viable but none is better than the others, the 5112 // implicit conversion sequence is a user-defined conversion sequence. 5113 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5114 // This function can deal with initializer lists. 5115 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5116 AllowedExplicit::None, 5117 InOverloadResolution, /*CStyle=*/false, 5118 AllowObjCWritebackConversion, 5119 /*AllowObjCConversionOnExplicit=*/false); 5120 } 5121 5122 // C++14 [over.ics.list]p5: 5123 // C++11 [over.ics.list]p4: 5124 // Otherwise, if the parameter has an aggregate type which can be 5125 // initialized from the initializer list [...] the implicit conversion 5126 // sequence is a user-defined conversion sequence. 5127 if (ToType->isAggregateType()) { 5128 // Type is an aggregate, argument is an init list. At this point it comes 5129 // down to checking whether the initialization works. 5130 // FIXME: Find out whether this parameter is consumed or not. 5131 InitializedEntity Entity = 5132 InitializedEntity::InitializeParameter(S.Context, ToType, 5133 /*Consumed=*/false); 5134 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5135 From)) { 5136 Result.setUserDefined(); 5137 Result.UserDefined.Before.setAsIdentityConversion(); 5138 // Initializer lists don't have a type. 5139 Result.UserDefined.Before.setFromType(QualType()); 5140 Result.UserDefined.Before.setAllToTypes(QualType()); 5141 5142 Result.UserDefined.After.setAsIdentityConversion(); 5143 Result.UserDefined.After.setFromType(ToType); 5144 Result.UserDefined.After.setAllToTypes(ToType); 5145 Result.UserDefined.ConversionFunction = nullptr; 5146 } 5147 return Result; 5148 } 5149 5150 // C++14 [over.ics.list]p6: 5151 // C++11 [over.ics.list]p5: 5152 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5153 if (ToType->isReferenceType()) { 5154 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5155 // mention initializer lists in any way. So we go by what list- 5156 // initialization would do and try to extrapolate from that. 5157 5158 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5159 5160 // If the initializer list has a single element that is reference-related 5161 // to the parameter type, we initialize the reference from that. 5162 if (From->getNumInits() == 1) { 5163 Expr *Init = From->getInit(0); 5164 5165 QualType T2 = Init->getType(); 5166 5167 // If the initializer is the address of an overloaded function, try 5168 // to resolve the overloaded function. If all goes well, T2 is the 5169 // type of the resulting function. 5170 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5171 DeclAccessPair Found; 5172 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5173 Init, ToType, false, Found)) 5174 T2 = Fn->getType(); 5175 } 5176 5177 // Compute some basic properties of the types and the initializer. 5178 Sema::ReferenceCompareResult RefRelationship = 5179 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5180 5181 if (RefRelationship >= Sema::Ref_Related) { 5182 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5183 SuppressUserConversions, 5184 /*AllowExplicit=*/false); 5185 } 5186 } 5187 5188 // Otherwise, we bind the reference to a temporary created from the 5189 // initializer list. 5190 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5191 InOverloadResolution, 5192 AllowObjCWritebackConversion); 5193 if (Result.isFailure()) 5194 return Result; 5195 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5196, __PRETTY_FUNCTION__))
5196 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5196, __PRETTY_FUNCTION__))
; 5197 5198 // Can we even bind to a temporary? 5199 if (ToType->isRValueReferenceType() || 5200 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5201 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5202 Result.UserDefined.After; 5203 SCS.ReferenceBinding = true; 5204 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5205 SCS.BindsToRvalue = true; 5206 SCS.BindsToFunctionLvalue = false; 5207 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5208 SCS.ObjCLifetimeConversionBinding = false; 5209 } else 5210 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5211 From, ToType); 5212 return Result; 5213 } 5214 5215 // C++14 [over.ics.list]p7: 5216 // C++11 [over.ics.list]p6: 5217 // Otherwise, if the parameter type is not a class: 5218 if (!ToType->isRecordType()) { 5219 // - if the initializer list has one element that is not itself an 5220 // initializer list, the implicit conversion sequence is the one 5221 // required to convert the element to the parameter type. 5222 unsigned NumInits = From->getNumInits(); 5223 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5224 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5225 SuppressUserConversions, 5226 InOverloadResolution, 5227 AllowObjCWritebackConversion); 5228 // - if the initializer list has no elements, the implicit conversion 5229 // sequence is the identity conversion. 5230 else if (NumInits == 0) { 5231 Result.setStandard(); 5232 Result.Standard.setAsIdentityConversion(); 5233 Result.Standard.setFromType(ToType); 5234 Result.Standard.setAllToTypes(ToType); 5235 } 5236 return Result; 5237 } 5238 5239 // C++14 [over.ics.list]p8: 5240 // C++11 [over.ics.list]p7: 5241 // In all cases other than those enumerated above, no conversion is possible 5242 return Result; 5243} 5244 5245/// TryCopyInitialization - Try to copy-initialize a value of type 5246/// ToType from the expression From. Return the implicit conversion 5247/// sequence required to pass this argument, which may be a bad 5248/// conversion sequence (meaning that the argument cannot be passed to 5249/// a parameter of this type). If @p SuppressUserConversions, then we 5250/// do not permit any user-defined conversion sequences. 5251static ImplicitConversionSequence 5252TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5253 bool SuppressUserConversions, 5254 bool InOverloadResolution, 5255 bool AllowObjCWritebackConversion, 5256 bool AllowExplicit) { 5257 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5258 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5259 InOverloadResolution,AllowObjCWritebackConversion); 5260 5261 if (ToType->isReferenceType()) 5262 return TryReferenceInit(S, From, ToType, 5263 /*FIXME:*/ From->getBeginLoc(), 5264 SuppressUserConversions, AllowExplicit); 5265 5266 return TryImplicitConversion(S, From, ToType, 5267 SuppressUserConversions, 5268 AllowedExplicit::None, 5269 InOverloadResolution, 5270 /*CStyle=*/false, 5271 AllowObjCWritebackConversion, 5272 /*AllowObjCConversionOnExplicit=*/false); 5273} 5274 5275static bool TryCopyInitialization(const CanQualType FromQTy, 5276 const CanQualType ToQTy, 5277 Sema &S, 5278 SourceLocation Loc, 5279 ExprValueKind FromVK) { 5280 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5281 ImplicitConversionSequence ICS = 5282 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5283 5284 return !ICS.isBad(); 5285} 5286 5287/// TryObjectArgumentInitialization - Try to initialize the object 5288/// parameter of the given member function (@c Method) from the 5289/// expression @p From. 5290static ImplicitConversionSequence 5291TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5292 Expr::Classification FromClassification, 5293 CXXMethodDecl *Method, 5294 CXXRecordDecl *ActingContext) { 5295 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5296 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5297 // const volatile object. 5298 Qualifiers Quals = Method->getMethodQualifiers(); 5299 if (isa<CXXDestructorDecl>(Method)) { 5300 Quals.addConst(); 5301 Quals.addVolatile(); 5302 } 5303 5304 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5305 5306 // Set up the conversion sequence as a "bad" conversion, to allow us 5307 // to exit early. 5308 ImplicitConversionSequence ICS; 5309 5310 // We need to have an object of class type. 5311 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5312 FromType = PT->getPointeeType(); 5313 5314 // When we had a pointer, it's implicitly dereferenced, so we 5315 // better have an lvalue. 5316 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5316, __PRETTY_FUNCTION__))
; 5317 } 5318 5319 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5319, __PRETTY_FUNCTION__))
; 5320 5321 // C++0x [over.match.funcs]p4: 5322 // For non-static member functions, the type of the implicit object 5323 // parameter is 5324 // 5325 // - "lvalue reference to cv X" for functions declared without a 5326 // ref-qualifier or with the & ref-qualifier 5327 // - "rvalue reference to cv X" for functions declared with the && 5328 // ref-qualifier 5329 // 5330 // where X is the class of which the function is a member and cv is the 5331 // cv-qualification on the member function declaration. 5332 // 5333 // However, when finding an implicit conversion sequence for the argument, we 5334 // are not allowed to perform user-defined conversions 5335 // (C++ [over.match.funcs]p5). We perform a simplified version of 5336 // reference binding here, that allows class rvalues to bind to 5337 // non-constant references. 5338 5339 // First check the qualifiers. 5340 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5341 if (ImplicitParamType.getCVRQualifiers() 5342 != FromTypeCanon.getLocalCVRQualifiers() && 5343 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5344 ICS.setBad(BadConversionSequence::bad_qualifiers, 5345 FromType, ImplicitParamType); 5346 return ICS; 5347 } 5348 5349 if (FromTypeCanon.hasAddressSpace()) { 5350 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5351 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5352 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5353 ICS.setBad(BadConversionSequence::bad_qualifiers, 5354 FromType, ImplicitParamType); 5355 return ICS; 5356 } 5357 } 5358 5359 // Check that we have either the same type or a derived type. It 5360 // affects the conversion rank. 5361 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5362 ImplicitConversionKind SecondKind; 5363 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5364 SecondKind = ICK_Identity; 5365 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5366 SecondKind = ICK_Derived_To_Base; 5367 else { 5368 ICS.setBad(BadConversionSequence::unrelated_class, 5369 FromType, ImplicitParamType); 5370 return ICS; 5371 } 5372 5373 // Check the ref-qualifier. 5374 switch (Method->getRefQualifier()) { 5375 case RQ_None: 5376 // Do nothing; we don't care about lvalueness or rvalueness. 5377 break; 5378 5379 case RQ_LValue: 5380 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5381 // non-const lvalue reference cannot bind to an rvalue 5382 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5383 ImplicitParamType); 5384 return ICS; 5385 } 5386 break; 5387 5388 case RQ_RValue: 5389 if (!FromClassification.isRValue()) { 5390 // rvalue reference cannot bind to an lvalue 5391 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5392 ImplicitParamType); 5393 return ICS; 5394 } 5395 break; 5396 } 5397 5398 // Success. Mark this as a reference binding. 5399 ICS.setStandard(); 5400 ICS.Standard.setAsIdentityConversion(); 5401 ICS.Standard.Second = SecondKind; 5402 ICS.Standard.setFromType(FromType); 5403 ICS.Standard.setAllToTypes(ImplicitParamType); 5404 ICS.Standard.ReferenceBinding = true; 5405 ICS.Standard.DirectBinding = true; 5406 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5407 ICS.Standard.BindsToFunctionLvalue = false; 5408 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5409 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5410 = (Method->getRefQualifier() == RQ_None); 5411 return ICS; 5412} 5413 5414/// PerformObjectArgumentInitialization - Perform initialization of 5415/// the implicit object parameter for the given Method with the given 5416/// expression. 5417ExprResult 5418Sema::PerformObjectArgumentInitialization(Expr *From, 5419 NestedNameSpecifier *Qualifier, 5420 NamedDecl *FoundDecl, 5421 CXXMethodDecl *Method) { 5422 QualType FromRecordType, DestType; 5423 QualType ImplicitParamRecordType = 5424 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5425 5426 Expr::Classification FromClassification; 5427 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5428 FromRecordType = PT->getPointeeType(); 5429 DestType = Method->getThisType(); 5430 FromClassification = Expr::Classification::makeSimpleLValue(); 5431 } else { 5432 FromRecordType = From->getType(); 5433 DestType = ImplicitParamRecordType; 5434 FromClassification = From->Classify(Context); 5435 5436 // When performing member access on an rvalue, materialize a temporary. 5437 if (From->isRValue()) { 5438 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5439 Method->getRefQualifier() != 5440 RefQualifierKind::RQ_RValue); 5441 } 5442 } 5443 5444 // Note that we always use the true parent context when performing 5445 // the actual argument initialization. 5446 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5447 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5448 Method->getParent()); 5449 if (ICS.isBad()) { 5450 switch (ICS.Bad.Kind) { 5451 case BadConversionSequence::bad_qualifiers: { 5452 Qualifiers FromQs = FromRecordType.getQualifiers(); 5453 Qualifiers ToQs = DestType.getQualifiers(); 5454 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5455 if (CVR) { 5456 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5457 << Method->getDeclName() << FromRecordType << (CVR - 1) 5458 << From->getSourceRange(); 5459 Diag(Method->getLocation(), diag::note_previous_decl) 5460 << Method->getDeclName(); 5461 return ExprError(); 5462 } 5463 break; 5464 } 5465 5466 case BadConversionSequence::lvalue_ref_to_rvalue: 5467 case BadConversionSequence::rvalue_ref_to_lvalue: { 5468 bool IsRValueQualified = 5469 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5470 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5471 << Method->getDeclName() << FromClassification.isRValue() 5472 << IsRValueQualified; 5473 Diag(Method->getLocation(), diag::note_previous_decl) 5474 << Method->getDeclName(); 5475 return ExprError(); 5476 } 5477 5478 case BadConversionSequence::no_conversion: 5479 case BadConversionSequence::unrelated_class: 5480 break; 5481 } 5482 5483 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5484 << ImplicitParamRecordType << FromRecordType 5485 << From->getSourceRange(); 5486 } 5487 5488 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5489 ExprResult FromRes = 5490 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5491 if (FromRes.isInvalid()) 5492 return ExprError(); 5493 From = FromRes.get(); 5494 } 5495 5496 if (!Context.hasSameType(From->getType(), DestType)) { 5497 CastKind CK; 5498 QualType PteeTy = DestType->getPointeeType(); 5499 LangAS DestAS = 5500 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5501 if (FromRecordType.getAddressSpace() != DestAS) 5502 CK = CK_AddressSpaceConversion; 5503 else 5504 CK = CK_NoOp; 5505 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5506 } 5507 return From; 5508} 5509 5510/// TryContextuallyConvertToBool - Attempt to contextually convert the 5511/// expression From to bool (C++0x [conv]p3). 5512static ImplicitConversionSequence 5513TryContextuallyConvertToBool(Sema &S, Expr *From) { 5514 // C++ [dcl.init]/17.8: 5515 // - Otherwise, if the initialization is direct-initialization, the source 5516 // type is std::nullptr_t, and the destination type is bool, the initial 5517 // value of the object being initialized is false. 5518 if (From->getType()->isNullPtrType()) 5519 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5520 S.Context.BoolTy, 5521 From->isGLValue()); 5522 5523 // All other direct-initialization of bool is equivalent to an implicit 5524 // conversion to bool in which explicit conversions are permitted. 5525 return TryImplicitConversion(S, From, S.Context.BoolTy, 5526 /*SuppressUserConversions=*/false, 5527 AllowedExplicit::Conversions, 5528 /*InOverloadResolution=*/false, 5529 /*CStyle=*/false, 5530 /*AllowObjCWritebackConversion=*/false, 5531 /*AllowObjCConversionOnExplicit=*/false); 5532} 5533 5534/// PerformContextuallyConvertToBool - Perform a contextual conversion 5535/// of the expression From to bool (C++0x [conv]p3). 5536ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5537 if (checkPlaceholderForOverload(*this, From)) 5538 return ExprError(); 5539 5540 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5541 if (!ICS.isBad()) 5542 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5543 5544 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5545 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5546 << From->getType() << From->getSourceRange(); 5547 return ExprError(); 5548} 5549 5550/// Check that the specified conversion is permitted in a converted constant 5551/// expression, according to C++11 [expr.const]p3. Return true if the conversion 5552/// is acceptable. 5553static bool CheckConvertedConstantConversions(Sema &S, 5554 StandardConversionSequence &SCS) { 5555 // Since we know that the target type is an integral or unscoped enumeration 5556 // type, most conversion kinds are impossible. All possible First and Third 5557 // conversions are fine. 5558 switch (SCS.Second) { 5559 case ICK_Identity: 5560 case ICK_Integral_Promotion: 5561 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5562 case ICK_Zero_Queue_Conversion: 5563 return true; 5564 5565 case ICK_Boolean_Conversion: 5566 // Conversion from an integral or unscoped enumeration type to bool is 5567 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5568 // conversion, so we allow it in a converted constant expression. 5569 // 5570 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5571 // a lot of popular code. We should at least add a warning for this 5572 // (non-conforming) extension. 5573 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5574 SCS.getToType(2)->isBooleanType(); 5575 5576 case ICK_Pointer_Conversion: 5577 case ICK_Pointer_Member: 5578 // C++1z: null pointer conversions and null member pointer conversions are 5579 // only permitted if the source type is std::nullptr_t. 5580 return SCS.getFromType()->isNullPtrType(); 5581 5582 case ICK_Floating_Promotion: 5583 case ICK_Complex_Promotion: 5584 case ICK_Floating_Conversion: 5585 case ICK_Complex_Conversion: 5586 case ICK_Floating_Integral: 5587 case ICK_Compatible_Conversion: 5588 case ICK_Derived_To_Base: 5589 case ICK_Vector_Conversion: 5590 case ICK_SVE_Vector_Conversion: 5591 case ICK_Vector_Splat: 5592 case ICK_Complex_Real: 5593 case ICK_Block_Pointer_Conversion: 5594 case ICK_TransparentUnionConversion: 5595 case ICK_Writeback_Conversion: 5596 case ICK_Zero_Event_Conversion: 5597 case ICK_C_Only_Conversion: 5598 case ICK_Incompatible_Pointer_Conversion: 5599 return false; 5600 5601 case ICK_Lvalue_To_Rvalue: 5602 case ICK_Array_To_Pointer: 5603 case ICK_Function_To_Pointer: 5604 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5604)
; 5605 5606 case ICK_Function_Conversion: 5607 case ICK_Qualification: 5608 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5608)
; 5609 5610 case ICK_Num_Conversion_Kinds: 5611 break; 5612 } 5613 5614 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5614)
; 5615} 5616 5617/// CheckConvertedConstantExpression - Check that the expression From is a 5618/// converted constant expression of type T, perform the conversion and produce 5619/// the converted expression, per C++11 [expr.const]p3. 5620static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5621 QualType T, APValue &Value, 5622 Sema::CCEKind CCE, 5623 bool RequireInt, 5624 NamedDecl *Dest) { 5625 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5626, __PRETTY_FUNCTION__))
5626 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5626, __PRETTY_FUNCTION__))
; 5627 5628 if (checkPlaceholderForOverload(S, From)) 5629 return ExprError(); 5630 5631 // C++1z [expr.const]p3: 5632 // A converted constant expression of type T is an expression, 5633 // implicitly converted to type T, where the converted 5634 // expression is a constant expression and the implicit conversion 5635 // sequence contains only [... list of conversions ...]. 5636 // C++1z [stmt.if]p2: 5637 // If the if statement is of the form if constexpr, the value of the 5638 // condition shall be a contextually converted constant expression of type 5639 // bool. 5640 ImplicitConversionSequence ICS = 5641 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5642 ? TryContextuallyConvertToBool(S, From) 5643 : TryCopyInitialization(S, From, T, 5644 /*SuppressUserConversions=*/false, 5645 /*InOverloadResolution=*/false, 5646 /*AllowObjCWritebackConversion=*/false, 5647 /*AllowExplicit=*/false); 5648 StandardConversionSequence *SCS = nullptr; 5649 switch (ICS.getKind()) { 5650 case ImplicitConversionSequence::StandardConversion: 5651 SCS = &ICS.Standard; 5652 break; 5653 case ImplicitConversionSequence::UserDefinedConversion: 5654 if (T->isRecordType()) 5655 SCS = &ICS.UserDefined.Before; 5656 else 5657 SCS = &ICS.UserDefined.After; 5658 break; 5659 case ImplicitConversionSequence::AmbiguousConversion: 5660 case ImplicitConversionSequence::BadConversion: 5661 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5662 return S.Diag(From->getBeginLoc(), 5663 diag::err_typecheck_converted_constant_expression) 5664 << From->getType() << From->getSourceRange() << T; 5665 return ExprError(); 5666 5667 case ImplicitConversionSequence::EllipsisConversion: 5668 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5668)
; 5669 } 5670 5671 // Check that we would only use permitted conversions. 5672 if (!CheckConvertedConstantConversions(S, *SCS)) { 5673 return S.Diag(From->getBeginLoc(), 5674 diag::err_typecheck_converted_constant_expression_disallowed) 5675 << From->getType() << From->getSourceRange() << T; 5676 } 5677 // [...] and where the reference binding (if any) binds directly. 5678 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5679 return S.Diag(From->getBeginLoc(), 5680 diag::err_typecheck_converted_constant_expression_indirect) 5681 << From->getType() << From->getSourceRange() << T; 5682 } 5683 5684 // Usually we can simply apply the ImplicitConversionSequence we formed 5685 // earlier, but that's not guaranteed to work when initializing an object of 5686 // class type. 5687 ExprResult Result; 5688 if (T->isRecordType()) { 5689 assert(CCE == Sema::CCEK_TemplateArg &&((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5690, __PRETTY_FUNCTION__))
5690 "unexpected class type converted constant expr")((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5690, __PRETTY_FUNCTION__))
; 5691 Result = S.PerformCopyInitialization( 5692 InitializedEntity::InitializeTemplateParameter( 5693 T, cast<NonTypeTemplateParmDecl>(Dest)), 5694 SourceLocation(), From); 5695 } else { 5696 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5697 } 5698 if (Result.isInvalid()) 5699 return Result; 5700 5701 // C++2a [intro.execution]p5: 5702 // A full-expression is [...] a constant-expression [...] 5703 Result = 5704 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5705 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5706 if (Result.isInvalid()) 5707 return Result; 5708 5709 // Check for a narrowing implicit conversion. 5710 bool ReturnPreNarrowingValue = false; 5711 APValue PreNarrowingValue; 5712 QualType PreNarrowingType; 5713 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5714 PreNarrowingType)) { 5715 case NK_Dependent_Narrowing: 5716 // Implicit conversion to a narrower type, but the expression is 5717 // value-dependent so we can't tell whether it's actually narrowing. 5718 case NK_Variable_Narrowing: 5719 // Implicit conversion to a narrower type, and the value is not a constant 5720 // expression. We'll diagnose this in a moment. 5721 case NK_Not_Narrowing: 5722 break; 5723 5724 case NK_Constant_Narrowing: 5725 if (CCE == Sema::CCEK_ArrayBound && 5726 PreNarrowingType->isIntegralOrEnumerationType() && 5727 PreNarrowingValue.isInt()) { 5728 // Don't diagnose array bound narrowing here; we produce more precise 5729 // errors by allowing the un-narrowed value through. 5730 ReturnPreNarrowingValue = true; 5731 break; 5732 } 5733 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5734 << CCE << /*Constant*/ 1 5735 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5736 break; 5737 5738 case NK_Type_Narrowing: 5739 // FIXME: It would be better to diagnose that the expression is not a 5740 // constant expression. 5741 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5742 << CCE << /*Constant*/ 0 << From->getType() << T; 5743 break; 5744 } 5745 5746 if (Result.get()->isValueDependent()) { 5747 Value = APValue(); 5748 return Result; 5749 } 5750 5751 // Check the expression is a constant expression. 5752 SmallVector<PartialDiagnosticAt, 8> Notes; 5753 Expr::EvalResult Eval; 5754 Eval.Diag = &Notes; 5755 5756 ConstantExprKind Kind; 5757 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5758 Kind = ConstantExprKind::ClassTemplateArgument; 5759 else if (CCE == Sema::CCEK_TemplateArg) 5760 Kind = ConstantExprKind::NonClassTemplateArgument; 5761 else 5762 Kind = ConstantExprKind::Normal; 5763 5764 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5765 (RequireInt && !Eval.Val.isInt())) { 5766 // The expression can't be folded, so we can't keep it at this position in 5767 // the AST. 5768 Result = ExprError(); 5769 } else { 5770 Value = Eval.Val; 5771 5772 if (Notes.empty()) { 5773 // It's a constant expression. 5774 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5775 if (ReturnPreNarrowingValue) 5776 Value = std::move(PreNarrowingValue); 5777 return E; 5778 } 5779 } 5780 5781 // It's not a constant expression. Produce an appropriate diagnostic. 5782 if (Notes.size() == 1 && 5783 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5784 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5785 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5786 diag::note_constexpr_invalid_template_arg) { 5787 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5788 for (unsigned I = 0; I < Notes.size(); ++I) 5789 S.Diag(Notes[I].first, Notes[I].second); 5790 } else { 5791 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5792 << CCE << From->getSourceRange(); 5793 for (unsigned I = 0; I < Notes.size(); ++I) 5794 S.Diag(Notes[I].first, Notes[I].second); 5795 } 5796 return ExprError(); 5797} 5798 5799ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5800 APValue &Value, CCEKind CCE, 5801 NamedDecl *Dest) { 5802 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5803 Dest); 5804} 5805 5806ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5807 llvm::APSInt &Value, 5808 CCEKind CCE) { 5809 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 5809, __PRETTY_FUNCTION__))
; 5810 5811 APValue V; 5812 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5813 /*Dest=*/nullptr); 5814 if (!R.isInvalid() && !R.get()->isValueDependent()) 5815 Value = V.getInt(); 5816 return R; 5817} 5818 5819 5820/// dropPointerConversions - If the given standard conversion sequence 5821/// involves any pointer conversions, remove them. This may change 5822/// the result type of the conversion sequence. 5823static void dropPointerConversion(StandardConversionSequence &SCS) { 5824 if (SCS.Second == ICK_Pointer_Conversion) { 5825 SCS.Second = ICK_Identity; 5826 SCS.Third = ICK_Identity; 5827 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5828 } 5829} 5830 5831/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5832/// convert the expression From to an Objective-C pointer type. 5833static ImplicitConversionSequence 5834TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5835 // Do an implicit conversion to 'id'. 5836 QualType Ty = S.Context.getObjCIdType(); 5837 ImplicitConversionSequence ICS 5838 = TryImplicitConversion(S, From, Ty, 5839 // FIXME: Are these flags correct? 5840 /*SuppressUserConversions=*/false, 5841 AllowedExplicit::Conversions, 5842 /*InOverloadResolution=*/false, 5843 /*CStyle=*/false, 5844 /*AllowObjCWritebackConversion=*/false, 5845 /*AllowObjCConversionOnExplicit=*/true); 5846 5847 // Strip off any final conversions to 'id'. 5848 switch (ICS.getKind()) { 5849 case ImplicitConversionSequence::BadConversion: 5850 case ImplicitConversionSequence::AmbiguousConversion: 5851 case ImplicitConversionSequence::EllipsisConversion: 5852 break; 5853 5854 case ImplicitConversionSequence::UserDefinedConversion: 5855 dropPointerConversion(ICS.UserDefined.After); 5856 break; 5857 5858 case ImplicitConversionSequence::StandardConversion: 5859 dropPointerConversion(ICS.Standard); 5860 break; 5861 } 5862 5863 return ICS; 5864} 5865 5866/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5867/// conversion of the expression From to an Objective-C pointer type. 5868/// Returns a valid but null ExprResult if no conversion sequence exists. 5869ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5870 if (checkPlaceholderForOverload(*this, From)) 5871 return ExprError(); 5872 5873 QualType Ty = Context.getObjCIdType(); 5874 ImplicitConversionSequence ICS = 5875 TryContextuallyConvertToObjCPointer(*this, From); 5876 if (!ICS.isBad()) 5877 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5878 return ExprResult(); 5879} 5880 5881/// Determine whether the provided type is an integral type, or an enumeration 5882/// type of a permitted flavor. 5883bool Sema::ICEConvertDiagnoser::match(QualType T) { 5884 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5885 : T->isIntegralOrUnscopedEnumerationType(); 5886} 5887 5888static ExprResult 5889diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5890 Sema::ContextualImplicitConverter &Converter, 5891 QualType T, UnresolvedSetImpl &ViableConversions) { 5892 5893 if (Converter.Suppress) 5894 return ExprError(); 5895 5896 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5897 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5898 CXXConversionDecl *Conv = 5899 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5900 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5901 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5902 } 5903 return From; 5904} 5905 5906static bool 5907diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5908 Sema::ContextualImplicitConverter &Converter, 5909 QualType T, bool HadMultipleCandidates, 5910 UnresolvedSetImpl &ExplicitConversions) { 5911 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5912 DeclAccessPair Found = ExplicitConversions[0]; 5913 CXXConversionDecl *Conversion = 5914 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5915 5916 // The user probably meant to invoke the given explicit 5917 // conversion; use it. 5918 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5919 std::string TypeStr; 5920 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5921 5922 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5923 << FixItHint::CreateInsertion(From->getBeginLoc(), 5924 "static_cast<" + TypeStr + ">(") 5925 << FixItHint::CreateInsertion( 5926 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5927 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5928 5929 // If we aren't in a SFINAE context, build a call to the 5930 // explicit conversion function. 5931 if (SemaRef.isSFINAEContext()) 5932 return true; 5933 5934 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5935 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5936 HadMultipleCandidates); 5937 if (Result.isInvalid()) 5938 return true; 5939 // Record usage of conversion in an implicit cast. 5940 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5941 CK_UserDefinedConversion, Result.get(), 5942 nullptr, Result.get()->getValueKind(), 5943 SemaRef.CurFPFeatureOverrides()); 5944 } 5945 return false; 5946} 5947 5948static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5949 Sema::ContextualImplicitConverter &Converter, 5950 QualType T, bool HadMultipleCandidates, 5951 DeclAccessPair &Found) { 5952 CXXConversionDecl *Conversion = 5953 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5954 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5955 5956 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5957 if (!Converter.SuppressConversion) { 5958 if (SemaRef.isSFINAEContext()) 5959 return true; 5960 5961 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5962 << From->getSourceRange(); 5963 } 5964 5965 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5966 HadMultipleCandidates); 5967 if (Result.isInvalid()) 5968 return true; 5969 // Record usage of conversion in an implicit cast. 5970 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5971 CK_UserDefinedConversion, Result.get(), 5972 nullptr, Result.get()->getValueKind(), 5973 SemaRef.CurFPFeatureOverrides()); 5974 return false; 5975} 5976 5977static ExprResult finishContextualImplicitConversion( 5978 Sema &SemaRef, SourceLocation Loc, Expr *From, 5979 Sema::ContextualImplicitConverter &Converter) { 5980 if (!Converter.match(From->getType()) && !Converter.Suppress) 5981 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5982 << From->getSourceRange(); 5983 5984 return SemaRef.DefaultLvalueConversion(From); 5985} 5986 5987static void 5988collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5989 UnresolvedSetImpl &ViableConversions, 5990 OverloadCandidateSet &CandidateSet) { 5991 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5992 DeclAccessPair FoundDecl = ViableConversions[I]; 5993 NamedDecl *D = FoundDecl.getDecl(); 5994 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5995 if (isa<UsingShadowDecl>(D)) 5996 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5997 5998 CXXConversionDecl *Conv; 5999 FunctionTemplateDecl *ConvTemplate; 6000 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6001 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6002 else 6003 Conv = cast<CXXConversionDecl>(D); 6004 6005 if (ConvTemplate) 6006 SemaRef.AddTemplateConversionCandidate( 6007 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6008 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6009 else 6010 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6011 ToType, CandidateSet, 6012 /*AllowObjCConversionOnExplicit=*/false, 6013 /*AllowExplicit*/ true); 6014 } 6015} 6016 6017/// Attempt to convert the given expression to a type which is accepted 6018/// by the given converter. 6019/// 6020/// This routine will attempt to convert an expression of class type to a 6021/// type accepted by the specified converter. In C++11 and before, the class 6022/// must have a single non-explicit conversion function converting to a matching 6023/// type. In C++1y, there can be multiple such conversion functions, but only 6024/// one target type. 6025/// 6026/// \param Loc The source location of the construct that requires the 6027/// conversion. 6028/// 6029/// \param From The expression we're converting from. 6030/// 6031/// \param Converter Used to control and diagnose the conversion process. 6032/// 6033/// \returns The expression, converted to an integral or enumeration type if 6034/// successful. 6035ExprResult Sema::PerformContextualImplicitConversion( 6036 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6037 // We can't perform any more checking for type-dependent expressions. 6038 if (From->isTypeDependent()) 6039 return From; 6040 6041 // Process placeholders immediately. 6042 if (From->hasPlaceholderType()) { 6043 ExprResult result = CheckPlaceholderExpr(From); 6044 if (result.isInvalid()) 6045 return result; 6046 From = result.get(); 6047 } 6048 6049 // If the expression already has a matching type, we're golden. 6050 QualType T = From->getType(); 6051 if (Converter.match(T)) 6052 return DefaultLvalueConversion(From); 6053 6054 // FIXME: Check for missing '()' if T is a function type? 6055 6056 // We can only perform contextual implicit conversions on objects of class 6057 // type. 6058 const RecordType *RecordTy = T->getAs<RecordType>(); 6059 if (!RecordTy || !getLangOpts().CPlusPlus) { 6060 if (!Converter.Suppress) 6061 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6062 return From; 6063 } 6064 6065 // We must have a complete class type. 6066 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6067 ContextualImplicitConverter &Converter; 6068 Expr *From; 6069 6070 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6071 : Converter(Converter), From(From) {} 6072 6073 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6074 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6075 } 6076 } IncompleteDiagnoser(Converter, From); 6077 6078 if (Converter.Suppress ? !isCompleteType(Loc, T) 6079 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6080 return From; 6081 6082 // Look for a conversion to an integral or enumeration type. 6083 UnresolvedSet<4> 6084 ViableConversions; // These are *potentially* viable in C++1y. 6085 UnresolvedSet<4> ExplicitConversions; 6086 const auto &Conversions = 6087 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6088 6089 bool HadMultipleCandidates = 6090 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6091 6092 // To check that there is only one target type, in C++1y: 6093 QualType ToType; 6094 bool HasUniqueTargetType = true; 6095 6096 // Collect explicit or viable (potentially in C++1y) conversions. 6097 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6098 NamedDecl *D = (*I)->getUnderlyingDecl(); 6099 CXXConversionDecl *Conversion; 6100 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6101 if (ConvTemplate) { 6102 if (getLangOpts().CPlusPlus14) 6103 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6104 else 6105 continue; // C++11 does not consider conversion operator templates(?). 6106 } else 6107 Conversion = cast<CXXConversionDecl>(D); 6108 6109 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6111, __PRETTY_FUNCTION__))
6110 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6111, __PRETTY_FUNCTION__))
6111 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6111, __PRETTY_FUNCTION__))
; 6112 6113 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6114 if (Converter.match(CurToType) || ConvTemplate) { 6115 6116 if (Conversion->isExplicit()) { 6117 // FIXME: For C++1y, do we need this restriction? 6118 // cf. diagnoseNoViableConversion() 6119 if (!ConvTemplate) 6120 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6121 } else { 6122 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6123 if (ToType.isNull()) 6124 ToType = CurToType.getUnqualifiedType(); 6125 else if (HasUniqueTargetType && 6126 (CurToType.getUnqualifiedType() != ToType)) 6127 HasUniqueTargetType = false; 6128 } 6129 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6130 } 6131 } 6132 } 6133 6134 if (getLangOpts().CPlusPlus14) { 6135 // C++1y [conv]p6: 6136 // ... An expression e of class type E appearing in such a context 6137 // is said to be contextually implicitly converted to a specified 6138 // type T and is well-formed if and only if e can be implicitly 6139 // converted to a type T that is determined as follows: E is searched 6140 // for conversion functions whose return type is cv T or reference to 6141 // cv T such that T is allowed by the context. There shall be 6142 // exactly one such T. 6143 6144 // If no unique T is found: 6145 if (ToType.isNull()) { 6146 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6147 HadMultipleCandidates, 6148 ExplicitConversions)) 6149 return ExprError(); 6150 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6151 } 6152 6153 // If more than one unique Ts are found: 6154 if (!HasUniqueTargetType) 6155 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6156 ViableConversions); 6157 6158 // If one unique T is found: 6159 // First, build a candidate set from the previously recorded 6160 // potentially viable conversions. 6161 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6162 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6163 CandidateSet); 6164 6165 // Then, perform overload resolution over the candidate set. 6166 OverloadCandidateSet::iterator Best; 6167 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6168 case OR_Success: { 6169 // Apply this conversion. 6170 DeclAccessPair Found = 6171 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6172 if (recordConversion(*this, Loc, From, Converter, T, 6173 HadMultipleCandidates, Found)) 6174 return ExprError(); 6175 break; 6176 } 6177 case OR_Ambiguous: 6178 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6179 ViableConversions); 6180 case OR_No_Viable_Function: 6181 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6182 HadMultipleCandidates, 6183 ExplicitConversions)) 6184 return ExprError(); 6185 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 6186 case OR_Deleted: 6187 // We'll complain below about a non-integral condition type. 6188 break; 6189 } 6190 } else { 6191 switch (ViableConversions.size()) { 6192 case 0: { 6193 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6194 HadMultipleCandidates, 6195 ExplicitConversions)) 6196 return ExprError(); 6197 6198 // We'll complain below about a non-integral condition type. 6199 break; 6200 } 6201 case 1: { 6202 // Apply this conversion. 6203 DeclAccessPair Found = ViableConversions[0]; 6204 if (recordConversion(*this, Loc, From, Converter, T, 6205 HadMultipleCandidates, Found)) 6206 return ExprError(); 6207 break; 6208 } 6209 default: 6210 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6211 ViableConversions); 6212 } 6213 } 6214 6215 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6216} 6217 6218/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6219/// an acceptable non-member overloaded operator for a call whose 6220/// arguments have types T1 (and, if non-empty, T2). This routine 6221/// implements the check in C++ [over.match.oper]p3b2 concerning 6222/// enumeration types. 6223static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6224 FunctionDecl *Fn, 6225 ArrayRef<Expr *> Args) { 6226 QualType T1 = Args[0]->getType(); 6227 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6228 6229 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6230 return true; 6231 6232 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6233 return true; 6234 6235 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6236 if (Proto->getNumParams() < 1) 6237 return false; 6238 6239 if (T1->isEnumeralType()) { 6240 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6241 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6242 return true; 6243 } 6244 6245 if (Proto->getNumParams() < 2) 6246 return false; 6247 6248 if (!T2.isNull() && T2->isEnumeralType()) { 6249 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6250 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6251 return true; 6252 } 6253 6254 return false; 6255} 6256 6257/// AddOverloadCandidate - Adds the given function to the set of 6258/// candidate functions, using the given function call arguments. If 6259/// @p SuppressUserConversions, then don't allow user-defined 6260/// conversions via constructors or conversion operators. 6261/// 6262/// \param PartialOverloading true if we are performing "partial" overloading 6263/// based on an incomplete set of function arguments. This feature is used by 6264/// code completion. 6265void Sema::AddOverloadCandidate( 6266 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6267 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6268 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6269 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6270 OverloadCandidateParamOrder PO) { 6271 const FunctionProtoType *Proto 6272 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6273 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6273, __PRETTY_FUNCTION__))
; 6274 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6275, __PRETTY_FUNCTION__))
6275 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6275, __PRETTY_FUNCTION__))
; 6276 6277 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6278 if (!isa<CXXConstructorDecl>(Method)) { 6279 // If we get here, it's because we're calling a member function 6280 // that is named without a member access expression (e.g., 6281 // "this->f") that was either written explicitly or created 6282 // implicitly. This can happen with a qualified call to a member 6283 // function, e.g., X::f(). We use an empty type for the implied 6284 // object argument (C++ [over.call.func]p3), and the acting context 6285 // is irrelevant. 6286 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6287 Expr::Classification::makeSimpleLValue(), Args, 6288 CandidateSet, SuppressUserConversions, 6289 PartialOverloading, EarlyConversions, PO); 6290 return; 6291 } 6292 // We treat a constructor like a non-member function, since its object 6293 // argument doesn't participate in overload resolution. 6294 } 6295 6296 if (!CandidateSet.isNewCandidate(Function, PO)) 6297 return; 6298 6299 // C++11 [class.copy]p11: [DR1402] 6300 // A defaulted move constructor that is defined as deleted is ignored by 6301 // overload resolution. 6302 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6303 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6304 Constructor->isMoveConstructor()) 6305 return; 6306 6307 // Overload resolution is always an unevaluated context. 6308 EnterExpressionEvaluationContext Unevaluated( 6309 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6310 6311 // C++ [over.match.oper]p3: 6312 // if no operand has a class type, only those non-member functions in the 6313 // lookup set that have a first parameter of type T1 or "reference to 6314 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6315 // is a right operand) a second parameter of type T2 or "reference to 6316 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6317 // candidate functions. 6318 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6319 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6320 return; 6321 6322 // Add this candidate 6323 OverloadCandidate &Candidate = 6324 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6325 Candidate.FoundDecl = FoundDecl; 6326 Candidate.Function = Function; 6327 Candidate.Viable = true; 6328 Candidate.RewriteKind = 6329 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6330 Candidate.IsSurrogate = false; 6331 Candidate.IsADLCandidate = IsADLCandidate; 6332 Candidate.IgnoreObjectArgument = false; 6333 Candidate.ExplicitCallArguments = Args.size(); 6334 6335 // Explicit functions are not actually candidates at all if we're not 6336 // allowing them in this context, but keep them around so we can point 6337 // to them in diagnostics. 6338 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6339 Candidate.Viable = false; 6340 Candidate.FailureKind = ovl_fail_explicit; 6341 return; 6342 } 6343 6344 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6345 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6346 Candidate.Viable = false; 6347 Candidate.FailureKind = ovl_non_default_multiversion_function; 6348 return; 6349 } 6350 6351 if (Constructor) { 6352 // C++ [class.copy]p3: 6353 // A member function template is never instantiated to perform the copy 6354 // of a class object to an object of its class type. 6355 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6356 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6357 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6358 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6359 ClassType))) { 6360 Candidate.Viable = false; 6361 Candidate.FailureKind = ovl_fail_illegal_constructor; 6362 return; 6363 } 6364 6365 // C++ [over.match.funcs]p8: (proposed DR resolution) 6366 // A constructor inherited from class type C that has a first parameter 6367 // of type "reference to P" (including such a constructor instantiated 6368 // from a template) is excluded from the set of candidate functions when 6369 // constructing an object of type cv D if the argument list has exactly 6370 // one argument and D is reference-related to P and P is reference-related 6371 // to C. 6372 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6373 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6374 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6375 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6376 QualType C = Context.getRecordType(Constructor->getParent()); 6377 QualType D = Context.getRecordType(Shadow->getParent()); 6378 SourceLocation Loc = Args.front()->getExprLoc(); 6379 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6380 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6381 Candidate.Viable = false; 6382 Candidate.FailureKind = ovl_fail_inhctor_slice; 6383 return; 6384 } 6385 } 6386 6387 // Check that the constructor is capable of constructing an object in the 6388 // destination address space. 6389 if (!Qualifiers::isAddressSpaceSupersetOf( 6390 Constructor->getMethodQualifiers().getAddressSpace(), 6391 CandidateSet.getDestAS())) { 6392 Candidate.Viable = false; 6393 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6394 } 6395 } 6396 6397 unsigned NumParams = Proto->getNumParams(); 6398 6399 // (C++ 13.3.2p2): A candidate function having fewer than m 6400 // parameters is viable only if it has an ellipsis in its parameter 6401 // list (8.3.5). 6402 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6403 !Proto->isVariadic()) { 6404 Candidate.Viable = false; 6405 Candidate.FailureKind = ovl_fail_too_many_arguments; 6406 return; 6407 } 6408 6409 // (C++ 13.3.2p2): A candidate function having more than m parameters 6410 // is viable only if the (m+1)st parameter has a default argument 6411 // (8.3.6). For the purposes of overload resolution, the 6412 // parameter list is truncated on the right, so that there are 6413 // exactly m parameters. 6414 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6415 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6416 // Not enough arguments. 6417 Candidate.Viable = false; 6418 Candidate.FailureKind = ovl_fail_too_few_arguments; 6419 return; 6420 } 6421 6422 // (CUDA B.1): Check for invalid calls between targets. 6423 if (getLangOpts().CUDA) 6424 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6425 // Skip the check for callers that are implicit members, because in this 6426 // case we may not yet know what the member's target is; the target is 6427 // inferred for the member automatically, based on the bases and fields of 6428 // the class. 6429 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6430 Candidate.Viable = false; 6431 Candidate.FailureKind = ovl_fail_bad_target; 6432 return; 6433 } 6434 6435 if (Function->getTrailingRequiresClause()) { 6436 ConstraintSatisfaction Satisfaction; 6437 if (CheckFunctionConstraints(Function, Satisfaction) || 6438 !Satisfaction.IsSatisfied) { 6439 Candidate.Viable = false; 6440 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6441 return; 6442 } 6443 } 6444 6445 // Determine the implicit conversion sequences for each of the 6446 // arguments. 6447 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6448 unsigned ConvIdx = 6449 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6450 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6451 // We already formed a conversion sequence for this parameter during 6452 // template argument deduction. 6453 } else if (ArgIdx < NumParams) { 6454 // (C++ 13.3.2p3): for F to be a viable function, there shall 6455 // exist for each argument an implicit conversion sequence 6456 // (13.3.3.1) that converts that argument to the corresponding 6457 // parameter of F. 6458 QualType ParamType = Proto->getParamType(ArgIdx); 6459 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6460 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6461 /*InOverloadResolution=*/true, 6462 /*AllowObjCWritebackConversion=*/ 6463 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6464 if (Candidate.Conversions[ConvIdx].isBad()) { 6465 Candidate.Viable = false; 6466 Candidate.FailureKind = ovl_fail_bad_conversion; 6467 return; 6468 } 6469 } else { 6470 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6471 // argument for which there is no corresponding parameter is 6472 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6473 Candidate.Conversions[ConvIdx].setEllipsis(); 6474 } 6475 } 6476 6477 if (EnableIfAttr *FailedAttr = 6478 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6479 Candidate.Viable = false; 6480 Candidate.FailureKind = ovl_fail_enable_if; 6481 Candidate.DeductionFailure.Data = FailedAttr; 6482 return; 6483 } 6484 6485 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6486 Candidate.Viable = false; 6487 Candidate.FailureKind = ovl_fail_ext_disabled; 6488 return; 6489 } 6490} 6491 6492ObjCMethodDecl * 6493Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6494 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6495 if (Methods.size() <= 1) 6496 return nullptr; 6497 6498 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6499 bool Match = true; 6500 ObjCMethodDecl *Method = Methods[b]; 6501 unsigned NumNamedArgs = Sel.getNumArgs(); 6502 // Method might have more arguments than selector indicates. This is due 6503 // to addition of c-style arguments in method. 6504 if (Method->param_size() > NumNamedArgs) 6505 NumNamedArgs = Method->param_size(); 6506 if (Args.size() < NumNamedArgs) 6507 continue; 6508 6509 for (unsigned i = 0; i < NumNamedArgs; i++) { 6510 // We can't do any type-checking on a type-dependent argument. 6511 if (Args[i]->isTypeDependent()) { 6512 Match = false; 6513 break; 6514 } 6515 6516 ParmVarDecl *param = Method->parameters()[i]; 6517 Expr *argExpr = Args[i]; 6518 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6518, __PRETTY_FUNCTION__))
; 6519 6520 // Strip the unbridged-cast placeholder expression off unless it's 6521 // a consumed argument. 6522 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6523 !param->hasAttr<CFConsumedAttr>()) 6524 argExpr = stripARCUnbridgedCast(argExpr); 6525 6526 // If the parameter is __unknown_anytype, move on to the next method. 6527 if (param->getType() == Context.UnknownAnyTy) { 6528 Match = false; 6529 break; 6530 } 6531 6532 ImplicitConversionSequence ConversionState 6533 = TryCopyInitialization(*this, argExpr, param->getType(), 6534 /*SuppressUserConversions*/false, 6535 /*InOverloadResolution=*/true, 6536 /*AllowObjCWritebackConversion=*/ 6537 getLangOpts().ObjCAutoRefCount, 6538 /*AllowExplicit*/false); 6539 // This function looks for a reasonably-exact match, so we consider 6540 // incompatible pointer conversions to be a failure here. 6541 if (ConversionState.isBad() || 6542 (ConversionState.isStandard() && 6543 ConversionState.Standard.Second == 6544 ICK_Incompatible_Pointer_Conversion)) { 6545 Match = false; 6546 break; 6547 } 6548 } 6549 // Promote additional arguments to variadic methods. 6550 if (Match && Method->isVariadic()) { 6551 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6552 if (Args[i]->isTypeDependent()) { 6553 Match = false; 6554 break; 6555 } 6556 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6557 nullptr); 6558 if (Arg.isInvalid()) { 6559 Match = false; 6560 break; 6561 } 6562 } 6563 } else { 6564 // Check for extra arguments to non-variadic methods. 6565 if (Args.size() != NumNamedArgs) 6566 Match = false; 6567 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6568 // Special case when selectors have no argument. In this case, select 6569 // one with the most general result type of 'id'. 6570 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6571 QualType ReturnT = Methods[b]->getReturnType(); 6572 if (ReturnT->isObjCIdType()) 6573 return Methods[b]; 6574 } 6575 } 6576 } 6577 6578 if (Match) 6579 return Method; 6580 } 6581 return nullptr; 6582} 6583 6584static bool convertArgsForAvailabilityChecks( 6585 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6586 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6587 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6588 if (ThisArg) { 6589 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6590 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6591, __PRETTY_FUNCTION__))
6591 "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6591, __PRETTY_FUNCTION__))
; 6592 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6592, __PRETTY_FUNCTION__))
; 6593 ExprResult R = S.PerformObjectArgumentInitialization( 6594 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6595 if (R.isInvalid()) 6596 return false; 6597 ConvertedThis = R.get(); 6598 } else { 6599 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6600 (void)MD; 6601 assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6603, __PRETTY_FUNCTION__))
6602 isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6603, __PRETTY_FUNCTION__))
6603 "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6603, __PRETTY_FUNCTION__))
; 6604 } 6605 ConvertedThis = nullptr; 6606 } 6607 6608 // Ignore any variadic arguments. Converting them is pointless, since the 6609 // user can't refer to them in the function condition. 6610 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6611 6612 // Convert the arguments. 6613 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6614 ExprResult R; 6615 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6616 S.Context, Function->getParamDecl(I)), 6617 SourceLocation(), Args[I]); 6618 6619 if (R.isInvalid()) 6620 return false; 6621 6622 ConvertedArgs.push_back(R.get()); 6623 } 6624 6625 if (Trap.hasErrorOccurred()) 6626 return false; 6627 6628 // Push default arguments if needed. 6629 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6630 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6631 ParmVarDecl *P = Function->getParamDecl(i); 6632 if (!P->hasDefaultArg()) 6633 return false; 6634 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6635 if (R.isInvalid()) 6636 return false; 6637 ConvertedArgs.push_back(R.get()); 6638 } 6639 6640 if (Trap.hasErrorOccurred()) 6641 return false; 6642 } 6643 return true; 6644} 6645 6646EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6647 SourceLocation CallLoc, 6648 ArrayRef<Expr *> Args, 6649 bool MissingImplicitThis) { 6650 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6651 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6652 return nullptr; 6653 6654 SFINAETrap Trap(*this); 6655 SmallVector<Expr *, 16> ConvertedArgs; 6656 // FIXME: We should look into making enable_if late-parsed. 6657 Expr *DiscardedThis; 6658 if (!convertArgsForAvailabilityChecks( 6659 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6660 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6661 return *EnableIfAttrs.begin(); 6662 6663 for (auto *EIA : EnableIfAttrs) { 6664 APValue Result; 6665 // FIXME: This doesn't consider value-dependent cases, because doing so is 6666 // very difficult. Ideally, we should handle them more gracefully. 6667 if (EIA->getCond()->isValueDependent() || 6668 !EIA->getCond()->EvaluateWithSubstitution( 6669 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6670 return EIA; 6671 6672 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6673 return EIA; 6674 } 6675 return nullptr; 6676} 6677 6678template <typename CheckFn> 6679static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6680 bool ArgDependent, SourceLocation Loc, 6681 CheckFn &&IsSuccessful) { 6682 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6683 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6684 if (ArgDependent == DIA->getArgDependent()) 6685 Attrs.push_back(DIA); 6686 } 6687 6688 // Common case: No diagnose_if attributes, so we can quit early. 6689 if (Attrs.empty()) 6690 return false; 6691 6692 auto WarningBegin = std::stable_partition( 6693 Attrs.begin(), Attrs.end(), 6694 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6695 6696 // Note that diagnose_if attributes are late-parsed, so they appear in the 6697 // correct order (unlike enable_if attributes). 6698 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6699 IsSuccessful); 6700 if (ErrAttr != WarningBegin) { 6701 const DiagnoseIfAttr *DIA = *ErrAttr; 6702 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6703 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6704 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6705 return true; 6706 } 6707 6708 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6709 if (IsSuccessful(DIA)) { 6710 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6711 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6712 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6713 } 6714 6715 return false; 6716} 6717 6718bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6719 const Expr *ThisArg, 6720 ArrayRef<const Expr *> Args, 6721 SourceLocation Loc) { 6722 return diagnoseDiagnoseIfAttrsWith( 6723 *this, Function, /*ArgDependent=*/true, Loc, 6724 [&](const DiagnoseIfAttr *DIA) { 6725 APValue Result; 6726 // It's sane to use the same Args for any redecl of this function, since 6727 // EvaluateWithSubstitution only cares about the position of each 6728 // argument in the arg list, not the ParmVarDecl* it maps to. 6729 if (!DIA->getCond()->EvaluateWithSubstitution( 6730 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6731 return false; 6732 return Result.isInt() && Result.getInt().getBoolValue(); 6733 }); 6734} 6735 6736bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6737 SourceLocation Loc) { 6738 return diagnoseDiagnoseIfAttrsWith( 6739 *this, ND, /*ArgDependent=*/false, Loc, 6740 [&](const DiagnoseIfAttr *DIA) { 6741 bool Result; 6742 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6743 Result; 6744 }); 6745} 6746 6747/// Add all of the function declarations in the given function set to 6748/// the overload candidate set. 6749void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6750 ArrayRef<Expr *> Args, 6751 OverloadCandidateSet &CandidateSet, 6752 TemplateArgumentListInfo *ExplicitTemplateArgs, 6753 bool SuppressUserConversions, 6754 bool PartialOverloading, 6755 bool FirstArgumentIsBase) { 6756 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6757 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6758 ArrayRef<Expr *> FunctionArgs = Args; 6759 6760 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6761 FunctionDecl *FD = 6762 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6763 6764 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6765 QualType ObjectType; 6766 Expr::Classification ObjectClassification; 6767 if (Args.size() > 0) { 6768 if (Expr *E = Args[0]) { 6769 // Use the explicit base to restrict the lookup: 6770 ObjectType = E->getType(); 6771 // Pointers in the object arguments are implicitly dereferenced, so we 6772 // always classify them as l-values. 6773 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6774 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6775 else 6776 ObjectClassification = E->Classify(Context); 6777 } // .. else there is an implicit base. 6778 FunctionArgs = Args.slice(1); 6779 } 6780 if (FunTmpl) { 6781 AddMethodTemplateCandidate( 6782 FunTmpl, F.getPair(), 6783 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6784 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6785 FunctionArgs, CandidateSet, SuppressUserConversions, 6786 PartialOverloading); 6787 } else { 6788 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6789 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6790 ObjectClassification, FunctionArgs, CandidateSet, 6791 SuppressUserConversions, PartialOverloading); 6792 } 6793 } else { 6794 // This branch handles both standalone functions and static methods. 6795 6796 // Slice the first argument (which is the base) when we access 6797 // static method as non-static. 6798 if (Args.size() > 0 && 6799 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6800 !isa<CXXConstructorDecl>(FD)))) { 6801 assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast
<void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6801, __PRETTY_FUNCTION__))
; 6802 FunctionArgs = Args.slice(1); 6803 } 6804 if (FunTmpl) { 6805 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6806 ExplicitTemplateArgs, FunctionArgs, 6807 CandidateSet, SuppressUserConversions, 6808 PartialOverloading); 6809 } else { 6810 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6811 SuppressUserConversions, PartialOverloading); 6812 } 6813 } 6814 } 6815} 6816 6817/// AddMethodCandidate - Adds a named decl (which is some kind of 6818/// method) as a method candidate to the given overload set. 6819void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6820 Expr::Classification ObjectClassification, 6821 ArrayRef<Expr *> Args, 6822 OverloadCandidateSet &CandidateSet, 6823 bool SuppressUserConversions, 6824 OverloadCandidateParamOrder PO) { 6825 NamedDecl *Decl = FoundDecl.getDecl(); 6826 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6827 6828 if (isa<UsingShadowDecl>(Decl)) 6829 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6830 6831 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6832 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6833, __PRETTY_FUNCTION__))
6833 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6833, __PRETTY_FUNCTION__))
; 6834 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6835 /*ExplicitArgs*/ nullptr, ObjectType, 6836 ObjectClassification, Args, CandidateSet, 6837 SuppressUserConversions, false, PO); 6838 } else { 6839 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6840 ObjectType, ObjectClassification, Args, CandidateSet, 6841 SuppressUserConversions, false, None, PO); 6842 } 6843} 6844 6845/// AddMethodCandidate - Adds the given C++ member function to the set 6846/// of candidate functions, using the given function call arguments 6847/// and the object argument (@c Object). For example, in a call 6848/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6849/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6850/// allow user-defined conversions via constructors or conversion 6851/// operators. 6852void 6853Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6854 CXXRecordDecl *ActingContext, QualType ObjectType, 6855 Expr::Classification ObjectClassification, 6856 ArrayRef<Expr *> Args, 6857 OverloadCandidateSet &CandidateSet, 6858 bool SuppressUserConversions, 6859 bool PartialOverloading, 6860 ConversionSequenceList EarlyConversions, 6861 OverloadCandidateParamOrder PO) { 6862 const FunctionProtoType *Proto 6863 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6864 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6864, __PRETTY_FUNCTION__))
; 6865 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6866, __PRETTY_FUNCTION__))
6866 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 6866, __PRETTY_FUNCTION__))
; 6867 6868 if (!CandidateSet.isNewCandidate(Method, PO)) 6869 return; 6870 6871 // C++11 [class.copy]p23: [DR1402] 6872 // A defaulted move assignment operator that is defined as deleted is 6873 // ignored by overload resolution. 6874 if (Method->isDefaulted() && Method->isDeleted() && 6875 Method->isMoveAssignmentOperator()) 6876 return; 6877 6878 // Overload resolution is always an unevaluated context. 6879 EnterExpressionEvaluationContext Unevaluated( 6880 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6881 6882 // Add this candidate 6883 OverloadCandidate &Candidate = 6884 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6885 Candidate.FoundDecl = FoundDecl; 6886 Candidate.Function = Method; 6887 Candidate.RewriteKind = 6888 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6889 Candidate.IsSurrogate = false; 6890 Candidate.IgnoreObjectArgument = false; 6891 Candidate.ExplicitCallArguments = Args.size(); 6892 6893 unsigned NumParams = Proto->getNumParams(); 6894 6895 // (C++ 13.3.2p2): A candidate function having fewer than m 6896 // parameters is viable only if it has an ellipsis in its parameter 6897 // list (8.3.5). 6898 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6899 !Proto->isVariadic()) { 6900 Candidate.Viable = false; 6901 Candidate.FailureKind = ovl_fail_too_many_arguments; 6902 return; 6903 } 6904 6905 // (C++ 13.3.2p2): A candidate function having more than m parameters 6906 // is viable only if the (m+1)st parameter has a default argument 6907 // (8.3.6). For the purposes of overload resolution, the 6908 // parameter list is truncated on the right, so that there are 6909 // exactly m parameters. 6910 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6911 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6912 // Not enough arguments. 6913 Candidate.Viable = false; 6914 Candidate.FailureKind = ovl_fail_too_few_arguments; 6915 return; 6916 } 6917 6918 Candidate.Viable = true; 6919 6920 if (Method->isStatic() || ObjectType.isNull()) 6921 // The implicit object argument is ignored. 6922 Candidate.IgnoreObjectArgument = true; 6923 else { 6924 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6925 // Determine the implicit conversion sequence for the object 6926 // parameter. 6927 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6928 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6929 Method, ActingContext); 6930 if (Candidate.Conversions[ConvIdx].isBad()) { 6931 Candidate.Viable = false; 6932 Candidate.FailureKind = ovl_fail_bad_conversion; 6933 return; 6934 } 6935 } 6936 6937 // (CUDA B.1): Check for invalid calls between targets. 6938 if (getLangOpts().CUDA) 6939 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6940 if (!IsAllowedCUDACall(Caller, Method)) { 6941 Candidate.Viable = false; 6942 Candidate.FailureKind = ovl_fail_bad_target; 6943 return; 6944 } 6945 6946 if (Method->getTrailingRequiresClause()) { 6947 ConstraintSatisfaction Satisfaction; 6948 if (CheckFunctionConstraints(Method, Satisfaction) || 6949 !Satisfaction.IsSatisfied) { 6950 Candidate.Viable = false; 6951 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6952 return; 6953 } 6954 } 6955 6956 // Determine the implicit conversion sequences for each of the 6957 // arguments. 6958 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6959 unsigned ConvIdx = 6960 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6961 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6962 // We already formed a conversion sequence for this parameter during 6963 // template argument deduction. 6964 } else if (ArgIdx < NumParams) { 6965 // (C++ 13.3.2p3): for F to be a viable function, there shall 6966 // exist for each argument an implicit conversion sequence 6967 // (13.3.3.1) that converts that argument to the corresponding 6968 // parameter of F. 6969 QualType ParamType = Proto->getParamType(ArgIdx); 6970 Candidate.Conversions[ConvIdx] 6971 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6972 SuppressUserConversions, 6973 /*InOverloadResolution=*/true, 6974 /*AllowObjCWritebackConversion=*/ 6975 getLangOpts().ObjCAutoRefCount); 6976 if (Candidate.Conversions[ConvIdx].isBad()) { 6977 Candidate.Viable = false; 6978 Candidate.FailureKind = ovl_fail_bad_conversion; 6979 return; 6980 } 6981 } else { 6982 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6983 // argument for which there is no corresponding parameter is 6984 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6985 Candidate.Conversions[ConvIdx].setEllipsis(); 6986 } 6987 } 6988 6989 if (EnableIfAttr *FailedAttr = 6990 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6991 Candidate.Viable = false; 6992 Candidate.FailureKind = ovl_fail_enable_if; 6993 Candidate.DeductionFailure.Data = FailedAttr; 6994 return; 6995 } 6996 6997 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6998 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6999 Candidate.Viable = false; 7000 Candidate.FailureKind = ovl_non_default_multiversion_function; 7001 } 7002} 7003 7004/// Add a C++ member function template as a candidate to the candidate 7005/// set, using template argument deduction to produce an appropriate member 7006/// function template specialization. 7007void Sema::AddMethodTemplateCandidate( 7008 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7009 CXXRecordDecl *ActingContext, 7010 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7011 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7012 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7013 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7014 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7015 return; 7016 7017 // C++ [over.match.funcs]p7: 7018 // In each case where a candidate is a function template, candidate 7019 // function template specializations are generated using template argument 7020 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7021 // candidate functions in the usual way.113) A given name can refer to one 7022 // or more function templates and also to a set of overloaded non-template 7023 // functions. In such a case, the candidate functions generated from each 7024 // function template are combined with the set of non-template candidate 7025 // functions. 7026 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7027 FunctionDecl *Specialization = nullptr; 7028 ConversionSequenceList Conversions; 7029 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7030 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7031 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7032 return CheckNonDependentConversions( 7033 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7034 SuppressUserConversions, ActingContext, ObjectType, 7035 ObjectClassification, PO); 7036 })) { 7037 OverloadCandidate &Candidate = 7038 CandidateSet.addCandidate(Conversions.size(), Conversions); 7039 Candidate.FoundDecl = FoundDecl; 7040 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7041 Candidate.Viable = false; 7042 Candidate.RewriteKind = 7043 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7044 Candidate.IsSurrogate = false; 7045 Candidate.IgnoreObjectArgument = 7046 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7047 ObjectType.isNull(); 7048 Candidate.ExplicitCallArguments = Args.size(); 7049 if (Result == TDK_NonDependentConversionFailure) 7050 Candidate.FailureKind = ovl_fail_bad_conversion; 7051 else { 7052 Candidate.FailureKind = ovl_fail_bad_deduction; 7053 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7054 Info); 7055 } 7056 return; 7057 } 7058 7059 // Add the function template specialization produced by template argument 7060 // deduction as a candidate. 7061 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7061, __PRETTY_FUNCTION__))
; 7062 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7063, __PRETTY_FUNCTION__))
7063 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7063, __PRETTY_FUNCTION__))
; 7064 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7065 ActingContext, ObjectType, ObjectClassification, Args, 7066 CandidateSet, SuppressUserConversions, PartialOverloading, 7067 Conversions, PO); 7068} 7069 7070/// Determine whether a given function template has a simple explicit specifier 7071/// or a non-value-dependent explicit-specification that evaluates to true. 7072static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7073 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7074} 7075 7076/// Add a C++ function template specialization as a candidate 7077/// in the candidate set, using template argument deduction to produce 7078/// an appropriate function template specialization. 7079void Sema::AddTemplateOverloadCandidate( 7080 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7081 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7082 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7083 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7084 OverloadCandidateParamOrder PO) { 7085 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7086 return; 7087 7088 // If the function template has a non-dependent explicit specification, 7089 // exclude it now if appropriate; we are not permitted to perform deduction 7090 // and substitution in this case. 7091 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7092 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7093 Candidate.FoundDecl = FoundDecl; 7094 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7095 Candidate.Viable = false; 7096 Candidate.FailureKind = ovl_fail_explicit; 7097 return; 7098 } 7099 7100 // C++ [over.match.funcs]p7: 7101 // In each case where a candidate is a function template, candidate 7102 // function template specializations are generated using template argument 7103 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7104 // candidate functions in the usual way.113) A given name can refer to one 7105 // or more function templates and also to a set of overloaded non-template 7106 // functions. In such a case, the candidate functions generated from each 7107 // function template are combined with the set of non-template candidate 7108 // functions. 7109 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7110 FunctionDecl *Specialization = nullptr; 7111 ConversionSequenceList Conversions; 7112 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7113 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7114 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7115 return CheckNonDependentConversions( 7116 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7117 SuppressUserConversions, nullptr, QualType(), {}, PO); 7118 })) { 7119 OverloadCandidate &Candidate = 7120 CandidateSet.addCandidate(Conversions.size(), Conversions); 7121 Candidate.FoundDecl = FoundDecl; 7122 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7123 Candidate.Viable = false; 7124 Candidate.RewriteKind = 7125 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7126 Candidate.IsSurrogate = false; 7127 Candidate.IsADLCandidate = IsADLCandidate; 7128 // Ignore the object argument if there is one, since we don't have an object 7129 // type. 7130 Candidate.IgnoreObjectArgument = 7131 isa<CXXMethodDecl>(Candidate.Function) && 7132 !isa<CXXConstructorDecl>(Candidate.Function); 7133 Candidate.ExplicitCallArguments = Args.size(); 7134 if (Result == TDK_NonDependentConversionFailure) 7135 Candidate.FailureKind = ovl_fail_bad_conversion; 7136 else { 7137 Candidate.FailureKind = ovl_fail_bad_deduction; 7138 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7139 Info); 7140 } 7141 return; 7142 } 7143 7144 // Add the function template specialization produced by template argument 7145 // deduction as a candidate. 7146 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7146, __PRETTY_FUNCTION__))
; 7147 AddOverloadCandidate( 7148 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7149 PartialOverloading, AllowExplicit, 7150 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7151} 7152 7153/// Check that implicit conversion sequences can be formed for each argument 7154/// whose corresponding parameter has a non-dependent type, per DR1391's 7155/// [temp.deduct.call]p10. 7156bool Sema::CheckNonDependentConversions( 7157 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7158 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7159 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7160 CXXRecordDecl *ActingContext, QualType ObjectType, 7161 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7162 // FIXME: The cases in which we allow explicit conversions for constructor 7163 // arguments never consider calling a constructor template. It's not clear 7164 // that is correct. 7165 const bool AllowExplicit = false; 7166 7167 auto *FD = FunctionTemplate->getTemplatedDecl(); 7168 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7169 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7170 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7171 7172 Conversions = 7173 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7174 7175 // Overload resolution is always an unevaluated context. 7176 EnterExpressionEvaluationContext Unevaluated( 7177 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7178 7179 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7180 // require that, but this check should never result in a hard error, and 7181 // overload resolution is permitted to sidestep instantiations. 7182 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7183 !ObjectType.isNull()) { 7184 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7185 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7186 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7187 Method, ActingContext); 7188 if (Conversions[ConvIdx].isBad()) 7189 return true; 7190 } 7191 7192 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7193 ++I) { 7194 QualType ParamType = ParamTypes[I]; 7195 if (!ParamType->isDependentType()) { 7196 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7197 ? 0 7198 : (ThisConversions + I); 7199 Conversions[ConvIdx] 7200 = TryCopyInitialization(*this, Args[I], ParamType, 7201 SuppressUserConversions, 7202 /*InOverloadResolution=*/true, 7203 /*AllowObjCWritebackConversion=*/ 7204 getLangOpts().ObjCAutoRefCount, 7205 AllowExplicit); 7206 if (Conversions[ConvIdx].isBad()) 7207 return true; 7208 } 7209 } 7210 7211 return false; 7212} 7213 7214/// Determine whether this is an allowable conversion from the result 7215/// of an explicit conversion operator to the expected type, per C++ 7216/// [over.match.conv]p1 and [over.match.ref]p1. 7217/// 7218/// \param ConvType The return type of the conversion function. 7219/// 7220/// \param ToType The type we are converting to. 7221/// 7222/// \param AllowObjCPointerConversion Allow a conversion from one 7223/// Objective-C pointer to another. 7224/// 7225/// \returns true if the conversion is allowable, false otherwise. 7226static bool isAllowableExplicitConversion(Sema &S, 7227 QualType ConvType, QualType ToType, 7228 bool AllowObjCPointerConversion) { 7229 QualType ToNonRefType = ToType.getNonReferenceType(); 7230 7231 // Easy case: the types are the same. 7232 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7233 return true; 7234 7235 // Allow qualification conversions. 7236 bool ObjCLifetimeConversion; 7237 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7238 ObjCLifetimeConversion)) 7239 return true; 7240 7241 // If we're not allowed to consider Objective-C pointer conversions, 7242 // we're done. 7243 if (!AllowObjCPointerConversion) 7244 return false; 7245 7246 // Is this an Objective-C pointer conversion? 7247 bool IncompatibleObjC = false; 7248 QualType ConvertedType; 7249 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7250 IncompatibleObjC); 7251} 7252 7253/// AddConversionCandidate - Add a C++ conversion function as a 7254/// candidate in the candidate set (C++ [over.match.conv], 7255/// C++ [over.match.copy]). From is the expression we're converting from, 7256/// and ToType is the type that we're eventually trying to convert to 7257/// (which may or may not be the same type as the type that the 7258/// conversion function produces). 7259void Sema::AddConversionCandidate( 7260 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7261 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7262 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7263 bool AllowExplicit, bool AllowResultConversion) { 7264 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7265, __PRETTY_FUNCTION__))
7265 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7265, __PRETTY_FUNCTION__))
; 7266 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7267 if (!CandidateSet.isNewCandidate(Conversion)) 7268 return; 7269 7270 // If the conversion function has an undeduced return type, trigger its 7271 // deduction now. 7272 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7273 if (DeduceReturnType(Conversion, From->getExprLoc())) 7274 return; 7275 ConvType = Conversion->getConversionType().getNonReferenceType(); 7276 } 7277 7278 // If we don't allow any conversion of the result type, ignore conversion 7279 // functions that don't convert to exactly (possibly cv-qualified) T. 7280 if (!AllowResultConversion && 7281 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7282 return; 7283 7284 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7285 // operator is only a candidate if its return type is the target type or 7286 // can be converted to the target type with a qualification conversion. 7287 // 7288 // FIXME: Include such functions in the candidate list and explain why we 7289 // can't select them. 7290 if (Conversion->isExplicit() && 7291 !isAllowableExplicitConversion(*this, ConvType, ToType, 7292 AllowObjCConversionOnExplicit)) 7293 return; 7294 7295 // Overload resolution is always an unevaluated context. 7296 EnterExpressionEvaluationContext Unevaluated( 7297 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7298 7299 // Add this candidate 7300 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7301 Candidate.FoundDecl = FoundDecl; 7302 Candidate.Function = Conversion; 7303 Candidate.IsSurrogate = false; 7304 Candidate.IgnoreObjectArgument = false; 7305 Candidate.FinalConversion.setAsIdentityConversion(); 7306 Candidate.FinalConversion.setFromType(ConvType); 7307 Candidate.FinalConversion.setAllToTypes(ToType); 7308 Candidate.Viable = true; 7309 Candidate.ExplicitCallArguments = 1; 7310 7311 // Explicit functions are not actually candidates at all if we're not 7312 // allowing them in this context, but keep them around so we can point 7313 // to them in diagnostics. 7314 if (!AllowExplicit && Conversion->isExplicit()) { 7315 Candidate.Viable = false; 7316 Candidate.FailureKind = ovl_fail_explicit; 7317 return; 7318 } 7319 7320 // C++ [over.match.funcs]p4: 7321 // For conversion functions, the function is considered to be a member of 7322 // the class of the implicit implied object argument for the purpose of 7323 // defining the type of the implicit object parameter. 7324 // 7325 // Determine the implicit conversion sequence for the implicit 7326 // object parameter. 7327 QualType ImplicitParamType = From->getType(); 7328 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7329 ImplicitParamType = FromPtrType->getPointeeType(); 7330 CXXRecordDecl *ConversionContext 7331 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7332 7333 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7334 *this, CandidateSet.getLocation(), From->getType(), 7335 From->Classify(Context), Conversion, ConversionContext); 7336 7337 if (Candidate.Conversions[0].isBad()) { 7338 Candidate.Viable = false; 7339 Candidate.FailureKind = ovl_fail_bad_conversion; 7340 return; 7341 } 7342 7343 if (Conversion->getTrailingRequiresClause()) { 7344 ConstraintSatisfaction Satisfaction; 7345 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7346 !Satisfaction.IsSatisfied) { 7347 Candidate.Viable = false; 7348 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7349 return; 7350 } 7351 } 7352 7353 // We won't go through a user-defined type conversion function to convert a 7354 // derived to base as such conversions are given Conversion Rank. They only 7355 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7356 QualType FromCanon 7357 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7358 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7359 if (FromCanon == ToCanon || 7360 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7361 Candidate.Viable = false; 7362 Candidate.FailureKind = ovl_fail_trivial_conversion; 7363 return; 7364 } 7365 7366 // To determine what the conversion from the result of calling the 7367 // conversion function to the type we're eventually trying to 7368 // convert to (ToType), we need to synthesize a call to the 7369 // conversion function and attempt copy initialization from it. This 7370 // makes sure that we get the right semantics with respect to 7371 // lvalues/rvalues and the type. Fortunately, we can allocate this 7372 // call on the stack and we don't need its arguments to be 7373 // well-formed. 7374 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7375 VK_LValue, From->getBeginLoc()); 7376 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7377 Context.getPointerType(Conversion->getType()), 7378 CK_FunctionToPointerDecay, &ConversionRef, 7379 VK_RValue, FPOptionsOverride()); 7380 7381 QualType ConversionType = Conversion->getConversionType(); 7382 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7383 Candidate.Viable = false; 7384 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7385 return; 7386 } 7387 7388 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7389 7390 // Note that it is safe to allocate CallExpr on the stack here because 7391 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7392 // allocator). 7393 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7394 7395 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7396 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7397 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7398 7399 ImplicitConversionSequence ICS = 7400 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7401 /*SuppressUserConversions=*/true, 7402 /*InOverloadResolution=*/false, 7403 /*AllowObjCWritebackConversion=*/false); 7404 7405 switch (ICS.getKind()) { 7406 case ImplicitConversionSequence::StandardConversion: 7407 Candidate.FinalConversion = ICS.Standard; 7408 7409 // C++ [over.ics.user]p3: 7410 // If the user-defined conversion is specified by a specialization of a 7411 // conversion function template, the second standard conversion sequence 7412 // shall have exact match rank. 7413 if (Conversion->getPrimaryTemplate() && 7414 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7415 Candidate.Viable = false; 7416 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7417 return; 7418 } 7419 7420 // C++0x [dcl.init.ref]p5: 7421 // In the second case, if the reference is an rvalue reference and 7422 // the second standard conversion sequence of the user-defined 7423 // conversion sequence includes an lvalue-to-rvalue conversion, the 7424 // program is ill-formed. 7425 if (ToType->isRValueReferenceType() && 7426 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7427 Candidate.Viable = false; 7428 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7429 return; 7430 } 7431 break; 7432 7433 case ImplicitConversionSequence::BadConversion: 7434 Candidate.Viable = false; 7435 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7436 return; 7437 7438 default: 7439 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7440)
7440 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7440)
; 7441 } 7442 7443 if (EnableIfAttr *FailedAttr = 7444 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7445 Candidate.Viable = false; 7446 Candidate.FailureKind = ovl_fail_enable_if; 7447 Candidate.DeductionFailure.Data = FailedAttr; 7448 return; 7449 } 7450 7451 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7452 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7453 Candidate.Viable = false; 7454 Candidate.FailureKind = ovl_non_default_multiversion_function; 7455 } 7456} 7457 7458/// Adds a conversion function template specialization 7459/// candidate to the overload set, using template argument deduction 7460/// to deduce the template arguments of the conversion function 7461/// template from the type that we are converting to (C++ 7462/// [temp.deduct.conv]). 7463void Sema::AddTemplateConversionCandidate( 7464 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7465 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7466 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7467 bool AllowExplicit, bool AllowResultConversion) { 7468 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7469, __PRETTY_FUNCTION__))
7469 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7469, __PRETTY_FUNCTION__))
; 7470 7471 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7472 return; 7473 7474 // If the function template has a non-dependent explicit specification, 7475 // exclude it now if appropriate; we are not permitted to perform deduction 7476 // and substitution in this case. 7477 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7478 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7479 Candidate.FoundDecl = FoundDecl; 7480 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7481 Candidate.Viable = false; 7482 Candidate.FailureKind = ovl_fail_explicit; 7483 return; 7484 } 7485 7486 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7487 CXXConversionDecl *Specialization = nullptr; 7488 if (TemplateDeductionResult Result 7489 = DeduceTemplateArguments(FunctionTemplate, ToType, 7490 Specialization, Info)) { 7491 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7492 Candidate.FoundDecl = FoundDecl; 7493 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7494 Candidate.Viable = false; 7495 Candidate.FailureKind = ovl_fail_bad_deduction; 7496 Candidate.IsSurrogate = false; 7497 Candidate.IgnoreObjectArgument = false; 7498 Candidate.ExplicitCallArguments = 1; 7499 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7500 Info); 7501 return; 7502 } 7503 7504 // Add the conversion function template specialization produced by 7505 // template argument deduction as a candidate. 7506 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7506, __PRETTY_FUNCTION__))
; 7507 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7508 CandidateSet, AllowObjCConversionOnExplicit, 7509 AllowExplicit, AllowResultConversion); 7510} 7511 7512/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7513/// converts the given @c Object to a function pointer via the 7514/// conversion function @c Conversion, and then attempts to call it 7515/// with the given arguments (C++ [over.call.object]p2-4). Proto is 7516/// the type of function that we'll eventually be calling. 7517void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7518 DeclAccessPair FoundDecl, 7519 CXXRecordDecl *ActingContext, 7520 const FunctionProtoType *Proto, 7521 Expr *Object, 7522 ArrayRef<Expr *> Args, 7523 OverloadCandidateSet& CandidateSet) { 7524 if (!CandidateSet.isNewCandidate(Conversion)) 7525 return; 7526 7527 // Overload resolution is always an unevaluated context. 7528 EnterExpressionEvaluationContext Unevaluated( 7529 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7530 7531 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7532 Candidate.FoundDecl = FoundDecl; 7533 Candidate.Function = nullptr; 7534 Candidate.Surrogate = Conversion; 7535 Candidate.Viable = true; 7536 Candidate.IsSurrogate = true; 7537 Candidate.IgnoreObjectArgument = false; 7538 Candidate.ExplicitCallArguments = Args.size(); 7539 7540 // Determine the implicit conversion sequence for the implicit 7541 // object parameter. 7542 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7543 *this, CandidateSet.getLocation(), Object->getType(), 7544 Object->Classify(Context), Conversion, ActingContext); 7545 if (ObjectInit.isBad()) { 7546 Candidate.Viable = false; 7547 Candidate.FailureKind = ovl_fail_bad_conversion; 7548 Candidate.Conversions[0] = ObjectInit; 7549 return; 7550 } 7551 7552 // The first conversion is actually a user-defined conversion whose 7553 // first conversion is ObjectInit's standard conversion (which is 7554 // effectively a reference binding). Record it as such. 7555 Candidate.Conversions[0].setUserDefined(); 7556 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7557 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7558 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7559 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7560 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7561 Candidate.Conversions[0].UserDefined.After 7562 = Candidate.Conversions[0].UserDefined.Before; 7563 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7564 7565 // Find the 7566 unsigned NumParams = Proto->getNumParams(); 7567 7568 // (C++ 13.3.2p2): A candidate function having fewer than m 7569 // parameters is viable only if it has an ellipsis in its parameter 7570 // list (8.3.5). 7571 if (Args.size() > NumParams && !Proto->isVariadic()) { 7572 Candidate.Viable = false; 7573 Candidate.FailureKind = ovl_fail_too_many_arguments; 7574 return; 7575 } 7576 7577 // Function types don't have any default arguments, so just check if 7578 // we have enough arguments. 7579 if (Args.size() < NumParams) { 7580 // Not enough arguments. 7581 Candidate.Viable = false; 7582 Candidate.FailureKind = ovl_fail_too_few_arguments; 7583 return; 7584 } 7585 7586 // Determine the implicit conversion sequences for each of the 7587 // arguments. 7588 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7589 if (ArgIdx < NumParams) { 7590 // (C++ 13.3.2p3): for F to be a viable function, there shall 7591 // exist for each argument an implicit conversion sequence 7592 // (13.3.3.1) that converts that argument to the corresponding 7593 // parameter of F. 7594 QualType ParamType = Proto->getParamType(ArgIdx); 7595 Candidate.Conversions[ArgIdx + 1] 7596 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7597 /*SuppressUserConversions=*/false, 7598 /*InOverloadResolution=*/false, 7599 /*AllowObjCWritebackConversion=*/ 7600 getLangOpts().ObjCAutoRefCount); 7601 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7602 Candidate.Viable = false; 7603 Candidate.FailureKind = ovl_fail_bad_conversion; 7604 return; 7605 } 7606 } else { 7607 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7608 // argument for which there is no corresponding parameter is 7609 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7610 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7611 } 7612 } 7613 7614 if (EnableIfAttr *FailedAttr = 7615 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7616 Candidate.Viable = false; 7617 Candidate.FailureKind = ovl_fail_enable_if; 7618 Candidate.DeductionFailure.Data = FailedAttr; 7619 return; 7620 } 7621} 7622 7623/// Add all of the non-member operator function declarations in the given 7624/// function set to the overload candidate set. 7625void Sema::AddNonMemberOperatorCandidates( 7626 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7627 OverloadCandidateSet &CandidateSet, 7628 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7629 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7630 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7631 ArrayRef<Expr *> FunctionArgs = Args; 7632 7633 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7634 FunctionDecl *FD = 7635 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7636 7637 // Don't consider rewritten functions if we're not rewriting. 7638 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7639 continue; 7640 7641 assert(!isa<CXXMethodDecl>(FD) &&((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7642, __PRETTY_FUNCTION__))
7642 "unqualified operator lookup found a member function")((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7642, __PRETTY_FUNCTION__))
; 7643 7644 if (FunTmpl) { 7645 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7646 FunctionArgs, CandidateSet); 7647 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7648 AddTemplateOverloadCandidate( 7649 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7650 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7651 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7652 } else { 7653 if (ExplicitTemplateArgs) 7654 continue; 7655 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7656 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7657 AddOverloadCandidate(FD, F.getPair(), 7658 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7659 false, false, true, false, ADLCallKind::NotADL, 7660 None, OverloadCandidateParamOrder::Reversed); 7661 } 7662 } 7663} 7664 7665/// Add overload candidates for overloaded operators that are 7666/// member functions. 7667/// 7668/// Add the overloaded operator candidates that are member functions 7669/// for the operator Op that was used in an operator expression such 7670/// as "x Op y". , Args/NumArgs provides the operator arguments, and 7671/// CandidateSet will store the added overload candidates. (C++ 7672/// [over.match.oper]). 7673void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7674 SourceLocation OpLoc, 7675 ArrayRef<Expr *> Args, 7676 OverloadCandidateSet &CandidateSet, 7677 OverloadCandidateParamOrder PO) { 7678 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7679 7680 // C++ [over.match.oper]p3: 7681 // For a unary operator @ with an operand of a type whose 7682 // cv-unqualified version is T1, and for a binary operator @ with 7683 // a left operand of a type whose cv-unqualified version is T1 and 7684 // a right operand of a type whose cv-unqualified version is T2, 7685 // three sets of candidate functions, designated member 7686 // candidates, non-member candidates and built-in candidates, are 7687 // constructed as follows: 7688 QualType T1 = Args[0]->getType(); 7689 7690 // -- If T1 is a complete class type or a class currently being 7691 // defined, the set of member candidates is the result of the 7692 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7693 // the set of member candidates is empty. 7694 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7695 // Complete the type if it can be completed. 7696 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7697 return; 7698 // If the type is neither complete nor being defined, bail out now. 7699 if (!T1Rec->getDecl()->getDefinition()) 7700 return; 7701 7702 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7703 LookupQualifiedName(Operators, T1Rec->getDecl()); 7704 Operators.suppressDiagnostics(); 7705 7706 for (LookupResult::iterator Oper = Operators.begin(), 7707 OperEnd = Operators.end(); 7708 Oper != OperEnd; 7709 ++Oper) 7710 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7711 Args[0]->Classify(Context), Args.slice(1), 7712 CandidateSet, /*SuppressUserConversion=*/false, PO); 7713 } 7714} 7715 7716/// AddBuiltinCandidate - Add a candidate for a built-in 7717/// operator. ResultTy and ParamTys are the result and parameter types 7718/// of the built-in candidate, respectively. Args and NumArgs are the 7719/// arguments being passed to the candidate. IsAssignmentOperator 7720/// should be true when this built-in candidate is an assignment 7721/// operator. NumContextualBoolArguments is the number of arguments 7722/// (at the beginning of the argument list) that will be contextually 7723/// converted to bool. 7724void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7725 OverloadCandidateSet& CandidateSet, 7726 bool IsAssignmentOperator, 7727 unsigned NumContextualBoolArguments) { 7728 // Overload resolution is always an unevaluated context. 7729 EnterExpressionEvaluationContext Unevaluated( 7730 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7731 7732 // Add this candidate 7733 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7734 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7735 Candidate.Function = nullptr; 7736 Candidate.IsSurrogate = false; 7737 Candidate.IgnoreObjectArgument = false; 7738 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7739 7740 // Determine the implicit conversion sequences for each of the 7741 // arguments. 7742 Candidate.Viable = true; 7743 Candidate.ExplicitCallArguments = Args.size(); 7744 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7745 // C++ [over.match.oper]p4: 7746 // For the built-in assignment operators, conversions of the 7747 // left operand are restricted as follows: 7748 // -- no temporaries are introduced to hold the left operand, and 7749 // -- no user-defined conversions are applied to the left 7750 // operand to achieve a type match with the left-most 7751 // parameter of a built-in candidate. 7752 // 7753 // We block these conversions by turning off user-defined 7754 // conversions, since that is the only way that initialization of 7755 // a reference to a non-class type can occur from something that 7756 // is not of the same type. 7757 if (ArgIdx < NumContextualBoolArguments) { 7758 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7759, __PRETTY_FUNCTION__))
7759 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7759, __PRETTY_FUNCTION__))
; 7760 Candidate.Conversions[ArgIdx] 7761 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7762 } else { 7763 Candidate.Conversions[ArgIdx] 7764 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7765 ArgIdx == 0 && IsAssignmentOperator, 7766 /*InOverloadResolution=*/false, 7767 /*AllowObjCWritebackConversion=*/ 7768 getLangOpts().ObjCAutoRefCount); 7769 } 7770 if (Candidate.Conversions[ArgIdx].isBad()) { 7771 Candidate.Viable = false; 7772 Candidate.FailureKind = ovl_fail_bad_conversion; 7773 break; 7774 } 7775 } 7776} 7777 7778namespace { 7779 7780/// BuiltinCandidateTypeSet - A set of types that will be used for the 7781/// candidate operator functions for built-in operators (C++ 7782/// [over.built]). The types are separated into pointer types and 7783/// enumeration types. 7784class BuiltinCandidateTypeSet { 7785 /// TypeSet - A set of types. 7786 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7787 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7788 7789 /// PointerTypes - The set of pointer types that will be used in the 7790 /// built-in candidates. 7791 TypeSet PointerTypes; 7792 7793 /// MemberPointerTypes - The set of member pointer types that will be 7794 /// used in the built-in candidates. 7795 TypeSet MemberPointerTypes; 7796 7797 /// EnumerationTypes - The set of enumeration types that will be 7798 /// used in the built-in candidates. 7799 TypeSet EnumerationTypes; 7800 7801 /// The set of vector types that will be used in the built-in 7802 /// candidates. 7803 TypeSet VectorTypes; 7804 7805 /// The set of matrix types that will be used in the built-in 7806 /// candidates. 7807 TypeSet MatrixTypes; 7808 7809 /// A flag indicating non-record types are viable candidates 7810 bool HasNonRecordTypes; 7811 7812 /// A flag indicating whether either arithmetic or enumeration types 7813 /// were present in the candidate set. 7814 bool HasArithmeticOrEnumeralTypes; 7815 7816 /// A flag indicating whether the nullptr type was present in the 7817 /// candidate set. 7818 bool HasNullPtrType; 7819 7820 /// Sema - The semantic analysis instance where we are building the 7821 /// candidate type set. 7822 Sema &SemaRef; 7823 7824 /// Context - The AST context in which we will build the type sets. 7825 ASTContext &Context; 7826 7827 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7828 const Qualifiers &VisibleQuals); 7829 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7830 7831public: 7832 /// iterator - Iterates through the types that are part of the set. 7833 typedef TypeSet::iterator iterator; 7834 7835 BuiltinCandidateTypeSet(Sema &SemaRef) 7836 : HasNonRecordTypes(false), 7837 HasArithmeticOrEnumeralTypes(false), 7838 HasNullPtrType(false), 7839 SemaRef(SemaRef), 7840 Context(SemaRef.Context) { } 7841 7842 void AddTypesConvertedFrom(QualType Ty, 7843 SourceLocation Loc, 7844 bool AllowUserConversions, 7845 bool AllowExplicitConversions, 7846 const Qualifiers &VisibleTypeConversionsQuals); 7847 7848 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7849 llvm::iterator_range<iterator> member_pointer_types() { 7850 return MemberPointerTypes; 7851 } 7852 llvm::iterator_range<iterator> enumeration_types() { 7853 return EnumerationTypes; 7854 } 7855 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7856 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7857 7858 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7859 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7860 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7861 bool hasNullPtrType() const { return HasNullPtrType; } 7862}; 7863 7864} // end anonymous namespace 7865 7866/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7867/// the set of pointer types along with any more-qualified variants of 7868/// that type. For example, if @p Ty is "int const *", this routine 7869/// will add "int const *", "int const volatile *", "int const 7870/// restrict *", and "int const volatile restrict *" to the set of 7871/// pointer types. Returns true if the add of @p Ty itself succeeded, 7872/// false otherwise. 7873/// 7874/// FIXME: what to do about extended qualifiers? 7875bool 7876BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7877 const Qualifiers &VisibleQuals) { 7878 7879 // Insert this type. 7880 if (!PointerTypes.insert(Ty)) 7881 return false; 7882 7883 QualType PointeeTy; 7884 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7885 bool buildObjCPtr = false; 7886 if (!PointerTy) { 7887 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7888 PointeeTy = PTy->getPointeeType(); 7889 buildObjCPtr = true; 7890 } else { 7891 PointeeTy = PointerTy->getPointeeType(); 7892 } 7893 7894 // Don't add qualified variants of arrays. For one, they're not allowed 7895 // (the qualifier would sink to the element type), and for another, the 7896 // only overload situation where it matters is subscript or pointer +- int, 7897 // and those shouldn't have qualifier variants anyway. 7898 if (PointeeTy->isArrayType()) 7899 return true; 7900 7901 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7902 bool hasVolatile = VisibleQuals.hasVolatile(); 7903 bool hasRestrict = VisibleQuals.hasRestrict(); 7904 7905 // Iterate through all strict supersets of BaseCVR. 7906 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7907 if ((CVR | BaseCVR) != CVR) continue; 7908 // Skip over volatile if no volatile found anywhere in the types. 7909 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7910 7911 // Skip over restrict if no restrict found anywhere in the types, or if 7912 // the type cannot be restrict-qualified. 7913 if ((CVR & Qualifiers::Restrict) && 7914 (!hasRestrict || 7915 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7916 continue; 7917 7918 // Build qualified pointee type. 7919 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7920 7921 // Build qualified pointer type. 7922 QualType QPointerTy; 7923 if (!buildObjCPtr) 7924 QPointerTy = Context.getPointerType(QPointeeTy); 7925 else 7926 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7927 7928 // Insert qualified pointer type. 7929 PointerTypes.insert(QPointerTy); 7930 } 7931 7932 return true; 7933} 7934 7935/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7936/// to the set of pointer types along with any more-qualified variants of 7937/// that type. For example, if @p Ty is "int const *", this routine 7938/// will add "int const *", "int const volatile *", "int const 7939/// restrict *", and "int const volatile restrict *" to the set of 7940/// pointer types. Returns true if the add of @p Ty itself succeeded, 7941/// false otherwise. 7942/// 7943/// FIXME: what to do about extended qualifiers? 7944bool 7945BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7946 QualType Ty) { 7947 // Insert this type. 7948 if (!MemberPointerTypes.insert(Ty)) 7949 return false; 7950 7951 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7952 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 7952, __PRETTY_FUNCTION__))
; 7953 7954 QualType PointeeTy = PointerTy->getPointeeType(); 7955 // Don't add qualified variants of arrays. For one, they're not allowed 7956 // (the qualifier would sink to the element type), and for another, the 7957 // only overload situation where it matters is subscript or pointer +- int, 7958 // and those shouldn't have qualifier variants anyway. 7959 if (PointeeTy->isArrayType()) 7960 return true; 7961 const Type *ClassTy = PointerTy->getClass(); 7962 7963 // Iterate through all strict supersets of the pointee type's CVR 7964 // qualifiers. 7965 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7966 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7967 if ((CVR | BaseCVR) != CVR) continue; 7968 7969 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7970 MemberPointerTypes.insert( 7971 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7972 } 7973 7974 return true; 7975} 7976 7977/// AddTypesConvertedFrom - Add each of the types to which the type @p 7978/// Ty can be implicit converted to the given set of @p Types. We're 7979/// primarily interested in pointer types and enumeration types. We also 7980/// take member pointer types, for the conditional operator. 7981/// AllowUserConversions is true if we should look at the conversion 7982/// functions of a class type, and AllowExplicitConversions if we 7983/// should also include the explicit conversion functions of a class 7984/// type. 7985void 7986BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7987 SourceLocation Loc, 7988 bool AllowUserConversions, 7989 bool AllowExplicitConversions, 7990 const Qualifiers &VisibleQuals) { 7991 // Only deal with canonical types. 7992 Ty = Context.getCanonicalType(Ty); 7993 7994 // Look through reference types; they aren't part of the type of an 7995 // expression for the purposes of conversions. 7996 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7997 Ty = RefTy->getPointeeType(); 7998 7999 // If we're dealing with an array type, decay to the pointer. 8000 if (Ty->isArrayType()) 8001 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8002 8003 // Otherwise, we don't care about qualifiers on the type. 8004 Ty = Ty.getLocalUnqualifiedType(); 8005 8006 // Flag if we ever add a non-record type. 8007 const RecordType *TyRec = Ty->getAs<RecordType>(); 8008 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8009 8010 // Flag if we encounter an arithmetic type. 8011 HasArithmeticOrEnumeralTypes = 8012 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8013 8014 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8015 PointerTypes.insert(Ty); 8016 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8017 // Insert our type, and its more-qualified variants, into the set 8018 // of types. 8019 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8020 return; 8021 } else if (Ty->isMemberPointerType()) { 8022 // Member pointers are far easier, since the pointee can't be converted. 8023 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8024 return; 8025 } else if (Ty->isEnumeralType()) { 8026 HasArithmeticOrEnumeralTypes = true; 8027 EnumerationTypes.insert(Ty); 8028 } else if (Ty->isVectorType()) { 8029 // We treat vector types as arithmetic types in many contexts as an 8030 // extension. 8031 HasArithmeticOrEnumeralTypes = true; 8032 VectorTypes.insert(Ty); 8033 } else if (Ty->isMatrixType()) { 8034 // Similar to vector types, we treat vector types as arithmetic types in 8035 // many contexts as an extension. 8036 HasArithmeticOrEnumeralTypes = true; 8037 MatrixTypes.insert(Ty); 8038 } else if (Ty->isNullPtrType()) { 8039 HasNullPtrType = true; 8040 } else if (AllowUserConversions && TyRec) { 8041 // No conversion functions in incomplete types. 8042 if (!SemaRef.isCompleteType(Loc, Ty)) 8043 return; 8044 8045 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8046 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8047 if (isa<UsingShadowDecl>(D)) 8048 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8049 8050 // Skip conversion function templates; they don't tell us anything 8051 // about which builtin types we can convert to. 8052 if (isa<FunctionTemplateDecl>(D)) 8053 continue; 8054 8055 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8056 if (AllowExplicitConversions || !Conv->isExplicit()) { 8057 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8058 VisibleQuals); 8059 } 8060 } 8061 } 8062} 8063/// Helper function for adjusting address spaces for the pointer or reference 8064/// operands of builtin operators depending on the argument. 8065static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8066 Expr *Arg) { 8067 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8068} 8069 8070/// Helper function for AddBuiltinOperatorCandidates() that adds 8071/// the volatile- and non-volatile-qualified assignment operators for the 8072/// given type to the candidate set. 8073static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8074 QualType T, 8075 ArrayRef<Expr *> Args, 8076 OverloadCandidateSet &CandidateSet) { 8077 QualType ParamTypes[2]; 8078 8079 // T& operator=(T&, T) 8080 ParamTypes[0] = S.Context.getLValueReferenceType( 8081 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8082 ParamTypes[1] = T; 8083 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8084 /*IsAssignmentOperator=*/true); 8085 8086 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8087 // volatile T& operator=(volatile T&, T) 8088 ParamTypes[0] = S.Context.getLValueReferenceType( 8089 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8090 Args[0])); 8091 ParamTypes[1] = T; 8092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8093 /*IsAssignmentOperator=*/true); 8094 } 8095} 8096 8097/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8098/// if any, found in visible type conversion functions found in ArgExpr's type. 8099static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8100 Qualifiers VRQuals; 8101 const RecordType *TyRec; 8102 if (const MemberPointerType *RHSMPType = 8103 ArgExpr->getType()->getAs<MemberPointerType>()) 8104 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8105 else 8106 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8107 if (!TyRec) { 8108 // Just to be safe, assume the worst case. 8109 VRQuals.addVolatile(); 8110 VRQuals.addRestrict(); 8111 return VRQuals; 8112 } 8113 8114 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8115 if (!ClassDecl->hasDefinition()) 8116 return VRQuals; 8117 8118 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8119 if (isa<UsingShadowDecl>(D)) 8120 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8121 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8122 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8123 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8124 CanTy = ResTypeRef->getPointeeType(); 8125 // Need to go down the pointer/mempointer chain and add qualifiers 8126 // as see them. 8127 bool done = false; 8128 while (!done) { 8129 if (CanTy.isRestrictQualified()) 8130 VRQuals.addRestrict(); 8131 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8132 CanTy = ResTypePtr->getPointeeType(); 8133 else if (const MemberPointerType *ResTypeMPtr = 8134 CanTy->getAs<MemberPointerType>()) 8135 CanTy = ResTypeMPtr->getPointeeType(); 8136 else 8137 done = true; 8138 if (CanTy.isVolatileQualified()) 8139 VRQuals.addVolatile(); 8140 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8141 return VRQuals; 8142 } 8143 } 8144 } 8145 return VRQuals; 8146} 8147 8148namespace { 8149 8150/// Helper class to manage the addition of builtin operator overload 8151/// candidates. It provides shared state and utility methods used throughout 8152/// the process, as well as a helper method to add each group of builtin 8153/// operator overloads from the standard to a candidate set. 8154class BuiltinOperatorOverloadBuilder { 8155 // Common instance state available to all overload candidate addition methods. 8156 Sema &S; 8157 ArrayRef<Expr *> Args; 8158 Qualifiers VisibleTypeConversionsQuals; 8159 bool HasArithmeticOrEnumeralCandidateType; 8160 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8161 OverloadCandidateSet &CandidateSet; 8162 8163 static constexpr int ArithmeticTypesCap = 24; 8164 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8165 8166 // Define some indices used to iterate over the arithmetic types in 8167 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8168 // types are that preserved by promotion (C++ [over.built]p2). 8169 unsigned FirstIntegralType, 8170 LastIntegralType; 8171 unsigned FirstPromotedIntegralType, 8172 LastPromotedIntegralType; 8173 unsigned FirstPromotedArithmeticType, 8174 LastPromotedArithmeticType; 8175 unsigned NumArithmeticTypes; 8176 8177 void InitArithmeticTypes() { 8178 // Start of promoted types. 8179 FirstPromotedArithmeticType = 0; 8180 ArithmeticTypes.push_back(S.Context.FloatTy); 8181 ArithmeticTypes.push_back(S.Context.DoubleTy); 8182 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8183 if (S.Context.getTargetInfo().hasFloat128Type()) 8184 ArithmeticTypes.push_back(S.Context.Float128Ty); 8185 8186 // Start of integral types. 8187 FirstIntegralType = ArithmeticTypes.size(); 8188 FirstPromotedIntegralType = ArithmeticTypes.size(); 8189 ArithmeticTypes.push_back(S.Context.IntTy); 8190 ArithmeticTypes.push_back(S.Context.LongTy); 8191 ArithmeticTypes.push_back(S.Context.LongLongTy); 8192 if (S.Context.getTargetInfo().hasInt128Type() || 8193 (S.Context.getAuxTargetInfo() && 8194 S.Context.getAuxTargetInfo()->hasInt128Type())) 8195 ArithmeticTypes.push_back(S.Context.Int128Ty); 8196 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8197 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8198 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8199 if (S.Context.getTargetInfo().hasInt128Type() || 8200 (S.Context.getAuxTargetInfo() && 8201 S.Context.getAuxTargetInfo()->hasInt128Type())) 8202 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8203 LastPromotedIntegralType = ArithmeticTypes.size(); 8204 LastPromotedArithmeticType = ArithmeticTypes.size(); 8205 // End of promoted types. 8206 8207 ArithmeticTypes.push_back(S.Context.BoolTy); 8208 ArithmeticTypes.push_back(S.Context.CharTy); 8209 ArithmeticTypes.push_back(S.Context.WCharTy); 8210 if (S.Context.getLangOpts().Char8) 8211 ArithmeticTypes.push_back(S.Context.Char8Ty); 8212 ArithmeticTypes.push_back(S.Context.Char16Ty); 8213 ArithmeticTypes.push_back(S.Context.Char32Ty); 8214 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8215 ArithmeticTypes.push_back(S.Context.ShortTy); 8216 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8217 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8218 LastIntegralType = ArithmeticTypes.size(); 8219 NumArithmeticTypes = ArithmeticTypes.size(); 8220 // End of integral types. 8221 // FIXME: What about complex? What about half? 8222 8223 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 8224, __PRETTY_FUNCTION__))
8224 "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 8224, __PRETTY_FUNCTION__))
; 8225 } 8226 8227 /// Helper method to factor out the common pattern of adding overloads 8228 /// for '++' and '--' builtin operators. 8229 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8230 bool HasVolatile, 8231 bool HasRestrict) { 8232 QualType ParamTypes[2] = { 8233 S.Context.getLValueReferenceType(CandidateTy), 8234 S.Context.IntTy 8235 }; 8236 8237 // Non-volatile version. 8238 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8239 8240 // Use a heuristic to reduce number of builtin candidates in the set: 8241 // add volatile version only if there are conversions to a volatile type. 8242 if (HasVolatile) { 8243 ParamTypes[0] = 8244 S.Context.getLValueReferenceType( 8245 S.Context.getVolatileType(CandidateTy)); 8246 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8247 } 8248 8249 // Add restrict version only if there are conversions to a restrict type 8250 // and our candidate type is a non-restrict-qualified pointer. 8251 if (HasRestrict && CandidateTy->isAnyPointerType() && 8252 !CandidateTy.isRestrictQualified()) { 8253 ParamTypes[0] 8254 = S.Context.getLValueReferenceType( 8255 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8256 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8257 8258 if (HasVolatile) { 8259 ParamTypes[0] 8260 = S.Context.getLValueReferenceType( 8261 S.Context.getCVRQualifiedType(CandidateTy, 8262 (Qualifiers::Volatile | 8263 Qualifiers::Restrict))); 8264 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8265 } 8266 } 8267 8268 } 8269 8270 /// Helper to add an overload candidate for a binary builtin with types \p L 8271 /// and \p R. 8272 void AddCandidate(QualType L, QualType R) { 8273 QualType LandR[2] = {L, R}; 8274 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8275 } 8276 8277public: 8278 BuiltinOperatorOverloadBuilder( 8279 Sema &S, ArrayRef<Expr *> Args, 8280 Qualifiers VisibleTypeConversionsQuals, 8281 bool HasArithmeticOrEnumeralCandidateType, 8282 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8283 OverloadCandidateSet &CandidateSet) 8284 : S(S), Args(Args), 8285 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8286 HasArithmeticOrEnumeralCandidateType( 8287 HasArithmeticOrEnumeralCandidateType), 8288 CandidateTypes(CandidateTypes), 8289 CandidateSet(CandidateSet) { 8290 8291 InitArithmeticTypes(); 8292 } 8293 8294 // Increment is deprecated for bool since C++17. 8295 // 8296 // C++ [over.built]p3: 8297 // 8298 // For every pair (T, VQ), where T is an arithmetic type other 8299 // than bool, and VQ is either volatile or empty, there exist 8300 // candidate operator functions of the form 8301 // 8302 // VQ T& operator++(VQ T&); 8303 // T operator++(VQ T&, int); 8304 // 8305 // C++ [over.built]p4: 8306 // 8307 // For every pair (T, VQ), where T is an arithmetic type other 8308 // than bool, and VQ is either volatile or empty, there exist 8309 // candidate operator functions of the form 8310 // 8311 // VQ T& operator--(VQ T&); 8312 // T operator--(VQ T&, int); 8313 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8314 if (!HasArithmeticOrEnumeralCandidateType) 8315 return; 8316 8317 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8318 const auto TypeOfT = ArithmeticTypes[Arith]; 8319 if (TypeOfT == S.Context.BoolTy) { 8320 if (Op == OO_MinusMinus) 8321 continue; 8322 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8323 continue; 8324 } 8325 addPlusPlusMinusMinusStyleOverloads( 8326 TypeOfT, 8327 VisibleTypeConversionsQuals.hasVolatile(), 8328 VisibleTypeConversionsQuals.hasRestrict()); 8329 } 8330 } 8331 8332 // C++ [over.built]p5: 8333 // 8334 // For every pair (T, VQ), where T is a cv-qualified or 8335 // cv-unqualified object type, and VQ is either volatile or 8336 // empty, there exist candidate operator functions of the form 8337 // 8338 // T*VQ& operator++(T*VQ&); 8339 // T*VQ& operator--(T*VQ&); 8340 // T* operator++(T*VQ&, int); 8341 // T* operator--(T*VQ&, int); 8342 void addPlusPlusMinusMinusPointerOverloads() { 8343 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8344 // Skip pointer types that aren't pointers to object types. 8345 if (!PtrTy->getPointeeType()->isObjectType()) 8346 continue; 8347 8348 addPlusPlusMinusMinusStyleOverloads( 8349 PtrTy, 8350 (!PtrTy.isVolatileQualified() && 8351 VisibleTypeConversionsQuals.hasVolatile()), 8352 (!PtrTy.isRestrictQualified() && 8353 VisibleTypeConversionsQuals.hasRestrict())); 8354 } 8355 } 8356 8357 // C++ [over.built]p6: 8358 // For every cv-qualified or cv-unqualified object type T, there 8359 // exist candidate operator functions of the form 8360 // 8361 // T& operator*(T*); 8362 // 8363 // C++ [over.built]p7: 8364 // For every function type T that does not have cv-qualifiers or a 8365 // ref-qualifier, there exist candidate operator functions of the form 8366 // T& operator*(T*); 8367 void addUnaryStarPointerOverloads() { 8368 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8369 QualType PointeeTy = ParamTy->getPointeeType(); 8370 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8371 continue; 8372 8373 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8374 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8375 continue; 8376 8377 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8378 } 8379 } 8380 8381 // C++ [over.built]p9: 8382 // For every promoted arithmetic type T, there exist candidate 8383 // operator functions of the form 8384 // 8385 // T operator+(T); 8386 // T operator-(T); 8387 void addUnaryPlusOrMinusArithmeticOverloads() { 8388 if (!HasArithmeticOrEnumeralCandidateType) 8389 return; 8390 8391 for (unsigned Arith = FirstPromotedArithmeticType; 8392 Arith < LastPromotedArithmeticType; ++Arith) { 8393 QualType ArithTy = ArithmeticTypes[Arith]; 8394 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8395 } 8396 8397 // Extension: We also add these operators for vector types. 8398 for (QualType VecTy : CandidateTypes[0].vector_types()) 8399 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8400 } 8401 8402 // C++ [over.built]p8: 8403 // For every type T, there exist candidate operator functions of 8404 // the form 8405 // 8406 // T* operator+(T*); 8407 void addUnaryPlusPointerOverloads() { 8408 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8409 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8410 } 8411 8412 // C++ [over.built]p10: 8413 // For every promoted integral type T, there exist candidate 8414 // operator functions of the form 8415 // 8416 // T operator~(T); 8417 void addUnaryTildePromotedIntegralOverloads() { 8418 if (!HasArithmeticOrEnumeralCandidateType) 8419 return; 8420 8421 for (unsigned Int = FirstPromotedIntegralType; 8422 Int < LastPromotedIntegralType; ++Int) { 8423 QualType IntTy = ArithmeticTypes[Int]; 8424 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8425 } 8426 8427 // Extension: We also add this operator for vector types. 8428 for (QualType VecTy : CandidateTypes[0].vector_types()) 8429 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8430 } 8431 8432 // C++ [over.match.oper]p16: 8433 // For every pointer to member type T or type std::nullptr_t, there 8434 // exist candidate operator functions of the form 8435 // 8436 // bool operator==(T,T); 8437 // bool operator!=(T,T); 8438 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8439 /// Set of (canonical) types that we've already handled. 8440 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8441 8442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8443 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8444 // Don't add the same builtin candidate twice. 8445 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8446 continue; 8447 8448 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8449 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8450 } 8451 8452 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8453 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8454 if (AddedTypes.insert(NullPtrTy).second) { 8455 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8456 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8457 } 8458 } 8459 } 8460 } 8461 8462 // C++ [over.built]p15: 8463 // 8464 // For every T, where T is an enumeration type or a pointer type, 8465 // there exist candidate operator functions of the form 8466 // 8467 // bool operator<(T, T); 8468 // bool operator>(T, T); 8469 // bool operator<=(T, T); 8470 // bool operator>=(T, T); 8471 // bool operator==(T, T); 8472 // bool operator!=(T, T); 8473 // R operator<=>(T, T) 8474 void addGenericBinaryPointerOrEnumeralOverloads() { 8475 // C++ [over.match.oper]p3: 8476 // [...]the built-in candidates include all of the candidate operator 8477 // functions defined in 13.6 that, compared to the given operator, [...] 8478 // do not have the same parameter-type-list as any non-template non-member 8479 // candidate. 8480 // 8481 // Note that in practice, this only affects enumeration types because there 8482 // aren't any built-in candidates of record type, and a user-defined operator 8483 // must have an operand of record or enumeration type. Also, the only other 8484 // overloaded operator with enumeration arguments, operator=, 8485 // cannot be overloaded for enumeration types, so this is the only place 8486 // where we must suppress candidates like this. 8487 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8488 UserDefinedBinaryOperators; 8489 8490 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8491 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8492 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8493 CEnd = CandidateSet.end(); 8494 C != CEnd; ++C) { 8495 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8496 continue; 8497 8498 if (C->Function->isFunctionTemplateSpecialization()) 8499 continue; 8500 8501 // We interpret "same parameter-type-list" as applying to the 8502 // "synthesized candidate, with the order of the two parameters 8503 // reversed", not to the original function. 8504 bool Reversed = C->isReversed(); 8505 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8506 ->getType() 8507 .getUnqualifiedType(); 8508 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8509 ->getType() 8510 .getUnqualifiedType(); 8511 8512 // Skip if either parameter isn't of enumeral type. 8513 if (!FirstParamType->isEnumeralType() || 8514 !SecondParamType->isEnumeralType()) 8515 continue; 8516 8517 // Add this operator to the set of known user-defined operators. 8518 UserDefinedBinaryOperators.insert( 8519 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8520 S.Context.getCanonicalType(SecondParamType))); 8521 } 8522 } 8523 } 8524 8525 /// Set of (canonical) types that we've already handled. 8526 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8527 8528 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8529 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8530 // Don't add the same builtin candidate twice. 8531 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8532 continue; 8533 8534 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8535 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8536 } 8537 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8538 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8539 8540 // Don't add the same builtin candidate twice, or if a user defined 8541 // candidate exists. 8542 if (!AddedTypes.insert(CanonType).second || 8543 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8544 CanonType))) 8545 continue; 8546 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8547 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8548 } 8549 } 8550 } 8551 8552 // C++ [over.built]p13: 8553 // 8554 // For every cv-qualified or cv-unqualified object type T 8555 // there exist candidate operator functions of the form 8556 // 8557 // T* operator+(T*, ptrdiff_t); 8558 // T& operator[](T*, ptrdiff_t); [BELOW] 8559 // T* operator-(T*, ptrdiff_t); 8560 // T* operator+(ptrdiff_t, T*); 8561 // T& operator[](ptrdiff_t, T*); [BELOW] 8562 // 8563 // C++ [over.built]p14: 8564 // 8565 // For every T, where T is a pointer to object type, there 8566 // exist candidate operator functions of the form 8567 // 8568 // ptrdiff_t operator-(T, T); 8569 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8570 /// Set of (canonical) types that we've already handled. 8571 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8572 8573 for (int Arg = 0; Arg < 2; ++Arg) { 8574 QualType AsymmetricParamTypes[2] = { 8575 S.Context.getPointerDiffType(), 8576 S.Context.getPointerDiffType(), 8577 }; 8578 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8579 QualType PointeeTy = PtrTy->getPointeeType(); 8580 if (!PointeeTy->isObjectType()) 8581 continue; 8582 8583 AsymmetricParamTypes[Arg] = PtrTy; 8584 if (Arg == 0 || Op == OO_Plus) { 8585 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8586 // T* operator+(ptrdiff_t, T*); 8587 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8588 } 8589 if (Op == OO_Minus) { 8590 // ptrdiff_t operator-(T, T); 8591 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8592 continue; 8593 8594 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8595 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8596 } 8597 } 8598 } 8599 } 8600 8601 // C++ [over.built]p12: 8602 // 8603 // For every pair of promoted arithmetic types L and R, there 8604 // exist candidate operator functions of the form 8605 // 8606 // LR operator*(L, R); 8607 // LR operator/(L, R); 8608 // LR operator+(L, R); 8609 // LR operator-(L, R); 8610 // bool operator<(L, R); 8611 // bool operator>(L, R); 8612 // bool operator<=(L, R); 8613 // bool operator>=(L, R); 8614 // bool operator==(L, R); 8615 // bool operator!=(L, R); 8616 // 8617 // where LR is the result of the usual arithmetic conversions 8618 // between types L and R. 8619 // 8620 // C++ [over.built]p24: 8621 // 8622 // For every pair of promoted arithmetic types L and R, there exist 8623 // candidate operator functions of the form 8624 // 8625 // LR operator?(bool, L, R); 8626 // 8627 // where LR is the result of the usual arithmetic conversions 8628 // between types L and R. 8629 // Our candidates ignore the first parameter. 8630 void addGenericBinaryArithmeticOverloads() { 8631 if (!HasArithmeticOrEnumeralCandidateType) 8632 return; 8633 8634 for (unsigned Left = FirstPromotedArithmeticType; 8635 Left < LastPromotedArithmeticType; ++Left) { 8636 for (unsigned Right = FirstPromotedArithmeticType; 8637 Right < LastPromotedArithmeticType; ++Right) { 8638 QualType LandR[2] = { ArithmeticTypes[Left], 8639 ArithmeticTypes[Right] }; 8640 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8641 } 8642 } 8643 8644 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8645 // conditional operator for vector types. 8646 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8647 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8648 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8649 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8650 } 8651 } 8652 8653 /// Add binary operator overloads for each candidate matrix type M1, M2: 8654 /// * (M1, M1) -> M1 8655 /// * (M1, M1.getElementType()) -> M1 8656 /// * (M2.getElementType(), M2) -> M2 8657 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8658 void addMatrixBinaryArithmeticOverloads() { 8659 if (!HasArithmeticOrEnumeralCandidateType) 8660 return; 8661 8662 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8663 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8664 AddCandidate(M1, M1); 8665 } 8666 8667 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8668 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8669 if (!CandidateTypes[0].containsMatrixType(M2)) 8670 AddCandidate(M2, M2); 8671 } 8672 } 8673 8674 // C++2a [over.built]p14: 8675 // 8676 // For every integral type T there exists a candidate operator function 8677 // of the form 8678 // 8679 // std::strong_ordering operator<=>(T, T) 8680 // 8681 // C++2a [over.built]p15: 8682 // 8683 // For every pair of floating-point types L and R, there exists a candidate 8684 // operator function of the form 8685 // 8686 // std::partial_ordering operator<=>(L, R); 8687 // 8688 // FIXME: The current specification for integral types doesn't play nice with 8689 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8690 // comparisons. Under the current spec this can lead to ambiguity during 8691 // overload resolution. For example: 8692 // 8693 // enum A : int {a}; 8694 // auto x = (a <=> (long)42); 8695 // 8696 // error: call is ambiguous for arguments 'A' and 'long'. 8697 // note: candidate operator<=>(int, int) 8698 // note: candidate operator<=>(long, long) 8699 // 8700 // To avoid this error, this function deviates from the specification and adds 8701 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8702 // arithmetic types (the same as the generic relational overloads). 8703 // 8704 // For now this function acts as a placeholder. 8705 void addThreeWayArithmeticOverloads() { 8706 addGenericBinaryArithmeticOverloads(); 8707 } 8708 8709 // C++ [over.built]p17: 8710 // 8711 // For every pair of promoted integral types L and R, there 8712 // exist candidate operator functions of the form 8713 // 8714 // LR operator%(L, R); 8715 // LR operator&(L, R); 8716 // LR operator^(L, R); 8717 // LR operator|(L, R); 8718 // L operator<<(L, R); 8719 // L operator>>(L, R); 8720 // 8721 // where LR is the result of the usual arithmetic conversions 8722 // between types L and R. 8723 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8724 if (!HasArithmeticOrEnumeralCandidateType) 8725 return; 8726 8727 for (unsigned Left = FirstPromotedIntegralType; 8728 Left < LastPromotedIntegralType; ++Left) { 8729 for (unsigned Right = FirstPromotedIntegralType; 8730 Right < LastPromotedIntegralType; ++Right) { 8731 QualType LandR[2] = { ArithmeticTypes[Left], 8732 ArithmeticTypes[Right] }; 8733 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8734 } 8735 } 8736 } 8737 8738 // C++ [over.built]p20: 8739 // 8740 // For every pair (T, VQ), where T is an enumeration or 8741 // pointer to member type and VQ is either volatile or 8742 // empty, there exist candidate operator functions of the form 8743 // 8744 // VQ T& operator=(VQ T&, T); 8745 void addAssignmentMemberPointerOrEnumeralOverloads() { 8746 /// Set of (canonical) types that we've already handled. 8747 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8748 8749 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8750 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8751 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8752 continue; 8753 8754 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8755 } 8756 8757 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8758 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8759 continue; 8760 8761 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8762 } 8763 } 8764 } 8765 8766 // C++ [over.built]p19: 8767 // 8768 // For every pair (T, VQ), where T is any type and VQ is either 8769 // volatile or empty, there exist candidate operator functions 8770 // of the form 8771 // 8772 // T*VQ& operator=(T*VQ&, T*); 8773 // 8774 // C++ [over.built]p21: 8775 // 8776 // For every pair (T, VQ), where T is a cv-qualified or 8777 // cv-unqualified object type and VQ is either volatile or 8778 // empty, there exist candidate operator functions of the form 8779 // 8780 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8781 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8782 void addAssignmentPointerOverloads(bool isEqualOp) { 8783 /// Set of (canonical) types that we've already handled. 8784 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8785 8786 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8787 // If this is operator=, keep track of the builtin candidates we added. 8788 if (isEqualOp) 8789 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8790 else if (!PtrTy->getPointeeType()->isObjectType()) 8791 continue; 8792 8793 // non-volatile version 8794 QualType ParamTypes[2] = { 8795 S.Context.getLValueReferenceType(PtrTy), 8796 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8797 }; 8798 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8799 /*IsAssignmentOperator=*/ isEqualOp); 8800 8801 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8802 VisibleTypeConversionsQuals.hasVolatile(); 8803 if (NeedVolatile) { 8804 // volatile version 8805 ParamTypes[0] = 8806 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8807 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8808 /*IsAssignmentOperator=*/isEqualOp); 8809 } 8810 8811 if (!PtrTy.isRestrictQualified() && 8812 VisibleTypeConversionsQuals.hasRestrict()) { 8813 // restrict version 8814 ParamTypes[0] = 8815 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8816 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8817 /*IsAssignmentOperator=*/isEqualOp); 8818 8819 if (NeedVolatile) { 8820 // volatile restrict version 8821 ParamTypes[0] = 8822 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8823 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8824 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8825 /*IsAssignmentOperator=*/isEqualOp); 8826 } 8827 } 8828 } 8829 8830 if (isEqualOp) { 8831 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8832 // Make sure we don't add the same candidate twice. 8833 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8834 continue; 8835 8836 QualType ParamTypes[2] = { 8837 S.Context.getLValueReferenceType(PtrTy), 8838 PtrTy, 8839 }; 8840 8841 // non-volatile version 8842 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8843 /*IsAssignmentOperator=*/true); 8844 8845 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8846 VisibleTypeConversionsQuals.hasVolatile(); 8847 if (NeedVolatile) { 8848 // volatile version 8849 ParamTypes[0] = S.Context.getLValueReferenceType( 8850 S.Context.getVolatileType(PtrTy)); 8851 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8852 /*IsAssignmentOperator=*/true); 8853 } 8854 8855 if (!PtrTy.isRestrictQualified() && 8856 VisibleTypeConversionsQuals.hasRestrict()) { 8857 // restrict version 8858 ParamTypes[0] = S.Context.getLValueReferenceType( 8859 S.Context.getRestrictType(PtrTy)); 8860 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8861 /*IsAssignmentOperator=*/true); 8862 8863 if (NeedVolatile) { 8864 // volatile restrict version 8865 ParamTypes[0] = 8866 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8867 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8868 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8869 /*IsAssignmentOperator=*/true); 8870 } 8871 } 8872 } 8873 } 8874 } 8875 8876 // C++ [over.built]p18: 8877 // 8878 // For every triple (L, VQ, R), where L is an arithmetic type, 8879 // VQ is either volatile or empty, and R is a promoted 8880 // arithmetic type, there exist candidate operator functions of 8881 // the form 8882 // 8883 // VQ L& operator=(VQ L&, R); 8884 // VQ L& operator*=(VQ L&, R); 8885 // VQ L& operator/=(VQ L&, R); 8886 // VQ L& operator+=(VQ L&, R); 8887 // VQ L& operator-=(VQ L&, R); 8888 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8889 if (!HasArithmeticOrEnumeralCandidateType) 8890 return; 8891 8892 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8893 for (unsigned Right = FirstPromotedArithmeticType; 8894 Right < LastPromotedArithmeticType; ++Right) { 8895 QualType ParamTypes[2]; 8896 ParamTypes[1] = ArithmeticTypes[Right]; 8897 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8898 S, ArithmeticTypes[Left], Args[0]); 8899 // Add this built-in operator as a candidate (VQ is empty). 8900 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8901 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8902 /*IsAssignmentOperator=*/isEqualOp); 8903 8904 // Add this built-in operator as a candidate (VQ is 'volatile'). 8905 if (VisibleTypeConversionsQuals.hasVolatile()) { 8906 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8907 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8908 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8909 /*IsAssignmentOperator=*/isEqualOp); 8910 } 8911 } 8912 } 8913 8914 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8915 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8916 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8917 QualType ParamTypes[2]; 8918 ParamTypes[1] = Vec2Ty; 8919 // Add this built-in operator as a candidate (VQ is empty). 8920 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8921 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8922 /*IsAssignmentOperator=*/isEqualOp); 8923 8924 // Add this built-in operator as a candidate (VQ is 'volatile'). 8925 if (VisibleTypeConversionsQuals.hasVolatile()) { 8926 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8927 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8928 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8929 /*IsAssignmentOperator=*/isEqualOp); 8930 } 8931 } 8932 } 8933 8934 // C++ [over.built]p22: 8935 // 8936 // For every triple (L, VQ, R), where L is an integral type, VQ 8937 // is either volatile or empty, and R is a promoted integral 8938 // type, there exist candidate operator functions of the form 8939 // 8940 // VQ L& operator%=(VQ L&, R); 8941 // VQ L& operator<<=(VQ L&, R); 8942 // VQ L& operator>>=(VQ L&, R); 8943 // VQ L& operator&=(VQ L&, R); 8944 // VQ L& operator^=(VQ L&, R); 8945 // VQ L& operator|=(VQ L&, R); 8946 void addAssignmentIntegralOverloads() { 8947 if (!HasArithmeticOrEnumeralCandidateType) 8948 return; 8949 8950 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8951 for (unsigned Right = FirstPromotedIntegralType; 8952 Right < LastPromotedIntegralType; ++Right) { 8953 QualType ParamTypes[2]; 8954 ParamTypes[1] = ArithmeticTypes[Right]; 8955 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8956 S, ArithmeticTypes[Left], Args[0]); 8957 // Add this built-in operator as a candidate (VQ is empty). 8958 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8959 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8960 if (VisibleTypeConversionsQuals.hasVolatile()) { 8961 // Add this built-in operator as a candidate (VQ is 'volatile'). 8962 ParamTypes[0] = LeftBaseTy; 8963 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8964 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8965 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8966 } 8967 } 8968 } 8969 } 8970 8971 // C++ [over.operator]p23: 8972 // 8973 // There also exist candidate operator functions of the form 8974 // 8975 // bool operator!(bool); 8976 // bool operator&&(bool, bool); 8977 // bool operator||(bool, bool); 8978 void addExclaimOverload() { 8979 QualType ParamTy = S.Context.BoolTy; 8980 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8981 /*IsAssignmentOperator=*/false, 8982 /*NumContextualBoolArguments=*/1); 8983 } 8984 void addAmpAmpOrPipePipeOverload() { 8985 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8986 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8987 /*IsAssignmentOperator=*/false, 8988 /*NumContextualBoolArguments=*/2); 8989 } 8990 8991 // C++ [over.built]p13: 8992 // 8993 // For every cv-qualified or cv-unqualified object type T there 8994 // exist candidate operator functions of the form 8995 // 8996 // T* operator+(T*, ptrdiff_t); [ABOVE] 8997 // T& operator[](T*, ptrdiff_t); 8998 // T* operator-(T*, ptrdiff_t); [ABOVE] 8999 // T* operator+(ptrdiff_t, T*); [ABOVE] 9000 // T& operator[](ptrdiff_t, T*); 9001 void addSubscriptOverloads() { 9002 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9003 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9004 QualType PointeeType = PtrTy->getPointeeType(); 9005 if (!PointeeType->isObjectType()) 9006 continue; 9007 9008 // T& operator[](T*, ptrdiff_t) 9009 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9010 } 9011 9012 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9013 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9014 QualType PointeeType = PtrTy->getPointeeType(); 9015 if (!PointeeType->isObjectType()) 9016 continue; 9017 9018 // T& operator[](ptrdiff_t, T*) 9019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9020 } 9021 } 9022 9023 // C++ [over.built]p11: 9024 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9025 // C1 is the same type as C2 or is a derived class of C2, T is an object 9026 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9027 // there exist candidate operator functions of the form 9028 // 9029 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9030 // 9031 // where CV12 is the union of CV1 and CV2. 9032 void addArrowStarOverloads() { 9033 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9034 QualType C1Ty = PtrTy; 9035 QualType C1; 9036 QualifierCollector Q1; 9037 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9038 if (!isa<RecordType>(C1)) 9039 continue; 9040 // heuristic to reduce number of builtin candidates in the set. 9041 // Add volatile/restrict version only if there are conversions to a 9042 // volatile/restrict type. 9043 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9044 continue; 9045 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9046 continue; 9047 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9048 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9049 QualType C2 = QualType(mptr->getClass(), 0); 9050 C2 = C2.getUnqualifiedType(); 9051 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9052 break; 9053 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9054 // build CV12 T& 9055 QualType T = mptr->getPointeeType(); 9056 if (!VisibleTypeConversionsQuals.hasVolatile() && 9057 T.isVolatileQualified()) 9058 continue; 9059 if (!VisibleTypeConversionsQuals.hasRestrict() && 9060 T.isRestrictQualified()) 9061 continue; 9062 T = Q1.apply(S.Context, T); 9063 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9064 } 9065 } 9066 } 9067 9068 // Note that we don't consider the first argument, since it has been 9069 // contextually converted to bool long ago. The candidates below are 9070 // therefore added as binary. 9071 // 9072 // C++ [over.built]p25: 9073 // For every type T, where T is a pointer, pointer-to-member, or scoped 9074 // enumeration type, there exist candidate operator functions of the form 9075 // 9076 // T operator?(bool, T, T); 9077 // 9078 void addConditionalOperatorOverloads() { 9079 /// Set of (canonical) types that we've already handled. 9080 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9081 9082 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9083 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9084 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9085 continue; 9086 9087 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9088 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9089 } 9090 9091 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9092 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9093 continue; 9094 9095 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9096 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9097 } 9098 9099 if (S.getLangOpts().CPlusPlus11) { 9100 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9101 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9102 continue; 9103 9104 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9105 continue; 9106 9107 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9108 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9109 } 9110 } 9111 } 9112 } 9113}; 9114 9115} // end anonymous namespace 9116 9117/// AddBuiltinOperatorCandidates - Add the appropriate built-in 9118/// operator overloads to the candidate set (C++ [over.built]), based 9119/// on the operator @p Op and the arguments given. For example, if the 9120/// operator is a binary '+', this routine might add "int 9121/// operator+(int, int)" to cover integer addition. 9122void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9123 SourceLocation OpLoc, 9124 ArrayRef<Expr *> Args, 9125 OverloadCandidateSet &CandidateSet) { 9126 // Find all of the types that the arguments can convert to, but only 9127 // if the operator we're looking at has built-in operator candidates 9128 // that make use of these types. Also record whether we encounter non-record 9129 // candidate types or either arithmetic or enumeral candidate types. 9130 Qualifiers VisibleTypeConversionsQuals; 9131 VisibleTypeConversionsQuals.addConst(); 9132 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9133 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9134 9135 bool HasNonRecordCandidateType = false; 9136 bool HasArithmeticOrEnumeralCandidateType = false; 9137 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9138 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9139 CandidateTypes.emplace_back(*this); 9140 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9141 OpLoc, 9142 true, 9143 (Op == OO_Exclaim || 9144 Op == OO_AmpAmp || 9145 Op == OO_PipePipe), 9146 VisibleTypeConversionsQuals); 9147 HasNonRecordCandidateType = HasNonRecordCandidateType || 9148 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9149 HasArithmeticOrEnumeralCandidateType = 9150 HasArithmeticOrEnumeralCandidateType || 9151 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9152 } 9153 9154 // Exit early when no non-record types have been added to the candidate set 9155 // for any of the arguments to the operator. 9156 // 9157 // We can't exit early for !, ||, or &&, since there we have always have 9158 // 'bool' overloads. 9159 if (!HasNonRecordCandidateType && 9160 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9161 return; 9162 9163 // Setup an object to manage the common state for building overloads. 9164 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9165 VisibleTypeConversionsQuals, 9166 HasArithmeticOrEnumeralCandidateType, 9167 CandidateTypes, CandidateSet); 9168 9169 // Dispatch over the operation to add in only those overloads which apply. 9170 switch (Op) { 9171 case OO_None: 9172 case NUM_OVERLOADED_OPERATORS: 9173 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9173)
; 9174 9175 case OO_New: 9176 case OO_Delete: 9177 case OO_Array_New: 9178 case OO_Array_Delete: 9179 case OO_Call: 9180 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9181)
9181 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9181)
; 9182 9183 case OO_Comma: 9184 case OO_Arrow: 9185 case OO_Coawait: 9186 // C++ [over.match.oper]p3: 9187 // -- For the operator ',', the unary operator '&', the 9188 // operator '->', or the operator 'co_await', the 9189 // built-in candidates set is empty. 9190 break; 9191 9192 case OO_Plus: // '+' is either unary or binary 9193 if (Args.size() == 1) 9194 OpBuilder.addUnaryPlusPointerOverloads(); 9195 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9196 9197 case OO_Minus: // '-' is either unary or binary 9198 if (Args.size() == 1) { 9199 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9200 } else { 9201 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9202 OpBuilder.addGenericBinaryArithmeticOverloads(); 9203 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9204 } 9205 break; 9206 9207 case OO_Star: // '*' is either unary or binary 9208 if (Args.size() == 1) 9209 OpBuilder.addUnaryStarPointerOverloads(); 9210 else { 9211 OpBuilder.addGenericBinaryArithmeticOverloads(); 9212 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9213 } 9214 break; 9215 9216 case OO_Slash: 9217 OpBuilder.addGenericBinaryArithmeticOverloads(); 9218 break; 9219 9220 case OO_PlusPlus: 9221 case OO_MinusMinus: 9222 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9223 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9224 break; 9225 9226 case OO_EqualEqual: 9227 case OO_ExclaimEqual: 9228 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9229 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9230 9231 case OO_Less: 9232 case OO_Greater: 9233 case OO_LessEqual: 9234 case OO_GreaterEqual: 9235 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9236 OpBuilder.addGenericBinaryArithmeticOverloads(); 9237 break; 9238 9239 case OO_Spaceship: 9240 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9241 OpBuilder.addThreeWayArithmeticOverloads(); 9242 break; 9243 9244 case OO_Percent: 9245 case OO_Caret: 9246 case OO_Pipe: 9247 case OO_LessLess: 9248 case OO_GreaterGreater: 9249 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9250 break; 9251 9252 case OO_Amp: // '&' is either unary or binary 9253 if (Args.size() == 1) 9254 // C++ [over.match.oper]p3: 9255 // -- For the operator ',', the unary operator '&', or the 9256 // operator '->', the built-in candidates set is empty. 9257 break; 9258 9259 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9260 break; 9261 9262 case OO_Tilde: 9263 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9264 break; 9265 9266 case OO_Equal: 9267 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9268 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9269 9270 case OO_PlusEqual: 9271 case OO_MinusEqual: 9272 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9273 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 9274 9275 case OO_StarEqual: 9276 case OO_SlashEqual: 9277 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9278 break; 9279 9280 case OO_PercentEqual: 9281 case OO_LessLessEqual: 9282 case OO_GreaterGreaterEqual: 9283 case OO_AmpEqual: 9284 case OO_CaretEqual: 9285 case OO_PipeEqual: 9286 OpBuilder.addAssignmentIntegralOverloads(); 9287 break; 9288 9289 case OO_Exclaim: 9290 OpBuilder.addExclaimOverload(); 9291 break; 9292 9293 case OO_AmpAmp: 9294 case OO_PipePipe: 9295 OpBuilder.addAmpAmpOrPipePipeOverload(); 9296 break; 9297 9298 case OO_Subscript: 9299 OpBuilder.addSubscriptOverloads(); 9300 break; 9301 9302 case OO_ArrowStar: 9303 OpBuilder.addArrowStarOverloads(); 9304 break; 9305 9306 case OO_Conditional: 9307 OpBuilder.addConditionalOperatorOverloads(); 9308 OpBuilder.addGenericBinaryArithmeticOverloads(); 9309 break; 9310 } 9311} 9312 9313/// Add function candidates found via argument-dependent lookup 9314/// to the set of overloading candidates. 9315/// 9316/// This routine performs argument-dependent name lookup based on the 9317/// given function name (which may also be an operator name) and adds 9318/// all of the overload candidates found by ADL to the overload 9319/// candidate set (C++ [basic.lookup.argdep]). 9320void 9321Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9322 SourceLocation Loc, 9323 ArrayRef<Expr *> Args, 9324 TemplateArgumentListInfo *ExplicitTemplateArgs, 9325 OverloadCandidateSet& CandidateSet, 9326 bool PartialOverloading) { 9327 ADLResult Fns; 9328 9329 // FIXME: This approach for uniquing ADL results (and removing 9330 // redundant candidates from the set) relies on pointer-equality, 9331 // which means we need to key off the canonical decl. However, 9332 // always going back to the canonical decl might not get us the 9333 // right set of default arguments. What default arguments are 9334 // we supposed to consider on ADL candidates, anyway? 9335 9336 // FIXME: Pass in the explicit template arguments? 9337 ArgumentDependentLookup(Name, Loc, Args, Fns); 9338 9339 // Erase all of the candidates we already knew about. 9340 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9341 CandEnd = CandidateSet.end(); 9342 Cand != CandEnd; ++Cand) 9343 if (Cand->Function) { 9344 Fns.erase(Cand->Function); 9345 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9346 Fns.erase(FunTmpl); 9347 } 9348 9349 // For each of the ADL candidates we found, add it to the overload 9350 // set. 9351 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9352 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9353 9354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9355 if (ExplicitTemplateArgs) 9356 continue; 9357 9358 AddOverloadCandidate( 9359 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9360 PartialOverloading, /*AllowExplicit=*/true, 9361 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9362 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9363 AddOverloadCandidate( 9364 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9365 /*SuppressUserConversions=*/false, PartialOverloading, 9366 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9367 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9368 } 9369 } else { 9370 auto *FTD = cast<FunctionTemplateDecl>(*I); 9371 AddTemplateOverloadCandidate( 9372 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9373 /*SuppressUserConversions=*/false, PartialOverloading, 9374 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9375 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9376 Context, FTD->getTemplatedDecl())) { 9377 AddTemplateOverloadCandidate( 9378 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9379 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9380 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9381 OverloadCandidateParamOrder::Reversed); 9382 } 9383 } 9384 } 9385} 9386 9387namespace { 9388enum class Comparison { Equal, Better, Worse }; 9389} 9390 9391/// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9392/// overload resolution. 9393/// 9394/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9395/// Cand1's first N enable_if attributes have precisely the same conditions as 9396/// Cand2's first N enable_if attributes (where N = the number of enable_if 9397/// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9398/// 9399/// Note that you can have a pair of candidates such that Cand1's enable_if 9400/// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9401/// worse than Cand1's. 9402static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9403 const FunctionDecl *Cand2) { 9404 // Common case: One (or both) decls don't have enable_if attrs. 9405 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9406 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9407 if (!Cand1Attr || !Cand2Attr) { 9408 if (Cand1Attr == Cand2Attr) 9409 return Comparison::Equal; 9410 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9411 } 9412 9413 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9414 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9415 9416 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9417 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9418 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9419 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9420 9421 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9422 // has fewer enable_if attributes than Cand2, and vice versa. 9423 if (!Cand1A) 9424 return Comparison::Worse; 9425 if (!Cand2A) 9426 return Comparison::Better; 9427 9428 Cand1ID.clear(); 9429 Cand2ID.clear(); 9430 9431 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9432 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9433 if (Cand1ID != Cand2ID) 9434 return Comparison::Worse; 9435 } 9436 9437 return Comparison::Equal; 9438} 9439 9440static Comparison 9441isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9442 const OverloadCandidate &Cand2) { 9443 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9444 !Cand2.Function->isMultiVersion()) 9445 return Comparison::Equal; 9446 9447 // If both are invalid, they are equal. If one of them is invalid, the other 9448 // is better. 9449 if (Cand1.Function->isInvalidDecl()) { 9450 if (Cand2.Function->isInvalidDecl()) 9451 return Comparison::Equal; 9452 return Comparison::Worse; 9453 } 9454 if (Cand2.Function->isInvalidDecl()) 9455 return Comparison::Better; 9456 9457 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9458 // cpu_dispatch, else arbitrarily based on the identifiers. 9459 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9460 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9461 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9462 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9463 9464 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9465 return Comparison::Equal; 9466 9467 if (Cand1CPUDisp && !Cand2CPUDisp) 9468 return Comparison::Better; 9469 if (Cand2CPUDisp && !Cand1CPUDisp) 9470 return Comparison::Worse; 9471 9472 if (Cand1CPUSpec && Cand2CPUSpec) { 9473 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9474 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9475 ? Comparison::Better 9476 : Comparison::Worse; 9477 9478 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9479 FirstDiff = std::mismatch( 9480 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9481 Cand2CPUSpec->cpus_begin(), 9482 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9483 return LHS->getName() == RHS->getName(); 9484 }); 9485 9486 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9488, __PRETTY_FUNCTION__))
9487 "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9488, __PRETTY_FUNCTION__))
9488 "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9488, __PRETTY_FUNCTION__))
; 9489 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9490 ? Comparison::Better 9491 : Comparison::Worse; 9492 } 9493 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9493)
; 9494} 9495 9496/// Compute the type of the implicit object parameter for the given function, 9497/// if any. Returns None if there is no implicit object parameter, and a null 9498/// QualType if there is a 'matches anything' implicit object parameter. 9499static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9500 const FunctionDecl *F) { 9501 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9502 return llvm::None; 9503 9504 auto *M = cast<CXXMethodDecl>(F); 9505 // Static member functions' object parameters match all types. 9506 if (M->isStatic()) 9507 return QualType(); 9508 9509 QualType T = M->getThisObjectType(); 9510 if (M->getRefQualifier() == RQ_RValue) 9511 return Context.getRValueReferenceType(T); 9512 return Context.getLValueReferenceType(T); 9513} 9514 9515static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9516 const FunctionDecl *F2, unsigned NumParams) { 9517 if (declaresSameEntity(F1, F2)) 9518 return true; 9519 9520 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9521 if (First) { 9522 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9523 return *T; 9524 } 9525 assert(I < F->getNumParams())((I < F->getNumParams()) ? static_cast<void> (0) :
__assert_fail ("I < F->getNumParams()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9525, __PRETTY_FUNCTION__))
; 9526 return F->getParamDecl(I++)->getType(); 9527 }; 9528 9529 unsigned I1 = 0, I2 = 0; 9530 for (unsigned I = 0; I != NumParams; ++I) { 9531 QualType T1 = NextParam(F1, I1, I == 0); 9532 QualType T2 = NextParam(F2, I2, I == 0); 9533 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9534 return false; 9535 } 9536 return true; 9537} 9538 9539/// isBetterOverloadCandidate - Determines whether the first overload 9540/// candidate is a better candidate than the second (C++ 13.3.3p1). 9541bool clang::isBetterOverloadCandidate( 9542 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9543 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9544 // Define viable functions to be better candidates than non-viable 9545 // functions. 9546 if (!Cand2.Viable)
1
Assuming field 'Viable' is true
2
Taking false branch
9547 return Cand1.Viable; 9548 else if (!Cand1.Viable)
3
Assuming field 'Viable' is true
4
Taking false branch
9549 return false; 9550 9551 // [CUDA] A function with 'never' preference is marked not viable, therefore 9552 // is never shown up here. The worst preference shown up here is 'wrong side', 9553 // e.g. an H function called by a HD function in device compilation. This is 9554 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9555 // function which is called only by an H function. A deferred diagnostic will 9556 // be triggered if it is emitted. However a wrong-sided function is still 9557 // a viable candidate here. 9558 // 9559 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9560 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9561 // can be emitted, Cand1 is not better than Cand2. This rule should have 9562 // precedence over other rules. 9563 // 9564 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9565 // other rules should be used to determine which is better. This is because 9566 // host/device based overloading resolution is mostly for determining 9567 // viability of a function. If two functions are both viable, other factors 9568 // should take precedence in preference, e.g. the standard-defined preferences 9569 // like argument conversion ranks or enable_if partial-ordering. The 9570 // preference for pass-object-size parameters is probably most similar to a 9571 // type-based-overloading decision and so should take priority. 9572 // 9573 // If other rules cannot determine which is better, CUDA preference will be 9574 // used again to determine which is better. 9575 // 9576 // TODO: Currently IdentifyCUDAPreference does not return correct values 9577 // for functions called in global variable initializers due to missing 9578 // correct context about device/host. Therefore we can only enforce this 9579 // rule when there is a caller. We should enforce this rule for functions 9580 // in global variable initializers once proper context is added. 9581 // 9582 // TODO: We can only enable the hostness based overloading resolution when 9583 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9584 // overloading resolution diagnostics. 9585 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
5
Assuming field 'CUDA' is 0
9586 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9587 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9588 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9589 bool IsCand1ImplicitHD = 9590 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9591 bool IsCand2ImplicitHD = 9592 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9593 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9594 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9595 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)((P1 != Sema::CFP_Never && P2 != Sema::CFP_Never) ? static_cast
<void> (0) : __assert_fail ("P1 != Sema::CFP_Never && P2 != Sema::CFP_Never"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9595, __PRETTY_FUNCTION__))
; 9596 // The implicit HD function may be a function in a system header which 9597 // is forced by pragma. In device compilation, if we prefer HD candidates 9598 // over wrong-sided candidates, overloading resolution may change, which 9599 // may result in non-deferrable diagnostics. As a workaround, we let 9600 // implicit HD candidates take equal preference as wrong-sided candidates. 9601 // This will preserve the overloading resolution. 9602 // TODO: We still need special handling of implicit HD functions since 9603 // they may incur other diagnostics to be deferred. We should make all 9604 // host/device related diagnostics deferrable and remove special handling 9605 // of implicit HD functions. 9606 auto EmitThreshold = 9607 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9608 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9609 ? Sema::CFP_Never 9610 : Sema::CFP_WrongSide; 9611 auto Cand1Emittable = P1 > EmitThreshold; 9612 auto Cand2Emittable = P2 > EmitThreshold; 9613 if (Cand1Emittable && !Cand2Emittable) 9614 return true; 9615 if (!Cand1Emittable && Cand2Emittable) 9616 return false; 9617 } 9618 } 9619 9620 // C++ [over.match.best]p1: 9621 // 9622 // -- if F is a static member function, ICS1(F) is defined such 9623 // that ICS1(F) is neither better nor worse than ICS1(G) for 9624 // any function G, and, symmetrically, ICS1(G) is neither 9625 // better nor worse than ICS1(F). 9626 unsigned StartArg = 0; 9627 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6
Assuming field 'IgnoreObjectArgument' is false
7
Assuming field 'IgnoreObjectArgument' is false
8
Taking false branch
9628 StartArg = 1; 9629 9630 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9631 // We don't allow incompatible pointer conversions in C++. 9632 if (!S.getLangOpts().CPlusPlus) 9633 return ICS.isStandard() && 9634 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9635 9636 // The only ill-formed conversion we allow in C++ is the string literal to 9637 // char* conversion, which is only considered ill-formed after C++11. 9638 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9639 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9640 }; 9641 9642 // Define functions that don't require ill-formed conversions for a given 9643 // argument to be better candidates than functions that do. 9644 unsigned NumArgs = Cand1.Conversions.size(); 9645 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9645, __PRETTY_FUNCTION__))
;
9
Assuming the condition is true
10
'?' condition is true
9646 bool HasBetterConversion = false; 9647 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11
Assuming 'ArgIdx' is >= 'NumArgs'
12
Loop condition is false. Execution continues on line 9657
9648 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9649 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9650 if (Cand1Bad != Cand2Bad) { 9651 if (Cand1Bad) 9652 return false; 9653 HasBetterConversion = true; 9654 } 9655 } 9656 9657 if (HasBetterConversion
12.1
'HasBetterConversion' is false
12.1
'HasBetterConversion' is false
)
13
Taking false branch
9658 return true; 9659 9660 // C++ [over.match.best]p1: 9661 // A viable function F1 is defined to be a better function than another 9662 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9663 // conversion sequence than ICSi(F2), and then... 9664 bool HasWorseConversion = false; 9665 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
14
Loop condition is false. Execution continues on line 9706
9666 switch (CompareImplicitConversionSequences(S, Loc, 9667 Cand1.Conversions[ArgIdx], 9668 Cand2.Conversions[ArgIdx])) { 9669 case ImplicitConversionSequence::Better: 9670 // Cand1 has a better conversion sequence. 9671 HasBetterConversion = true; 9672 break; 9673 9674 case ImplicitConversionSequence::Worse: 9675 if (Cand1.Function && Cand2.Function && 9676 Cand1.isReversed() != Cand2.isReversed() && 9677 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9678 NumArgs)) { 9679 // Work around large-scale breakage caused by considering reversed 9680 // forms of operator== in C++20: 9681 // 9682 // When comparing a function against a reversed function with the same 9683 // parameter types, if we have a better conversion for one argument and 9684 // a worse conversion for the other, the implicit conversion sequences 9685 // are treated as being equally good. 9686 // 9687 // This prevents a comparison function from being considered ambiguous 9688 // with a reversed form that is written in the same way. 9689 // 9690 // We diagnose this as an extension from CreateOverloadedBinOp. 9691 HasWorseConversion = true; 9692 break; 9693 } 9694 9695 // Cand1 can't be better than Cand2. 9696 return false; 9697 9698 case ImplicitConversionSequence::Indistinguishable: 9699 // Do nothing. 9700 break; 9701 } 9702 } 9703 9704 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9705 // ICSj(F2), or, if not that, 9706 if (HasBetterConversion
14.1
'HasBetterConversion' is false
14.1
'HasBetterConversion' is false
&& !HasWorseConversion) 9707 return true; 9708 9709 // -- the context is an initialization by user-defined conversion 9710 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9711 // from the return type of F1 to the destination type (i.e., 9712 // the type of the entity being initialized) is a better 9713 // conversion sequence than the standard conversion sequence 9714 // from the return type of F2 to the destination type. 9715 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
15
Assuming 'Kind' is equal to CSK_InitByUserDefinedConversion
20
Taking true branch
9716 Cand1.Function && Cand2.Function &&
16
Assuming field 'Function' is non-null
17
Assuming field 'Function' is non-null
9717 isa<CXXConversionDecl>(Cand1.Function) &&
18
Assuming field 'Function' is a 'CXXConversionDecl'
9718 isa<CXXConversionDecl>(Cand2.Function)) {
19
Assuming field 'Function' is a 'CXXConversionDecl'
9719 // First check whether we prefer one of the conversion functions over the 9720 // other. This only distinguishes the results in non-standard, extension 9721 // cases such as the conversion from a lambda closure type to a function 9722 // pointer or block. 9723 ImplicitConversionSequence::CompareKind Result = 9724 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9725 if (Result
20.1
'Result' is equal to Indistinguishable
20.1
'Result' is equal to Indistinguishable
== ImplicitConversionSequence::Indistinguishable)
21
Taking true branch
9726 Result = CompareStandardConversionSequences(S, Loc,
22
Calling 'CompareStandardConversionSequences'
9727 Cand1.FinalConversion, 9728 Cand2.FinalConversion); 9729 9730 if (Result != ImplicitConversionSequence::Indistinguishable) 9731 return Result == ImplicitConversionSequence::Better; 9732 9733 // FIXME: Compare kind of reference binding if conversion functions 9734 // convert to a reference type used in direct reference binding, per 9735 // C++14 [over.match.best]p1 section 2 bullet 3. 9736 } 9737 9738 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9739 // as combined with the resolution to CWG issue 243. 9740 // 9741 // When the context is initialization by constructor ([over.match.ctor] or 9742 // either phase of [over.match.list]), a constructor is preferred over 9743 // a conversion function. 9744 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9745 Cand1.Function && Cand2.Function && 9746 isa<CXXConstructorDecl>(Cand1.Function) != 9747 isa<CXXConstructorDecl>(Cand2.Function)) 9748 return isa<CXXConstructorDecl>(Cand1.Function); 9749 9750 // -- F1 is a non-template function and F2 is a function template 9751 // specialization, or, if not that, 9752 bool Cand1IsSpecialization = Cand1.Function && 9753 Cand1.Function->getPrimaryTemplate(); 9754 bool Cand2IsSpecialization = Cand2.Function && 9755 Cand2.Function->getPrimaryTemplate(); 9756 if (Cand1IsSpecialization != Cand2IsSpecialization) 9757 return Cand2IsSpecialization; 9758 9759 // -- F1 and F2 are function template specializations, and the function 9760 // template for F1 is more specialized than the template for F2 9761 // according to the partial ordering rules described in 14.5.5.2, or, 9762 // if not that, 9763 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9764 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9765 Cand1.Function->getPrimaryTemplate(), 9766 Cand2.Function->getPrimaryTemplate(), Loc, 9767 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9768 : TPOC_Call, 9769 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9770 Cand1.isReversed() ^ Cand2.isReversed())) 9771 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9772 } 9773 9774 // -— F1 and F2 are non-template functions with the same 9775 // parameter-type-lists, and F1 is more constrained than F2 [...], 9776 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9777 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9778 Cand2.Function->hasPrototype()) { 9779 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9780 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9781 if (PT1->getNumParams() == PT2->getNumParams() && 9782 PT1->isVariadic() == PT2->isVariadic() && 9783 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9784 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9785 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9786 if (RC1 && RC2) { 9787 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9788 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9789 {RC2}, AtLeastAsConstrained1) || 9790 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9791 {RC1}, AtLeastAsConstrained2)) 9792 return false; 9793 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9794 return AtLeastAsConstrained1; 9795 } else if (RC1 || RC2) { 9796 return RC1 != nullptr; 9797 } 9798 } 9799 } 9800 9801 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9802 // class B of D, and for all arguments the corresponding parameters of 9803 // F1 and F2 have the same type. 9804 // FIXME: Implement the "all parameters have the same type" check. 9805 bool Cand1IsInherited = 9806 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9807 bool Cand2IsInherited = 9808 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9809 if (Cand1IsInherited != Cand2IsInherited) 9810 return Cand2IsInherited; 9811 else if (Cand1IsInherited) { 9812 assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9812, __PRETTY_FUNCTION__))
; 9813 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9814 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9815 if (Cand1Class->isDerivedFrom(Cand2Class)) 9816 return true; 9817 if (Cand2Class->isDerivedFrom(Cand1Class)) 9818 return false; 9819 // Inherited from sibling base classes: still ambiguous. 9820 } 9821 9822 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9823 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9824 // with reversed order of parameters and F1 is not 9825 // 9826 // We rank reversed + different operator as worse than just reversed, but 9827 // that comparison can never happen, because we only consider reversing for 9828 // the maximally-rewritten operator (== or <=>). 9829 if (Cand1.RewriteKind != Cand2.RewriteKind) 9830 return Cand1.RewriteKind < Cand2.RewriteKind; 9831 9832 // Check C++17 tie-breakers for deduction guides. 9833 { 9834 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9835 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9836 if (Guide1 && Guide2) { 9837 // -- F1 is generated from a deduction-guide and F2 is not 9838 if (Guide1->isImplicit() != Guide2->isImplicit()) 9839 return Guide2->isImplicit(); 9840 9841 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9842 if (Guide1->isCopyDeductionCandidate()) 9843 return true; 9844 } 9845 } 9846 9847 // Check for enable_if value-based overload resolution. 9848 if (Cand1.Function && Cand2.Function) { 9849 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9850 if (Cmp != Comparison::Equal) 9851 return Cmp == Comparison::Better; 9852 } 9853 9854 bool HasPS1 = Cand1.Function != nullptr && 9855 functionHasPassObjectSizeParams(Cand1.Function); 9856 bool HasPS2 = Cand2.Function != nullptr && 9857 functionHasPassObjectSizeParams(Cand2.Function); 9858 if (HasPS1 != HasPS2 && HasPS1) 9859 return true; 9860 9861 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9862 if (MV == Comparison::Better) 9863 return true; 9864 if (MV == Comparison::Worse) 9865 return false; 9866 9867 // If other rules cannot determine which is better, CUDA preference is used 9868 // to determine which is better. 9869 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9870 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9871 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9872 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9873 } 9874 9875 return false; 9876} 9877 9878/// Determine whether two declarations are "equivalent" for the purposes of 9879/// name lookup and overload resolution. This applies when the same internal/no 9880/// linkage entity is defined by two modules (probably by textually including 9881/// the same header). In such a case, we don't consider the declarations to 9882/// declare the same entity, but we also don't want lookups with both 9883/// declarations visible to be ambiguous in some cases (this happens when using 9884/// a modularized libstdc++). 9885bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9886 const NamedDecl *B) { 9887 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9888 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9889 if (!VA || !VB) 9890 return false; 9891 9892 // The declarations must be declaring the same name as an internal linkage 9893 // entity in different modules. 9894 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9895 VB->getDeclContext()->getRedeclContext()) || 9896 getOwningModule(VA) == getOwningModule(VB) || 9897 VA->isExternallyVisible() || VB->isExternallyVisible()) 9898 return false; 9899 9900 // Check that the declarations appear to be equivalent. 9901 // 9902 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9903 // For constants and functions, we should check the initializer or body is 9904 // the same. For non-constant variables, we shouldn't allow it at all. 9905 if (Context.hasSameType(VA->getType(), VB->getType())) 9906 return true; 9907 9908 // Enum constants within unnamed enumerations will have different types, but 9909 // may still be similar enough to be interchangeable for our purposes. 9910 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9911 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9912 // Only handle anonymous enums. If the enumerations were named and 9913 // equivalent, they would have been merged to the same type. 9914 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9915 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9916 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9917 !Context.hasSameType(EnumA->getIntegerType(), 9918 EnumB->getIntegerType())) 9919 return false; 9920 // Allow this only if the value is the same for both enumerators. 9921 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9922 } 9923 } 9924 9925 // Nothing else is sufficiently similar. 9926 return false; 9927} 9928 9929void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9930 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9931 assert(D && "Unknown declaration")((D && "Unknown declaration") ? static_cast<void>
(0) : __assert_fail ("D && \"Unknown declaration\"",
"/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 9931, __PRETTY_FUNCTION__))
; 9932 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9933 9934 Module *M = getOwningModule(D); 9935 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9936 << !M << (M ? M->getFullModuleName() : ""); 9937 9938 for (auto *E : Equiv) { 9939 Module *M = getOwningModule(E); 9940 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9941 << !M << (M ? M->getFullModuleName() : ""); 9942 } 9943} 9944 9945/// Computes the best viable function (C++ 13.3.3) 9946/// within an overload candidate set. 9947/// 9948/// \param Loc The location of the function name (or operator symbol) for 9949/// which overload resolution occurs. 9950/// 9951/// \param Best If overload resolution was successful or found a deleted 9952/// function, \p Best points to the candidate function found. 9953/// 9954/// \returns The result of overload resolution. 9955OverloadingResult 9956OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9957 iterator &Best) { 9958 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9959 std::transform(begin(), end(), std::back_inserter(Candidates), 9960 [](OverloadCandidate &Cand) { return &Cand; }); 9961 9962 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9963 // are accepted by both clang and NVCC. However, during a particular 9964 // compilation mode only one call variant is viable. We need to 9965 // exclude non-viable overload candidates from consideration based 9966 // only on their host/device attributes. Specifically, if one 9967 // candidate call is WrongSide and the other is SameSide, we ignore 9968 // the WrongSide candidate. 9969 // We only need to remove wrong-sided candidates here if 9970 // -fgpu-exclude-wrong-side-overloads is off. When 9971 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 9972 // uniformly in isBetterOverloadCandidate. 9973 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 9974 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9975 bool ContainsSameSideCandidate = 9976 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9977 // Check viable function only. 9978 return Cand->Viable && Cand->Function && 9979 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9980 Sema::CFP_SameSide; 9981 }); 9982 if (ContainsSameSideCandidate) { 9983 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9984 // Check viable function only to avoid unnecessary data copying/moving. 9985 return Cand->Viable && Cand->Function && 9986 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9987 Sema::CFP_WrongSide; 9988 }; 9989 llvm::erase_if(Candidates, IsWrongSideCandidate); 9990 } 9991 } 9992 9993 // Find the best viable function. 9994 Best = end(); 9995 for (auto *Cand : Candidates) { 9996 Cand->Best = false; 9997 if (Cand->Viable) 9998 if (Best == end() || 9999 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10000 Best = Cand; 10001 } 10002 10003 // If we didn't find any viable functions, abort. 10004 if (Best == end()) 10005 return OR_No_Viable_Function; 10006 10007 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10008 10009 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10010 PendingBest.push_back(&*Best); 10011 Best->Best = true; 10012 10013 // Make sure that this function is better than every other viable 10014 // function. If not, we have an ambiguity. 10015 while (!PendingBest.empty()) { 10016 auto *Curr = PendingBest.pop_back_val(); 10017 for (auto *Cand : Candidates) { 10018 if (Cand->Viable && !Cand->Best && 10019 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10020 PendingBest.push_back(Cand); 10021 Cand->Best = true; 10022 10023 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10024 Curr->Function)) 10025 EquivalentCands.push_back(Cand->Function); 10026 else 10027 Best = end(); 10028 } 10029 } 10030 } 10031 10032 // If we found more than one best candidate, this is ambiguous. 10033 if (Best == end()) 10034 return OR_Ambiguous; 10035 10036 // Best is the best viable function. 10037 if (Best->Function && Best->Function->isDeleted()) 10038 return OR_Deleted; 10039 10040 if (!EquivalentCands.empty()) 10041 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10042 EquivalentCands); 10043 10044 return OR_Success; 10045} 10046 10047namespace { 10048 10049enum OverloadCandidateKind { 10050 oc_function, 10051 oc_method, 10052 oc_reversed_binary_operator, 10053 oc_constructor, 10054 oc_implicit_default_constructor, 10055 oc_implicit_copy_constructor, 10056 oc_implicit_move_constructor, 10057 oc_implicit_copy_assignment, 10058 oc_implicit_move_assignment, 10059 oc_implicit_equality_comparison, 10060 oc_inherited_constructor 10061}; 10062 10063enum OverloadCandidateSelect { 10064 ocs_non_template, 10065 ocs_template, 10066 ocs_described_template, 10067}; 10068 10069static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10070ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10071 OverloadCandidateRewriteKind CRK, 10072 std::string &Description) { 10073 10074 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10075 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10076 isTemplate = true; 10077 Description = S.getTemplateArgumentBindingsText( 10078 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10079 } 10080 10081 OverloadCandidateSelect Select = [&]() { 10082 if (!Description.empty()) 10083 return ocs_described_template; 10084 return isTemplate ? ocs_template : ocs_non_template; 10085 }(); 10086 10087 OverloadCandidateKind Kind = [&]() { 10088 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10089 return oc_implicit_equality_comparison; 10090 10091 if (CRK & CRK_Reversed) 10092 return oc_reversed_binary_operator; 10093 10094 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10095 if (!Ctor->isImplicit()) { 10096 if (isa<ConstructorUsingShadowDecl>(Found)) 10097 return oc_inherited_constructor; 10098 else 10099 return oc_constructor; 10100 } 10101 10102 if (Ctor->isDefaultConstructor()) 10103 return oc_implicit_default_constructor; 10104 10105 if (Ctor->isMoveConstructor()) 10106 return oc_implicit_move_constructor; 10107 10108 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10109, __PRETTY_FUNCTION__))
10109 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10109, __PRETTY_FUNCTION__))
; 10110 return oc_implicit_copy_constructor; 10111 } 10112 10113 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10114 // This actually gets spelled 'candidate function' for now, but 10115 // it doesn't hurt to split it out. 10116 if (!Meth->isImplicit()) 10117 return oc_method; 10118 10119 if (Meth->isMoveAssignmentOperator()) 10120 return oc_implicit_move_assignment; 10121 10122 if (Meth->isCopyAssignmentOperator()) 10123 return oc_implicit_copy_assignment; 10124 10125 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10125, __PRETTY_FUNCTION__))
; 10126 return oc_method; 10127 } 10128 10129 return oc_function; 10130 }(); 10131 10132 return std::make_pair(Kind, Select); 10133} 10134 10135void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10136 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10137 // set. 10138 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10139 S.Diag(FoundDecl->getLocation(), 10140 diag::note_ovl_candidate_inherited_constructor) 10141 << Shadow->getNominatedBaseClass(); 10142} 10143 10144} // end anonymous namespace 10145 10146static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10147 const FunctionDecl *FD) { 10148 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10149 bool AlwaysTrue; 10150 if (EnableIf->getCond()->isValueDependent() || 10151 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10152 return false; 10153 if (!AlwaysTrue) 10154 return false; 10155 } 10156 return true; 10157} 10158 10159/// Returns true if we can take the address of the function. 10160/// 10161/// \param Complain - If true, we'll emit a diagnostic 10162/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10163/// we in overload resolution? 10164/// \param Loc - The location of the statement we're complaining about. Ignored 10165/// if we're not complaining, or if we're in overload resolution. 10166static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10167 bool Complain, 10168 bool InOverloadResolution, 10169 SourceLocation Loc) { 10170 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10171 if (Complain) { 10172 if (InOverloadResolution) 10173 S.Diag(FD->getBeginLoc(), 10174 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10175 else 10176 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10177 } 10178 return false; 10179 } 10180 10181 if (FD->getTrailingRequiresClause()) { 10182 ConstraintSatisfaction Satisfaction; 10183 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10184 return false; 10185 if (!Satisfaction.IsSatisfied) { 10186 if (Complain) { 10187 if (InOverloadResolution) 10188 S.Diag(FD->getBeginLoc(), 10189 diag::note_ovl_candidate_unsatisfied_constraints); 10190 else 10191 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10192 << FD; 10193 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10194 } 10195 return false; 10196 } 10197 } 10198 10199 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10200 return P->hasAttr<PassObjectSizeAttr>(); 10201 }); 10202 if (I == FD->param_end()) 10203 return true; 10204 10205 if (Complain) { 10206 // Add one to ParamNo because it's user-facing 10207 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10208 if (InOverloadResolution) 10209 S.Diag(FD->getLocation(), 10210 diag::note_ovl_candidate_has_pass_object_size_params) 10211 << ParamNo; 10212 else 10213 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10214 << FD << ParamNo; 10215 } 10216 return false; 10217} 10218 10219static bool checkAddressOfCandidateIsAvailable(Sema &S, 10220 const FunctionDecl *FD) { 10221 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10222 /*InOverloadResolution=*/true, 10223 /*Loc=*/SourceLocation()); 10224} 10225 10226bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10227 bool Complain, 10228 SourceLocation Loc) { 10229 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10230 /*InOverloadResolution=*/false, 10231 Loc); 10232} 10233 10234// Don't print candidates other than the one that matches the calling 10235// convention of the call operator, since that is guaranteed to exist. 10236static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10237 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10238 10239 if (!ConvD) 10240 return false; 10241 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10242 if (!RD->isLambda()) 10243 return false; 10244 10245 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10246 CallingConv CallOpCC = 10247 CallOp->getType()->getAs<FunctionType>()->getCallConv(); 10248 QualType ConvRTy = ConvD->getType()->getAs<FunctionType>()->getReturnType(); 10249 CallingConv ConvToCC = 10250 ConvRTy->getPointeeType()->getAs<FunctionType>()->getCallConv(); 10251 10252 return ConvToCC != CallOpCC; 10253} 10254 10255// Notes the location of an overload candidate. 10256void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10257 OverloadCandidateRewriteKind RewriteKind, 10258 QualType DestType, bool TakingAddress) { 10259 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10260 return; 10261 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10262 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10263 return; 10264 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10265 return; 10266 10267 std::string FnDesc; 10268 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10269 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10270 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10271 << (unsigned)KSPair.first << (unsigned)KSPair.second 10272 << Fn << FnDesc; 10273 10274 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10275 Diag(Fn->getLocation(), PD); 10276 MaybeEmitInheritedConstructorNote(*this, Found); 10277} 10278 10279static void 10280MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10281 // Perhaps the ambiguity was caused by two atomic constraints that are 10282 // 'identical' but not equivalent: 10283 // 10284 // void foo() requires (sizeof(T) > 4) { } // #1 10285 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10286 // 10287 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10288 // #2 to subsume #1, but these constraint are not considered equivalent 10289 // according to the subsumption rules because they are not the same 10290 // source-level construct. This behavior is quite confusing and we should try 10291 // to help the user figure out what happened. 10292 10293 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10294 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10295 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10296 if (!I->Function) 10297 continue; 10298 SmallVector<const Expr *, 3> AC; 10299 if (auto *Template = I->Function->getPrimaryTemplate()) 10300 Template->getAssociatedConstraints(AC); 10301 else 10302 I->Function->getAssociatedConstraints(AC); 10303 if (AC.empty()) 10304 continue; 10305 if (FirstCand == nullptr) { 10306 FirstCand = I->Function; 10307 FirstAC = AC; 10308 } else if (SecondCand == nullptr) { 10309 SecondCand = I->Function; 10310 SecondAC = AC; 10311 } else { 10312 // We have more than one pair of constrained functions - this check is 10313 // expensive and we'd rather not try to diagnose it. 10314 return; 10315 } 10316 } 10317 if (!SecondCand) 10318 return; 10319 // The diagnostic can only happen if there are associated constraints on 10320 // both sides (there needs to be some identical atomic constraint). 10321 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10322 SecondCand, SecondAC)) 10323 // Just show the user one diagnostic, they'll probably figure it out 10324 // from here. 10325 return; 10326} 10327 10328// Notes the location of all overload candidates designated through 10329// OverloadedExpr 10330void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10331 bool TakingAddress) { 10332 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10332, __PRETTY_FUNCTION__))
; 10333 10334 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10335 OverloadExpr *OvlExpr = Ovl.Expression; 10336 10337 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10338 IEnd = OvlExpr->decls_end(); 10339 I != IEnd; ++I) { 10340 if (FunctionTemplateDecl *FunTmpl = 10341 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10342 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10343 TakingAddress); 10344 } else if (FunctionDecl *Fun 10345 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10346 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10347 } 10348 } 10349} 10350 10351/// Diagnoses an ambiguous conversion. The partial diagnostic is the 10352/// "lead" diagnostic; it will be given two arguments, the source and 10353/// target types of the conversion. 10354void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10355 Sema &S, 10356 SourceLocation CaretLoc, 10357 const PartialDiagnostic &PDiag) const { 10358 S.Diag(CaretLoc, PDiag) 10359 << Ambiguous.getFromType() << Ambiguous.getToType(); 10360 unsigned CandsShown = 0; 10361 AmbiguousConversionSequence::const_iterator I, E; 10362 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10363 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10364 break; 10365 ++CandsShown; 10366 S.NoteOverloadCandidate(I->first, I->second); 10367 } 10368 S.Diags.overloadCandidatesShown(CandsShown); 10369 if (I != E) 10370 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10371} 10372 10373static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10374 unsigned I, bool TakingCandidateAddress) { 10375 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10376 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10376, __PRETTY_FUNCTION__))
; 10377 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10377, __PRETTY_FUNCTION__))
; 10378 FunctionDecl *Fn = Cand->Function; 10379 10380 // There's a conversion slot for the object argument if this is a 10381 // non-constructor method. Note that 'I' corresponds the 10382 // conversion-slot index. 10383 bool isObjectArgument = false; 10384 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10385 if (I == 0) 10386 isObjectArgument = true; 10387 else 10388 I--; 10389 } 10390 10391 std::string FnDesc; 10392 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10393 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10394 FnDesc); 10395 10396 Expr *FromExpr = Conv.Bad.FromExpr; 10397 QualType FromTy = Conv.Bad.getFromType(); 10398 QualType ToTy = Conv.Bad.getToType(); 10399 10400 if (FromTy == S.Context.OverloadTy) { 10401 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10401, __PRETTY_FUNCTION__))
; 10402 Expr *E = FromExpr->IgnoreParens(); 10403 if (isa<UnaryOperator>(E)) 10404 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10405 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10406 10407 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10408 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10409 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10410 << Name << I + 1; 10411 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10412 return; 10413 } 10414 10415 // Do some hand-waving analysis to see if the non-viability is due 10416 // to a qualifier mismatch. 10417 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10418 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10419 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10420 CToTy = RT->getPointeeType(); 10421 else { 10422 // TODO: detect and diagnose the full richness of const mismatches. 10423 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10424 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10425 CFromTy = FromPT->getPointeeType(); 10426 CToTy = ToPT->getPointeeType(); 10427 } 10428 } 10429 10430 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10431 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10432 Qualifiers FromQs = CFromTy.getQualifiers(); 10433 Qualifiers ToQs = CToTy.getQualifiers(); 10434 10435 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10436 if (isObjectArgument) 10437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10438 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10439 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10440 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10441 else 10442 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10443 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10444 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10445 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10446 << ToTy->isReferenceType() << I + 1; 10447 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10448 return; 10449 } 10450 10451 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10452 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10453 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10454 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10455 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10456 << (unsigned)isObjectArgument << I + 1; 10457 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10458 return; 10459 } 10460 10461 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10463 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10464 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10465 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10466 << (unsigned)isObjectArgument << I + 1; 10467 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10468 return; 10469 } 10470 10471 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10473 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10474 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10475 << FromQs.hasUnaligned() << I + 1; 10476 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10477 return; 10478 } 10479 10480 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10481 assert(CVR && "expected qualifiers mismatch")((CVR && "expected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"expected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10481, __PRETTY_FUNCTION__))
; 10482 10483 if (isObjectArgument) { 10484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10485 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10486 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10487 << (CVR - 1); 10488 } else { 10489 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10490 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10491 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10492 << (CVR - 1) << I + 1; 10493 } 10494 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10495 return; 10496 } 10497 10498 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10499 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10500 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10501 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10502 << (unsigned)isObjectArgument << I + 1 10503 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10504 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10505 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10506 return; 10507 } 10508 10509 // Special diagnostic for failure to convert an initializer list, since 10510 // telling the user that it has type void is not useful. 10511 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10513 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10514 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10515 << ToTy << (unsigned)isObjectArgument << I + 1; 10516 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10517 return; 10518 } 10519 10520 // Diagnose references or pointers to incomplete types differently, 10521 // since it's far from impossible that the incompleteness triggered 10522 // the failure. 10523 QualType TempFromTy = FromTy.getNonReferenceType(); 10524 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10525 TempFromTy = PTy->getPointeeType(); 10526 if (TempFromTy->isIncompleteType()) { 10527 // Emit the generic diagnostic and, optionally, add the hints to it. 10528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10529 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10531 << ToTy << (unsigned)isObjectArgument << I + 1 10532 << (unsigned)(Cand->Fix.Kind); 10533 10534 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10535 return; 10536 } 10537 10538 // Diagnose base -> derived pointer conversions. 10539 unsigned BaseToDerivedConversion = 0; 10540 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10541 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10542 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10543 FromPtrTy->getPointeeType()) && 10544 !FromPtrTy->getPointeeType()->isIncompleteType() && 10545 !ToPtrTy->getPointeeType()->isIncompleteType() && 10546 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10547 FromPtrTy->getPointeeType())) 10548 BaseToDerivedConversion = 1; 10549 } 10550 } else if (const ObjCObjectPointerType *FromPtrTy 10551 = FromTy->getAs<ObjCObjectPointerType>()) { 10552 if (const ObjCObjectPointerType *ToPtrTy 10553 = ToTy->getAs<ObjCObjectPointerType>()) 10554 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10555 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10556 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10557 FromPtrTy->getPointeeType()) && 10558 FromIface->isSuperClassOf(ToIface)) 10559 BaseToDerivedConversion = 2; 10560 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10561 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10562 !FromTy->isIncompleteType() && 10563 !ToRefTy->getPointeeType()->isIncompleteType() && 10564 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10565 BaseToDerivedConversion = 3; 10566 } 10567 } 10568 10569 if (BaseToDerivedConversion) { 10570 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10571 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10572 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10573 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10574 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10575 return; 10576 } 10577 10578 if (isa<ObjCObjectPointerType>(CFromTy) && 10579 isa<PointerType>(CToTy)) { 10580 Qualifiers FromQs = CFromTy.getQualifiers(); 10581 Qualifiers ToQs = CToTy.getQualifiers(); 10582 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10583 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10584 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10585 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10586 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10587 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10588 return; 10589 } 10590 } 10591 10592 if (TakingCandidateAddress && 10593 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10594 return; 10595 10596 // Emit the generic diagnostic and, optionally, add the hints to it. 10597 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10598 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10599 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10600 << ToTy << (unsigned)isObjectArgument << I + 1 10601 << (unsigned)(Cand->Fix.Kind); 10602 10603 // If we can fix the conversion, suggest the FixIts. 10604 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10605 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10606 FDiag << *HI; 10607 S.Diag(Fn->getLocation(), FDiag); 10608 10609 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10610} 10611 10612/// Additional arity mismatch diagnosis specific to a function overload 10613/// candidates. This is not covered by the more general DiagnoseArityMismatch() 10614/// over a candidate in any candidate set. 10615static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10616 unsigned NumArgs) { 10617 FunctionDecl *Fn = Cand->Function; 10618 unsigned MinParams = Fn->getMinRequiredArguments(); 10619 10620 // With invalid overloaded operators, it's possible that we think we 10621 // have an arity mismatch when in fact it looks like we have the 10622 // right number of arguments, because only overloaded operators have 10623 // the weird behavior of overloading member and non-member functions. 10624 // Just don't report anything. 10625 if (Fn->isInvalidDecl() && 10626 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10627 return true; 10628 10629 if (NumArgs < MinParams) { 10630 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10632, __PRETTY_FUNCTION__))
10631 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10632, __PRETTY_FUNCTION__))
10632 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10632, __PRETTY_FUNCTION__))
; 10633 } else { 10634 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10636, __PRETTY_FUNCTION__))
10635 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10636, __PRETTY_FUNCTION__))
10636 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10636, __PRETTY_FUNCTION__))
; 10637 } 10638 10639 return false; 10640} 10641 10642/// General arity mismatch diagnosis over a candidate in a candidate set. 10643static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10644 unsigned NumFormalArgs) { 10645 assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
10646 "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
10647 " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
10648 " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
; 10649 10650 FunctionDecl *Fn = cast<FunctionDecl>(D); 10651 10652 // TODO: treat calls to a missing default constructor as a special case 10653 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10654 unsigned MinParams = Fn->getMinRequiredArguments(); 10655 10656 // at least / at most / exactly 10657 unsigned mode, modeCount; 10658 if (NumFormalArgs < MinParams) { 10659 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10660 FnTy->isTemplateVariadic()) 10661 mode = 0; // "at least" 10662 else 10663 mode = 2; // "exactly" 10664 modeCount = MinParams; 10665 } else { 10666 if (MinParams != FnTy->getNumParams()) 10667 mode = 1; // "at most" 10668 else 10669 mode = 2; // "exactly" 10670 modeCount = FnTy->getNumParams(); 10671 } 10672 10673 std::string Description; 10674 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10675 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10676 10677 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10678 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10679 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10680 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10681 else 10682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10683 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10684 << Description << mode << modeCount << NumFormalArgs; 10685 10686 MaybeEmitInheritedConstructorNote(S, Found); 10687} 10688 10689/// Arity mismatch diagnosis specific to a function overload candidate. 10690static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10691 unsigned NumFormalArgs) { 10692 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10693 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10694} 10695 10696static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10697 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10698 return TD; 10699 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10700)
10700 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10700)
; 10701} 10702 10703/// Diagnose a failed template-argument deduction. 10704static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10705 DeductionFailureInfo &DeductionFailure, 10706 unsigned NumArgs, 10707 bool TakingCandidateAddress) { 10708 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10709 NamedDecl *ParamD; 10710 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10711 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10712 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10713 switch (DeductionFailure.Result) { 10714 case Sema::TDK_Success: 10715 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10715)
; 10716 10717 case Sema::TDK_Incomplete: { 10718 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10718, __PRETTY_FUNCTION__))
; 10719 S.Diag(Templated->getLocation(), 10720 diag::note_ovl_candidate_incomplete_deduction) 10721 << ParamD->getDeclName(); 10722 MaybeEmitInheritedConstructorNote(S, Found); 10723 return; 10724 } 10725 10726 case Sema::TDK_IncompletePack: { 10727 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10727, __PRETTY_FUNCTION__))
; 10728 S.Diag(Templated->getLocation(), 10729 diag::note_ovl_candidate_incomplete_deduction_pack) 10730 << ParamD->getDeclName() 10731 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10732 << *DeductionFailure.getFirstArg(); 10733 MaybeEmitInheritedConstructorNote(S, Found); 10734 return; 10735 } 10736 10737 case Sema::TDK_Underqualified: { 10738 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10738, __PRETTY_FUNCTION__))
; 10739 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10740 10741 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10742 10743 // Param will have been canonicalized, but it should just be a 10744 // qualified version of ParamD, so move the qualifiers to that. 10745 QualifierCollector Qs; 10746 Qs.strip(Param); 10747 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10748 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10748, __PRETTY_FUNCTION__))
; 10749 10750 // Arg has also been canonicalized, but there's nothing we can do 10751 // about that. It also doesn't matter as much, because it won't 10752 // have any template parameters in it (because deduction isn't 10753 // done on dependent types). 10754 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10755 10756 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10757 << ParamD->getDeclName() << Arg << NonCanonParam; 10758 MaybeEmitInheritedConstructorNote(S, Found); 10759 return; 10760 } 10761 10762 case Sema::TDK_Inconsistent: { 10763 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10763, __PRETTY_FUNCTION__))
; 10764 int which = 0; 10765 if (isa<TemplateTypeParmDecl>(ParamD)) 10766 which = 0; 10767 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10768 // Deduction might have failed because we deduced arguments of two 10769 // different types for a non-type template parameter. 10770 // FIXME: Use a different TDK value for this. 10771 QualType T1 = 10772 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10773 QualType T2 = 10774 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10775 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10776 S.Diag(Templated->getLocation(), 10777 diag::note_ovl_candidate_inconsistent_deduction_types) 10778 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10779 << *DeductionFailure.getSecondArg() << T2; 10780 MaybeEmitInheritedConstructorNote(S, Found); 10781 return; 10782 } 10783 10784 which = 1; 10785 } else { 10786 which = 2; 10787 } 10788 10789 // Tweak the diagnostic if the problem is that we deduced packs of 10790 // different arities. We'll print the actual packs anyway in case that 10791 // includes additional useful information. 10792 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10793 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10794 DeductionFailure.getFirstArg()->pack_size() != 10795 DeductionFailure.getSecondArg()->pack_size()) { 10796 which = 3; 10797 } 10798 10799 S.Diag(Templated->getLocation(), 10800 diag::note_ovl_candidate_inconsistent_deduction) 10801 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10802 << *DeductionFailure.getSecondArg(); 10803 MaybeEmitInheritedConstructorNote(S, Found); 10804 return; 10805 } 10806 10807 case Sema::TDK_InvalidExplicitArguments: 10808 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 10808, __PRETTY_FUNCTION__))
; 10809 if (ParamD->getDeclName()) 10810 S.Diag(Templated->getLocation(), 10811 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10812 << ParamD->getDeclName(); 10813 else { 10814 int index = 0; 10815 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10816 index = TTP->getIndex(); 10817 else if (NonTypeTemplateParmDecl *NTTP 10818 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10819 index = NTTP->getIndex(); 10820 else 10821 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10822 S.Diag(Templated->getLocation(), 10823 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10824 << (index + 1); 10825 } 10826 MaybeEmitInheritedConstructorNote(S, Found); 10827 return; 10828 10829 case Sema::TDK_ConstraintsNotSatisfied: { 10830 // Format the template argument list into the argument string. 10831 SmallString<128> TemplateArgString; 10832 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10833 TemplateArgString = " "; 10834 TemplateArgString += S.getTemplateArgumentBindingsText( 10835 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10836 if (TemplateArgString.size() == 1) 10837 TemplateArgString.clear(); 10838 S.Diag(Templated->getLocation(), 10839 diag::note_ovl_candidate_unsatisfied_constraints) 10840 << TemplateArgString; 10841 10842 S.DiagnoseUnsatisfiedConstraint( 10843 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10844 return; 10845 } 10846 case Sema::TDK_TooManyArguments: 10847 case Sema::TDK_TooFewArguments: 10848 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10849 return; 10850 10851 case Sema::TDK_InstantiationDepth: 10852 S.Diag(Templated->getLocation(), 10853 diag::note_ovl_candidate_instantiation_depth); 10854 MaybeEmitInheritedConstructorNote(S, Found); 10855 return; 10856 10857 case Sema::TDK_SubstitutionFailure: { 10858 // Format the template argument list into the argument string. 10859 SmallString<128> TemplateArgString; 10860 if (TemplateArgumentList *Args = 10861 DeductionFailure.getTemplateArgumentList()) { 10862 TemplateArgString = " "; 10863 TemplateArgString += S.getTemplateArgumentBindingsText( 10864 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10865 if (TemplateArgString.size() == 1) 10866 TemplateArgString.clear(); 10867 } 10868 10869 // If this candidate was disabled by enable_if, say so. 10870 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10871 if (PDiag && PDiag->second.getDiagID() == 10872 diag::err_typename_nested_not_found_enable_if) { 10873 // FIXME: Use the source range of the condition, and the fully-qualified 10874 // name of the enable_if template. These are both present in PDiag. 10875 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10876 << "'enable_if'" << TemplateArgString; 10877 return; 10878 } 10879 10880 // We found a specific requirement that disabled the enable_if. 10881 if (PDiag && PDiag->second.getDiagID() == 10882 diag::err_typename_nested_not_found_requirement) { 10883 S.Diag(Templated->getLocation(), 10884 diag::note_ovl_candidate_disabled_by_requirement) 10885 << PDiag->second.getStringArg(0) << TemplateArgString; 10886 return; 10887 } 10888 10889 // Format the SFINAE diagnostic into the argument string. 10890 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10891 // formatted message in another diagnostic. 10892 SmallString<128> SFINAEArgString; 10893 SourceRange R; 10894 if (PDiag) { 10895 SFINAEArgString = ": "; 10896 R = SourceRange(PDiag->first, PDiag->first); 10897 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10898 } 10899 10900 S.Diag(Templated->getLocation(), 10901 diag::note_ovl_candidate_substitution_failure) 10902 << TemplateArgString << SFINAEArgString << R; 10903 MaybeEmitInheritedConstructorNote(S, Found); 10904 return; 10905 } 10906 10907 case Sema::TDK_DeducedMismatch: 10908 case Sema::TDK_DeducedMismatchNested: { 10909 // Format the template argument list into the argument string. 10910 SmallString<128> TemplateArgString; 10911 if (TemplateArgumentList *Args = 10912 DeductionFailure.getTemplateArgumentList()) { 10913 TemplateArgString = " "; 10914 TemplateArgString += S.getTemplateArgumentBindingsText( 10915 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10916 if (TemplateArgString.size() == 1) 10917 TemplateArgString.clear(); 10918 } 10919 10920 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10921 << (*DeductionFailure.getCallArgIndex() + 1) 10922 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10923 << TemplateArgString 10924 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10925 break; 10926 } 10927 10928 case Sema::TDK_NonDeducedMismatch: { 10929 // FIXME: Provide a source location to indicate what we couldn't match. 10930 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10931 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10932 if (FirstTA.getKind() == TemplateArgument::Template && 10933 SecondTA.getKind() == TemplateArgument::Template) { 10934 TemplateName FirstTN = FirstTA.getAsTemplate(); 10935 TemplateName SecondTN = SecondTA.getAsTemplate(); 10936 if (FirstTN.getKind() == TemplateName::Template && 10937 SecondTN.getKind() == TemplateName::Template) { 10938 if (FirstTN.getAsTemplateDecl()->getName() == 10939 SecondTN.getAsTemplateDecl()->getName()) { 10940 // FIXME: This fixes a bad diagnostic where both templates are named 10941 // the same. This particular case is a bit difficult since: 10942 // 1) It is passed as a string to the diagnostic printer. 10943 // 2) The diagnostic printer only attempts to find a better 10944 // name for types, not decls. 10945 // Ideally, this should folded into the diagnostic printer. 10946 S.Diag(Templated->getLocation(), 10947 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10948 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10949 return; 10950 } 10951 } 10952 } 10953 10954 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10955 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10956 return; 10957 10958 // FIXME: For generic lambda parameters, check if the function is a lambda 10959 // call operator, and if so, emit a prettier and more informative 10960 // diagnostic that mentions 'auto' and lambda in addition to 10961 // (or instead of?) the canonical template type parameters. 10962 S.Diag(Templated->getLocation(), 10963 diag::note_ovl_candidate_non_deduced_mismatch) 10964 << FirstTA << SecondTA; 10965 return; 10966 } 10967 // TODO: diagnose these individually, then kill off 10968 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10969 case Sema::TDK_MiscellaneousDeductionFailure: 10970 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10971 MaybeEmitInheritedConstructorNote(S, Found); 10972 return; 10973 case Sema::TDK_CUDATargetMismatch: 10974 S.Diag(Templated->getLocation(), 10975 diag::note_cuda_ovl_candidate_target_mismatch); 10976 return; 10977 } 10978} 10979 10980/// Diagnose a failed template-argument deduction, for function calls. 10981static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10982 unsigned NumArgs, 10983 bool TakingCandidateAddress) { 10984 unsigned TDK = Cand->DeductionFailure.Result; 10985 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10986 if (CheckArityMismatch(S, Cand, NumArgs)) 10987 return; 10988 } 10989 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10990 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10991} 10992 10993/// CUDA: diagnose an invalid call across targets. 10994static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10995 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10996 FunctionDecl *Callee = Cand->Function; 10997 10998 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10999 CalleeTarget = S.IdentifyCUDATarget(Callee); 11000 11001 std::string FnDesc; 11002 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11003 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11004 Cand->getRewriteKind(), FnDesc); 11005 11006 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11007 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11008 << FnDesc /* Ignored */ 11009 << CalleeTarget << CallerTarget; 11010 11011 // This could be an implicit constructor for which we could not infer the 11012 // target due to a collsion. Diagnose that case. 11013 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11014 if (Meth != nullptr && Meth->isImplicit()) { 11015 CXXRecordDecl *ParentClass = Meth->getParent(); 11016 Sema::CXXSpecialMember CSM; 11017 11018 switch (FnKindPair.first) { 11019 default: 11020 return; 11021 case oc_implicit_default_constructor: 11022 CSM = Sema::CXXDefaultConstructor; 11023 break; 11024 case oc_implicit_copy_constructor: 11025 CSM = Sema::CXXCopyConstructor; 11026 break; 11027 case oc_implicit_move_constructor: 11028 CSM = Sema::CXXMoveConstructor; 11029 break; 11030 case oc_implicit_copy_assignment: 11031 CSM = Sema::CXXCopyAssignment; 11032 break; 11033 case oc_implicit_move_assignment: 11034 CSM = Sema::CXXMoveAssignment; 11035 break; 11036 }; 11037 11038 bool ConstRHS = false; 11039 if (Meth->getNumParams()) { 11040 if (const ReferenceType *RT = 11041 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11042 ConstRHS = RT->getPointeeType().isConstQualified(); 11043 } 11044 } 11045 11046 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11047 /* ConstRHS */ ConstRHS, 11048 /* Diagnose */ true); 11049 } 11050} 11051 11052static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11053 FunctionDecl *Callee = Cand->Function; 11054 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11055 11056 S.Diag(Callee->getLocation(), 11057 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11058 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11059} 11060 11061static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11062 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11063 assert(ES.isExplicit() && "not an explicit candidate")((ES.isExplicit() && "not an explicit candidate") ? static_cast
<void> (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11063, __PRETTY_FUNCTION__))
; 11064 11065 unsigned Kind; 11066 switch (Cand->Function->getDeclKind()) { 11067 case Decl::Kind::CXXConstructor: 11068 Kind = 0; 11069 break; 11070 case Decl::Kind::CXXConversion: 11071 Kind = 1; 11072 break; 11073 case Decl::Kind::CXXDeductionGuide: 11074 Kind = Cand->Function->isImplicit() ? 0 : 2; 11075 break; 11076 default: 11077 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11077)
; 11078 } 11079 11080 // Note the location of the first (in-class) declaration; a redeclaration 11081 // (particularly an out-of-class definition) will typically lack the 11082 // 'explicit' specifier. 11083 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11084 FunctionDecl *First = Cand->Function->getFirstDecl(); 11085 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11086 First = Pattern->getFirstDecl(); 11087 11088 S.Diag(First->getLocation(), 11089 diag::note_ovl_candidate_explicit) 11090 << Kind << (ES.getExpr() ? 1 : 0) 11091 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11092} 11093 11094static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 11095 FunctionDecl *Callee = Cand->Function; 11096 11097 S.Diag(Callee->getLocation(), 11098 diag::note_ovl_candidate_disabled_by_extension) 11099 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 11100} 11101 11102/// Generates a 'note' diagnostic for an overload candidate. We've 11103/// already generated a primary error at the call site. 11104/// 11105/// It really does need to be a single diagnostic with its caret 11106/// pointed at the candidate declaration. Yes, this creates some 11107/// major challenges of technical writing. Yes, this makes pointing 11108/// out problems with specific arguments quite awkward. It's still 11109/// better than generating twenty screens of text for every failed 11110/// overload. 11111/// 11112/// It would be great to be able to express per-candidate problems 11113/// more richly for those diagnostic clients that cared, but we'd 11114/// still have to be just as careful with the default diagnostics. 11115/// \param CtorDestAS Addr space of object being constructed (for ctor 11116/// candidates only). 11117static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11118 unsigned NumArgs, 11119 bool TakingCandidateAddress, 11120 LangAS CtorDestAS = LangAS::Default) { 11121 FunctionDecl *Fn = Cand->Function; 11122 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11123 return; 11124 11125 // Note deleted candidates, but only if they're viable. 11126 if (Cand->Viable) { 11127 if (Fn->isDeleted()) { 11128 std::string FnDesc; 11129 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11130 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11131 Cand->getRewriteKind(), FnDesc); 11132 11133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11134 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11135 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11136 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11137 return; 11138 } 11139 11140 // We don't really have anything else to say about viable candidates. 11141 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11142 return; 11143 } 11144 11145 switch (Cand->FailureKind) { 11146 case ovl_fail_too_many_arguments: 11147 case ovl_fail_too_few_arguments: 11148 return DiagnoseArityMismatch(S, Cand, NumArgs); 11149 11150 case ovl_fail_bad_deduction: 11151 return DiagnoseBadDeduction(S, Cand, NumArgs, 11152 TakingCandidateAddress); 11153 11154 case ovl_fail_illegal_constructor: { 11155 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11156 << (Fn->getPrimaryTemplate() ? 1 : 0); 11157 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11158 return; 11159 } 11160 11161 case ovl_fail_object_addrspace_mismatch: { 11162 Qualifiers QualsForPrinting; 11163 QualsForPrinting.setAddressSpace(CtorDestAS); 11164 S.Diag(Fn->getLocation(), 11165 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11166 << QualsForPrinting; 11167 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11168 return; 11169 } 11170 11171 case ovl_fail_trivial_conversion: 11172 case ovl_fail_bad_final_conversion: 11173 case ovl_fail_final_conversion_not_exact: 11174 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11175 11176 case ovl_fail_bad_conversion: { 11177 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11178 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11179 if (Cand->Conversions[I].isBad()) 11180 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11181 11182 // FIXME: this currently happens when we're called from SemaInit 11183 // when user-conversion overload fails. Figure out how to handle 11184 // those conditions and diagnose them well. 11185 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11186 } 11187 11188 case ovl_fail_bad_target: 11189 return DiagnoseBadTarget(S, Cand); 11190 11191 case ovl_fail_enable_if: 11192 return DiagnoseFailedEnableIfAttr(S, Cand); 11193 11194 case ovl_fail_explicit: 11195 return DiagnoseFailedExplicitSpec(S, Cand); 11196 11197 case ovl_fail_ext_disabled: 11198 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11199 11200 case ovl_fail_inhctor_slice: 11201 // It's generally not interesting to note copy/move constructors here. 11202 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11203 return; 11204 S.Diag(Fn->getLocation(), 11205 diag::note_ovl_candidate_inherited_constructor_slice) 11206 << (Fn->getPrimaryTemplate() ? 1 : 0) 11207 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11208 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11209 return; 11210 11211 case ovl_fail_addr_not_available: { 11212 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11213 (void)Available; 11214 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11214, __PRETTY_FUNCTION__))
; 11215 break; 11216 } 11217 case ovl_non_default_multiversion_function: 11218 // Do nothing, these should simply be ignored. 11219 break; 11220 11221 case ovl_fail_constraints_not_satisfied: { 11222 std::string FnDesc; 11223 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11224 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11225 Cand->getRewriteKind(), FnDesc); 11226 11227 S.Diag(Fn->getLocation(), 11228 diag::note_ovl_candidate_constraints_not_satisfied) 11229 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11230 << FnDesc /* Ignored */; 11231 ConstraintSatisfaction Satisfaction; 11232 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11233 break; 11234 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11235 } 11236 } 11237} 11238 11239static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11240 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11241 return; 11242 11243 // Desugar the type of the surrogate down to a function type, 11244 // retaining as many typedefs as possible while still showing 11245 // the function type (and, therefore, its parameter types). 11246 QualType FnType = Cand->Surrogate->getConversionType(); 11247 bool isLValueReference = false; 11248 bool isRValueReference = false; 11249 bool isPointer = false; 11250 if (const LValueReferenceType *FnTypeRef = 11251 FnType->getAs<LValueReferenceType>()) { 11252 FnType = FnTypeRef->getPointeeType(); 11253 isLValueReference = true; 11254 } else if (const RValueReferenceType *FnTypeRef = 11255 FnType->getAs<RValueReferenceType>()) { 11256 FnType = FnTypeRef->getPointeeType(); 11257 isRValueReference = true; 11258 } 11259 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11260 FnType = FnTypePtr->getPointeeType(); 11261 isPointer = true; 11262 } 11263 // Desugar down to a function type. 11264 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11265 // Reconstruct the pointer/reference as appropriate. 11266 if (isPointer) FnType = S.Context.getPointerType(FnType); 11267 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11268 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11269 11270 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11271 << FnType; 11272} 11273 11274static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11275 SourceLocation OpLoc, 11276 OverloadCandidate *Cand) { 11277 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11277, __PRETTY_FUNCTION__))
; 11278 std::string TypeStr("operator"); 11279 TypeStr += Opc; 11280 TypeStr += "("; 11281 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11282 if (Cand->Conversions.size() == 1) { 11283 TypeStr += ")"; 11284 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11285 } else { 11286 TypeStr += ", "; 11287 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11288 TypeStr += ")"; 11289 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11290 } 11291} 11292 11293static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11294 OverloadCandidate *Cand) { 11295 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11296 if (ICS.isBad()) break; // all meaningless after first invalid 11297 if (!ICS.isAmbiguous()) continue; 11298 11299 ICS.DiagnoseAmbiguousConversion( 11300 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11301 } 11302} 11303 11304static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11305 if (Cand->Function) 11306 return Cand->Function->getLocation(); 11307 if (Cand->IsSurrogate) 11308 return Cand->Surrogate->getLocation(); 11309 return SourceLocation(); 11310} 11311 11312static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11313 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11314 case Sema::TDK_Success: 11315 case Sema::TDK_NonDependentConversionFailure: 11316 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11316)
; 11317 11318 case Sema::TDK_Invalid: 11319 case Sema::TDK_Incomplete: 11320 case Sema::TDK_IncompletePack: 11321 return 1; 11322 11323 case Sema::TDK_Underqualified: 11324 case Sema::TDK_Inconsistent: 11325 return 2; 11326 11327 case Sema::TDK_SubstitutionFailure: 11328 case Sema::TDK_DeducedMismatch: 11329 case Sema::TDK_ConstraintsNotSatisfied: 11330 case Sema::TDK_DeducedMismatchNested: 11331 case Sema::TDK_NonDeducedMismatch: 11332 case Sema::TDK_MiscellaneousDeductionFailure: 11333 case Sema::TDK_CUDATargetMismatch: 11334 return 3; 11335 11336 case Sema::TDK_InstantiationDepth: 11337 return 4; 11338 11339 case Sema::TDK_InvalidExplicitArguments: 11340 return 5; 11341 11342 case Sema::TDK_TooManyArguments: 11343 case Sema::TDK_TooFewArguments: 11344 return 6; 11345 } 11346 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11346)
; 11347} 11348 11349namespace { 11350struct CompareOverloadCandidatesForDisplay { 11351 Sema &S; 11352 SourceLocation Loc; 11353 size_t NumArgs; 11354 OverloadCandidateSet::CandidateSetKind CSK; 11355 11356 CompareOverloadCandidatesForDisplay( 11357 Sema &S, SourceLocation Loc, size_t NArgs, 11358 OverloadCandidateSet::CandidateSetKind CSK) 11359 : S(S), NumArgs(NArgs), CSK(CSK) {} 11360 11361 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11362 // If there are too many or too few arguments, that's the high-order bit we 11363 // want to sort by, even if the immediate failure kind was something else. 11364 if (C->FailureKind == ovl_fail_too_many_arguments || 11365 C->FailureKind == ovl_fail_too_few_arguments) 11366 return static_cast<OverloadFailureKind>(C->FailureKind); 11367 11368 if (C->Function) { 11369 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11370 return ovl_fail_too_many_arguments; 11371 if (NumArgs < C->Function->getMinRequiredArguments()) 11372 return ovl_fail_too_few_arguments; 11373 } 11374 11375 return static_cast<OverloadFailureKind>(C->FailureKind); 11376 } 11377 11378 bool operator()(const OverloadCandidate *L, 11379 const OverloadCandidate *R) { 11380 // Fast-path this check. 11381 if (L == R) return false; 11382 11383 // Order first by viability. 11384 if (L->Viable) { 11385 if (!R->Viable) return true; 11386 11387 // TODO: introduce a tri-valued comparison for overload 11388 // candidates. Would be more worthwhile if we had a sort 11389 // that could exploit it. 11390 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11391 return true; 11392 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11393 return false; 11394 } else if (R->Viable) 11395 return false; 11396 11397 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11397, __PRETTY_FUNCTION__))
; 11398 11399 // Criteria by which we can sort non-viable candidates: 11400 if (!L->Viable) { 11401 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11402 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11403 11404 // 1. Arity mismatches come after other candidates. 11405 if (LFailureKind == ovl_fail_too_many_arguments || 11406 LFailureKind == ovl_fail_too_few_arguments) { 11407 if (RFailureKind == ovl_fail_too_many_arguments || 11408 RFailureKind == ovl_fail_too_few_arguments) { 11409 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11410 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11411 if (LDist == RDist) { 11412 if (LFailureKind == RFailureKind) 11413 // Sort non-surrogates before surrogates. 11414 return !L->IsSurrogate && R->IsSurrogate; 11415 // Sort candidates requiring fewer parameters than there were 11416 // arguments given after candidates requiring more parameters 11417 // than there were arguments given. 11418 return LFailureKind == ovl_fail_too_many_arguments; 11419 } 11420 return LDist < RDist; 11421 } 11422 return false; 11423 } 11424 if (RFailureKind == ovl_fail_too_many_arguments || 11425 RFailureKind == ovl_fail_too_few_arguments) 11426 return true; 11427 11428 // 2. Bad conversions come first and are ordered by the number 11429 // of bad conversions and quality of good conversions. 11430 if (LFailureKind == ovl_fail_bad_conversion) { 11431 if (RFailureKind != ovl_fail_bad_conversion) 11432 return true; 11433 11434 // The conversion that can be fixed with a smaller number of changes, 11435 // comes first. 11436 unsigned numLFixes = L->Fix.NumConversionsFixed; 11437 unsigned numRFixes = R->Fix.NumConversionsFixed; 11438 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; 11439 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; 11440 if (numLFixes != numRFixes) { 11441 return numLFixes < numRFixes; 11442 } 11443 11444 // If there's any ordering between the defined conversions... 11445 // FIXME: this might not be transitive. 11446 assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast
<void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11446, __PRETTY_FUNCTION__))
; 11447 11448 int leftBetter = 0; 11449 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11450 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11451 switch (CompareImplicitConversionSequences(S, Loc, 11452 L->Conversions[I], 11453 R->Conversions[I])) { 11454 case ImplicitConversionSequence::Better: 11455 leftBetter++; 11456 break; 11457 11458 case ImplicitConversionSequence::Worse: 11459 leftBetter--; 11460 break; 11461 11462 case ImplicitConversionSequence::Indistinguishable: 11463 break; 11464 } 11465 } 11466 if (leftBetter > 0) return true; 11467 if (leftBetter < 0) return false; 11468 11469 } else if (RFailureKind == ovl_fail_bad_conversion) 11470 return false; 11471 11472 if (LFailureKind == ovl_fail_bad_deduction) { 11473 if (RFailureKind != ovl_fail_bad_deduction) 11474 return true; 11475 11476 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11477 return RankDeductionFailure(L->DeductionFailure) 11478 < RankDeductionFailure(R->DeductionFailure); 11479 } else if (RFailureKind == ovl_fail_bad_deduction) 11480 return false; 11481 11482 // TODO: others? 11483 } 11484 11485 // Sort everything else by location. 11486 SourceLocation LLoc = GetLocationForCandidate(L); 11487 SourceLocation RLoc = GetLocationForCandidate(R); 11488 11489 // Put candidates without locations (e.g. builtins) at the end. 11490 if (LLoc.isInvalid()) return false; 11491 if (RLoc.isInvalid()) return true; 11492 11493 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11494 } 11495}; 11496} 11497 11498/// CompleteNonViableCandidate - Normally, overload resolution only 11499/// computes up to the first bad conversion. Produces the FixIt set if 11500/// possible. 11501static void 11502CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11503 ArrayRef<Expr *> Args, 11504 OverloadCandidateSet::CandidateSetKind CSK) { 11505 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11505, __PRETTY_FUNCTION__))
; 11506 11507 // Don't do anything on failures other than bad conversion. 11508 if (Cand->FailureKind != ovl_fail_bad_conversion) 11509 return; 11510 11511 // We only want the FixIts if all the arguments can be corrected. 11512 bool Unfixable = false; 11513 // Use a implicit copy initialization to check conversion fixes. 11514 Cand->Fix.setConversionChecker(TryCopyInitialization); 11515 11516 // Attempt to fix the bad conversion. 11517 unsigned ConvCount = Cand->Conversions.size(); 11518 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11519 ++ConvIdx) { 11520 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11520, __PRETTY_FUNCTION__))
; 11521 if (Cand->Conversions[ConvIdx].isInitialized() && 11522 Cand->Conversions[ConvIdx].isBad()) { 11523 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11524 break; 11525 } 11526 } 11527 11528 // FIXME: this should probably be preserved from the overload 11529 // operation somehow. 11530 bool SuppressUserConversions = false; 11531 11532 unsigned ConvIdx = 0; 11533 unsigned ArgIdx = 0; 11534 ArrayRef<QualType> ParamTypes; 11535 bool Reversed = Cand->isReversed(); 11536 11537 if (Cand->IsSurrogate) { 11538 QualType ConvType 11539 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11540 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11541 ConvType = ConvPtrType->getPointeeType(); 11542 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11543 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11544 ConvIdx = 1; 11545 } else if (Cand->Function) { 11546 ParamTypes = 11547 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11548 if (isa<CXXMethodDecl>(Cand->Function) && 11549 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11550 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11551 ConvIdx = 1; 11552 if (CSK == OverloadCandidateSet::CSK_Operator && 11553 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11554 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11555 ArgIdx = 1; 11556 } 11557 } else { 11558 // Builtin operator. 11559 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11559, __PRETTY_FUNCTION__))
; 11560 ParamTypes = Cand->BuiltinParamTypes; 11561 } 11562 11563 // Fill in the rest of the conversions. 11564 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11565 ConvIdx != ConvCount; 11566 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11567 assert(ArgIdx < Args.size() && "no argument for this arg conversion")((ArgIdx < Args.size() && "no argument for this arg conversion"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11567, __PRETTY_FUNCTION__))
; 11568 if (Cand->Conversions[ConvIdx].isInitialized()) { 11569 // We've already checked this conversion. 11570 } else if (ParamIdx < ParamTypes.size()) { 11571 if (ParamTypes[ParamIdx]->isDependentType()) 11572 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11573 Args[ArgIdx]->getType()); 11574 else { 11575 Cand->Conversions[ConvIdx] = 11576 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11577 SuppressUserConversions, 11578 /*InOverloadResolution=*/true, 11579 /*AllowObjCWritebackConversion=*/ 11580 S.getLangOpts().ObjCAutoRefCount); 11581 // Store the FixIt in the candidate if it exists. 11582 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11583 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11584 } 11585 } else 11586 Cand->Conversions[ConvIdx].setEllipsis(); 11587 } 11588} 11589 11590SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11591 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11592 SourceLocation OpLoc, 11593 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11594 // Sort the candidates by viability and position. Sorting directly would 11595 // be prohibitive, so we make a set of pointers and sort those. 11596 SmallVector<OverloadCandidate*, 32> Cands; 11597 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11598 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11599 if (!Filter(*Cand)) 11600 continue; 11601 switch (OCD) { 11602 case OCD_AllCandidates: 11603 if (!Cand->Viable) { 11604 if (!Cand->Function && !Cand->IsSurrogate) { 11605 // This a non-viable builtin candidate. We do not, in general, 11606 // want to list every possible builtin candidate. 11607 continue; 11608 } 11609 CompleteNonViableCandidate(S, Cand, Args, Kind); 11610 } 11611 break; 11612 11613 case OCD_ViableCandidates: 11614 if (!Cand->Viable) 11615 continue; 11616 break; 11617 11618 case OCD_AmbiguousCandidates: 11619 if (!Cand->Best) 11620 continue; 11621 break; 11622 } 11623 11624 Cands.push_back(Cand); 11625 } 11626 11627 llvm::stable_sort( 11628 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11629 11630 return Cands; 11631} 11632 11633bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11634 SourceLocation OpLoc) { 11635 bool DeferHint = false; 11636 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11637 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11638 // host device candidates. 11639 auto WrongSidedCands = 11640 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11641 return (Cand.Viable == false && 11642 Cand.FailureKind == ovl_fail_bad_target) || 11643 (Cand.Function->template hasAttr<CUDAHostAttr>() && 11644 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11645 }); 11646 DeferHint = !WrongSidedCands.empty(); 11647 } 11648 return DeferHint; 11649} 11650 11651/// When overload resolution fails, prints diagnostic messages containing the 11652/// candidates in the candidate set. 11653void OverloadCandidateSet::NoteCandidates( 11654 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11655 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11656 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11657 11658 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11659 11660 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11661 11662 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11663 11664 if (OCD == OCD_AmbiguousCandidates) 11665 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11666} 11667 11668void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11669 ArrayRef<OverloadCandidate *> Cands, 11670 StringRef Opc, SourceLocation OpLoc) { 11671 bool ReportedAmbiguousConversions = false; 11672 11673 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11674 unsigned CandsShown = 0; 11675 auto I = Cands.begin(), E = Cands.end(); 11676 for (; I != E; ++I) { 11677 OverloadCandidate *Cand = *I; 11678 11679 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11680 ShowOverloads == Ovl_Best) { 11681 break; 11682 } 11683 ++CandsShown; 11684 11685 if (Cand->Function) 11686 NoteFunctionCandidate(S, Cand, Args.size(), 11687 /*TakingCandidateAddress=*/false, DestAS); 11688 else if (Cand->IsSurrogate) 11689 NoteSurrogateCandidate(S, Cand); 11690 else { 11691 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11692, __PRETTY_FUNCTION__))
11692 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11692, __PRETTY_FUNCTION__))
; 11693 // Generally we only see ambiguities including viable builtin 11694 // operators if overload resolution got screwed up by an 11695 // ambiguous user-defined conversion. 11696 // 11697 // FIXME: It's quite possible for different conversions to see 11698 // different ambiguities, though. 11699 if (!ReportedAmbiguousConversions) { 11700 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11701 ReportedAmbiguousConversions = true; 11702 } 11703 11704 // If this is a viable builtin, print it. 11705 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11706 } 11707 } 11708 11709 // Inform S.Diags that we've shown an overload set with N elements. This may 11710 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11711 S.Diags.overloadCandidatesShown(CandsShown); 11712 11713 if (I != E) 11714 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11715 shouldDeferDiags(S, Args, OpLoc)) 11716 << int(E - I); 11717} 11718 11719static SourceLocation 11720GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11721 return Cand->Specialization ? Cand->Specialization->getLocation() 11722 : SourceLocation(); 11723} 11724 11725namespace { 11726struct CompareTemplateSpecCandidatesForDisplay { 11727 Sema &S; 11728 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11729 11730 bool operator()(const TemplateSpecCandidate *L, 11731 const TemplateSpecCandidate *R) { 11732 // Fast-path this check. 11733 if (L == R) 11734 return false; 11735 11736 // Assuming that both candidates are not matches... 11737 11738 // Sort by the ranking of deduction failures. 11739 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11740 return RankDeductionFailure(L->DeductionFailure) < 11741 RankDeductionFailure(R->DeductionFailure); 11742 11743 // Sort everything else by location. 11744 SourceLocation LLoc = GetLocationForCandidate(L); 11745 SourceLocation RLoc = GetLocationForCandidate(R); 11746 11747 // Put candidates without locations (e.g. builtins) at the end. 11748 if (LLoc.isInvalid()) 11749 return false; 11750 if (RLoc.isInvalid()) 11751 return true; 11752 11753 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11754 } 11755}; 11756} 11757 11758/// Diagnose a template argument deduction failure. 11759/// We are treating these failures as overload failures due to bad 11760/// deductions. 11761void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11762 bool ForTakingAddress) { 11763 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11764 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11765} 11766 11767void TemplateSpecCandidateSet::destroyCandidates() { 11768 for (iterator i = begin(), e = end(); i != e; ++i) { 11769 i->DeductionFailure.Destroy(); 11770 } 11771} 11772 11773void TemplateSpecCandidateSet::clear() { 11774 destroyCandidates(); 11775 Candidates.clear(); 11776} 11777 11778/// NoteCandidates - When no template specialization match is found, prints 11779/// diagnostic messages containing the non-matching specializations that form 11780/// the candidate set. 11781/// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11782/// OCD == OCD_AllCandidates and Cand->Viable == false. 11783void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11784 // Sort the candidates by position (assuming no candidate is a match). 11785 // Sorting directly would be prohibitive, so we make a set of pointers 11786 // and sort those. 11787 SmallVector<TemplateSpecCandidate *, 32> Cands; 11788 Cands.reserve(size()); 11789 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11790 if (Cand->Specialization) 11791 Cands.push_back(Cand); 11792 // Otherwise, this is a non-matching builtin candidate. We do not, 11793 // in general, want to list every possible builtin candidate. 11794 } 11795 11796 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11797 11798 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11799 // for generalization purposes (?). 11800 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11801 11802 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11803 unsigned CandsShown = 0; 11804 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11805 TemplateSpecCandidate *Cand = *I; 11806 11807 // Set an arbitrary limit on the number of candidates we'll spam 11808 // the user with. FIXME: This limit should depend on details of the 11809 // candidate list. 11810 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11811 break; 11812 ++CandsShown; 11813 11814 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11815, __PRETTY_FUNCTION__))
11815 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 11815, __PRETTY_FUNCTION__))
; 11816 Cand->NoteDeductionFailure(S, ForTakingAddress); 11817 } 11818 11819 if (I != E) 11820 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11821} 11822 11823// [PossiblyAFunctionType] --> [Return] 11824// NonFunctionType --> NonFunctionType 11825// R (A) --> R(A) 11826// R (*)(A) --> R (A) 11827// R (&)(A) --> R (A) 11828// R (S::*)(A) --> R (A) 11829QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11830 QualType Ret = PossiblyAFunctionType; 11831 if (const PointerType *ToTypePtr = 11832 PossiblyAFunctionType->getAs<PointerType>()) 11833 Ret = ToTypePtr->getPointeeType(); 11834 else if (const ReferenceType *ToTypeRef = 11835 PossiblyAFunctionType->getAs<ReferenceType>()) 11836 Ret = ToTypeRef->getPointeeType(); 11837 else if (const MemberPointerType *MemTypePtr = 11838 PossiblyAFunctionType->getAs<MemberPointerType>()) 11839 Ret = MemTypePtr->getPointeeType(); 11840 Ret = 11841 Context.getCanonicalType(Ret).getUnqualifiedType(); 11842 return Ret; 11843} 11844 11845static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11846 bool Complain = true) { 11847 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11848 S.DeduceReturnType(FD, Loc, Complain)) 11849 return true; 11850 11851 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11852 if (S.getLangOpts().CPlusPlus17 && 11853 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11854 !S.ResolveExceptionSpec(Loc, FPT)) 11855 return true; 11856 11857 return false; 11858} 11859 11860namespace { 11861// A helper class to help with address of function resolution 11862// - allows us to avoid passing around all those ugly parameters 11863class AddressOfFunctionResolver { 11864 Sema& S; 11865 Expr* SourceExpr; 11866 const QualType& TargetType; 11867 QualType TargetFunctionType; // Extracted function type from target type 11868 11869 bool Complain; 11870 //DeclAccessPair& ResultFunctionAccessPair; 11871 ASTContext& Context; 11872 11873 bool TargetTypeIsNonStaticMemberFunction; 11874 bool FoundNonTemplateFunction; 11875 bool StaticMemberFunctionFromBoundPointer; 11876 bool HasComplained; 11877 11878 OverloadExpr::FindResult OvlExprInfo; 11879 OverloadExpr *OvlExpr; 11880 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11881 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11882 TemplateSpecCandidateSet FailedCandidates; 11883 11884public: 11885 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11886 const QualType &TargetType, bool Complain) 11887 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11888 Complain(Complain), Context(S.getASTContext()), 11889 TargetTypeIsNonStaticMemberFunction( 11890 !!TargetType->getAs<MemberPointerType>()), 11891 FoundNonTemplateFunction(false), 11892 StaticMemberFunctionFromBoundPointer(false), 11893 HasComplained(false), 11894 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11895 OvlExpr(OvlExprInfo.Expression), 11896 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11897 ExtractUnqualifiedFunctionTypeFromTargetType(); 11898 11899 if (TargetFunctionType->isFunctionType()) { 11900 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11901 if (!UME->isImplicitAccess() && 11902 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11903 StaticMemberFunctionFromBoundPointer = true; 11904 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11905 DeclAccessPair dap; 11906 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11907 OvlExpr, false, &dap)) { 11908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11909 if (!Method->isStatic()) { 11910 // If the target type is a non-function type and the function found 11911 // is a non-static member function, pretend as if that was the 11912 // target, it's the only possible type to end up with. 11913 TargetTypeIsNonStaticMemberFunction = true; 11914 11915 // And skip adding the function if its not in the proper form. 11916 // We'll diagnose this due to an empty set of functions. 11917 if (!OvlExprInfo.HasFormOfMemberPointer) 11918 return; 11919 } 11920 11921 Matches.push_back(std::make_pair(dap, Fn)); 11922 } 11923 return; 11924 } 11925 11926 if (OvlExpr->hasExplicitTemplateArgs()) 11927 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11928 11929 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11930 // C++ [over.over]p4: 11931 // If more than one function is selected, [...] 11932 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11933 if (FoundNonTemplateFunction) 11934 EliminateAllTemplateMatches(); 11935 else 11936 EliminateAllExceptMostSpecializedTemplate(); 11937 } 11938 } 11939 11940 if (S.getLangOpts().CUDA && Matches.size() > 1) 11941 EliminateSuboptimalCudaMatches(); 11942 } 11943 11944 bool hasComplained() const { return HasComplained; } 11945 11946private: 11947 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11948 QualType Discard; 11949 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11950 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11951 } 11952 11953 /// \return true if A is considered a better overload candidate for the 11954 /// desired type than B. 11955 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11956 // If A doesn't have exactly the correct type, we don't want to classify it 11957 // as "better" than anything else. This way, the user is required to 11958 // disambiguate for us if there are multiple candidates and no exact match. 11959 return candidateHasExactlyCorrectType(A) && 11960 (!candidateHasExactlyCorrectType(B) || 11961 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11962 } 11963 11964 /// \return true if we were able to eliminate all but one overload candidate, 11965 /// false otherwise. 11966 bool eliminiateSuboptimalOverloadCandidates() { 11967 // Same algorithm as overload resolution -- one pass to pick the "best", 11968 // another pass to be sure that nothing is better than the best. 11969 auto Best = Matches.begin(); 11970 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11971 if (isBetterCandidate(I->second, Best->second)) 11972 Best = I; 11973 11974 const FunctionDecl *BestFn = Best->second; 11975 auto IsBestOrInferiorToBest = [this, BestFn]( 11976 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11977 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11978 }; 11979 11980 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11981 // option, so we can potentially give the user a better error 11982 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11983 return false; 11984 Matches[0] = *Best; 11985 Matches.resize(1); 11986 return true; 11987 } 11988 11989 bool isTargetTypeAFunction() const { 11990 return TargetFunctionType->isFunctionType(); 11991 } 11992 11993 // [ToType] [Return] 11994 11995 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11996 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11997 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11998 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11999 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12000 } 12001 12002 // return true if any matching specializations were found 12003 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12004 const DeclAccessPair& CurAccessFunPair) { 12005 if (CXXMethodDecl *Method 12006 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12007 // Skip non-static function templates when converting to pointer, and 12008 // static when converting to member pointer. 12009 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12010 return false; 12011 } 12012 else if (TargetTypeIsNonStaticMemberFunction) 12013 return false; 12014 12015 // C++ [over.over]p2: 12016 // If the name is a function template, template argument deduction is 12017 // done (14.8.2.2), and if the argument deduction succeeds, the 12018 // resulting template argument list is used to generate a single 12019 // function template specialization, which is added to the set of 12020 // overloaded functions considered. 12021 FunctionDecl *Specialization = nullptr; 12022 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12023 if (Sema::TemplateDeductionResult Result 12024 = S.DeduceTemplateArguments(FunctionTemplate, 12025 &OvlExplicitTemplateArgs, 12026 TargetFunctionType, Specialization, 12027 Info, /*IsAddressOfFunction*/true)) { 12028 // Make a note of the failed deduction for diagnostics. 12029 FailedCandidates.addCandidate() 12030 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12031 MakeDeductionFailureInfo(Context, Result, Info)); 12032 return false; 12033 } 12034 12035 // Template argument deduction ensures that we have an exact match or 12036 // compatible pointer-to-function arguments that would be adjusted by ICS. 12037 // This function template specicalization works. 12038 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12040, __PRETTY_FUNCTION__))
12039 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12040, __PRETTY_FUNCTION__))
12040 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12040, __PRETTY_FUNCTION__))
; 12041 12042 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12043 return false; 12044 12045 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12046 return true; 12047 } 12048 12049 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12050 const DeclAccessPair& CurAccessFunPair) { 12051 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12052 // Skip non-static functions when converting to pointer, and static 12053 // when converting to member pointer. 12054 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12055 return false; 12056 } 12057 else if (TargetTypeIsNonStaticMemberFunction) 12058 return false; 12059 12060 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12061 if (S.getLangOpts().CUDA) 12062 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12063 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12064 return false; 12065 if (FunDecl->isMultiVersion()) { 12066 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12067 if (TA && !TA->isDefaultVersion()) 12068 return false; 12069 } 12070 12071 // If any candidate has a placeholder return type, trigger its deduction 12072 // now. 12073 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12074 Complain)) { 12075 HasComplained |= Complain; 12076 return false; 12077 } 12078 12079 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12080 return false; 12081 12082 // If we're in C, we need to support types that aren't exactly identical. 12083 if (!S.getLangOpts().CPlusPlus || 12084 candidateHasExactlyCorrectType(FunDecl)) { 12085 Matches.push_back(std::make_pair( 12086 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12087 FoundNonTemplateFunction = true; 12088 return true; 12089 } 12090 } 12091 12092 return false; 12093 } 12094 12095 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12096 bool Ret = false; 12097 12098 // If the overload expression doesn't have the form of a pointer to 12099 // member, don't try to convert it to a pointer-to-member type. 12100 if (IsInvalidFormOfPointerToMemberFunction()) 12101 return false; 12102 12103 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12104 E = OvlExpr->decls_end(); 12105 I != E; ++I) { 12106 // Look through any using declarations to find the underlying function. 12107 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12108 12109 // C++ [over.over]p3: 12110 // Non-member functions and static member functions match 12111 // targets of type "pointer-to-function" or "reference-to-function." 12112 // Nonstatic member functions match targets of 12113 // type "pointer-to-member-function." 12114 // Note that according to DR 247, the containing class does not matter. 12115 if (FunctionTemplateDecl *FunctionTemplate 12116 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12117 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12118 Ret = true; 12119 } 12120 // If we have explicit template arguments supplied, skip non-templates. 12121 else if (!OvlExpr->hasExplicitTemplateArgs() && 12122 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12123 Ret = true; 12124 } 12125 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12125, __PRETTY_FUNCTION__))
; 12126 return Ret; 12127 } 12128 12129 void EliminateAllExceptMostSpecializedTemplate() { 12130 // [...] and any given function template specialization F1 is 12131 // eliminated if the set contains a second function template 12132 // specialization whose function template is more specialized 12133 // than the function template of F1 according to the partial 12134 // ordering rules of 14.5.5.2. 12135 12136 // The algorithm specified above is quadratic. We instead use a 12137 // two-pass algorithm (similar to the one used to identify the 12138 // best viable function in an overload set) that identifies the 12139 // best function template (if it exists). 12140 12141 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12142 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12143 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12144 12145 // TODO: It looks like FailedCandidates does not serve much purpose 12146 // here, since the no_viable diagnostic has index 0. 12147 UnresolvedSetIterator Result = S.getMostSpecialized( 12148 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12149 SourceExpr->getBeginLoc(), S.PDiag(), 12150 S.PDiag(diag::err_addr_ovl_ambiguous) 12151 << Matches[0].second->getDeclName(), 12152 S.PDiag(diag::note_ovl_candidate) 12153 << (unsigned)oc_function << (unsigned)ocs_described_template, 12154 Complain, TargetFunctionType); 12155 12156 if (Result != MatchesCopy.end()) { 12157 // Make it the first and only element 12158 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12159 Matches[0].second = cast<FunctionDecl>(*Result); 12160 Matches.resize(1); 12161 } else 12162 HasComplained |= Complain; 12163 } 12164 12165 void EliminateAllTemplateMatches() { 12166 // [...] any function template specializations in the set are 12167 // eliminated if the set also contains a non-template function, [...] 12168 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12169 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12170 ++I; 12171 else { 12172 Matches[I] = Matches[--N]; 12173 Matches.resize(N); 12174 } 12175 } 12176 } 12177 12178 void EliminateSuboptimalCudaMatches() { 12179 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12180 } 12181 12182public: 12183 void ComplainNoMatchesFound() const { 12184 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12184, __PRETTY_FUNCTION__))
; 12185 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12186 << OvlExpr->getName() << TargetFunctionType 12187 << OvlExpr->getSourceRange(); 12188 if (FailedCandidates.empty()) 12189 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12190 /*TakingAddress=*/true); 12191 else { 12192 // We have some deduction failure messages. Use them to diagnose 12193 // the function templates, and diagnose the non-template candidates 12194 // normally. 12195 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12196 IEnd = OvlExpr->decls_end(); 12197 I != IEnd; ++I) 12198 if (FunctionDecl *Fun = 12199 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12200 if (!functionHasPassObjectSizeParams(Fun)) 12201 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12202 /*TakingAddress=*/true); 12203 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12204 } 12205 } 12206 12207 bool IsInvalidFormOfPointerToMemberFunction() const { 12208 return TargetTypeIsNonStaticMemberFunction && 12209 !OvlExprInfo.HasFormOfMemberPointer; 12210 } 12211 12212 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12213 // TODO: Should we condition this on whether any functions might 12214 // have matched, or is it more appropriate to do that in callers? 12215 // TODO: a fixit wouldn't hurt. 12216 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12217 << TargetType << OvlExpr->getSourceRange(); 12218 } 12219 12220 bool IsStaticMemberFunctionFromBoundPointer() const { 12221 return StaticMemberFunctionFromBoundPointer; 12222 } 12223 12224 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12225 S.Diag(OvlExpr->getBeginLoc(), 12226 diag::err_invalid_form_pointer_member_function) 12227 << OvlExpr->getSourceRange(); 12228 } 12229 12230 void ComplainOfInvalidConversion() const { 12231 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12232 << OvlExpr->getName() << TargetType; 12233 } 12234 12235 void ComplainMultipleMatchesFound() const { 12236 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12236, __PRETTY_FUNCTION__))
; 12237 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12238 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12239 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12240 /*TakingAddress=*/true); 12241 } 12242 12243 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12244 12245 int getNumMatches() const { return Matches.size(); } 12246 12247 FunctionDecl* getMatchingFunctionDecl() const { 12248 if (Matches.size() != 1) return nullptr; 12249 return Matches[0].second; 12250 } 12251 12252 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12253 if (Matches.size() != 1) return nullptr; 12254 return &Matches[0].first; 12255 } 12256}; 12257} 12258 12259/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12260/// an overloaded function (C++ [over.over]), where @p From is an 12261/// expression with overloaded function type and @p ToType is the type 12262/// we're trying to resolve to. For example: 12263/// 12264/// @code 12265/// int f(double); 12266/// int f(int); 12267/// 12268/// int (*pfd)(double) = f; // selects f(double) 12269/// @endcode 12270/// 12271/// This routine returns the resulting FunctionDecl if it could be 12272/// resolved, and NULL otherwise. When @p Complain is true, this 12273/// routine will emit diagnostics if there is an error. 12274FunctionDecl * 12275Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12276 QualType TargetType, 12277 bool Complain, 12278 DeclAccessPair &FoundResult, 12279 bool *pHadMultipleCandidates) { 12280 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12280, __PRETTY_FUNCTION__))
; 12281 12282 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12283 Complain); 12284 int NumMatches = Resolver.getNumMatches(); 12285 FunctionDecl *Fn = nullptr; 12286 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12287 if (NumMatches == 0 && ShouldComplain) { 12288 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12289 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12290 else 12291 Resolver.ComplainNoMatchesFound(); 12292 } 12293 else if (NumMatches > 1 && ShouldComplain) 12294 Resolver.ComplainMultipleMatchesFound(); 12295 else if (NumMatches == 1) { 12296 Fn = Resolver.getMatchingFunctionDecl(); 12297 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12297, __PRETTY_FUNCTION__))
; 12298 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12299 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12300 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12301 if (Complain) { 12302 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12303 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12304 else 12305 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12306 } 12307 } 12308 12309 if (pHadMultipleCandidates) 12310 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12311 return Fn; 12312} 12313 12314/// Given an expression that refers to an overloaded function, try to 12315/// resolve that function to a single function that can have its address taken. 12316/// This will modify `Pair` iff it returns non-null. 12317/// 12318/// This routine can only succeed if from all of the candidates in the overload 12319/// set for SrcExpr that can have their addresses taken, there is one candidate 12320/// that is more constrained than the rest. 12321FunctionDecl * 12322Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12323 OverloadExpr::FindResult R = OverloadExpr::find(E); 12324 OverloadExpr *Ovl = R.Expression; 12325 bool IsResultAmbiguous = false; 12326 FunctionDecl *Result = nullptr; 12327 DeclAccessPair DAP; 12328 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12329 12330 auto CheckMoreConstrained = 12331 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12332 SmallVector<const Expr *, 1> AC1, AC2; 12333 FD1->getAssociatedConstraints(AC1); 12334 FD2->getAssociatedConstraints(AC2); 12335 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12336 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12337 return None; 12338 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12339 return None; 12340 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12341 return None; 12342 return AtLeastAsConstrained1; 12343 }; 12344 12345 // Don't use the AddressOfResolver because we're specifically looking for 12346 // cases where we have one overload candidate that lacks 12347 // enable_if/pass_object_size/... 12348 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12349 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12350 if (!FD) 12351 return nullptr; 12352 12353 if (!checkAddressOfFunctionIsAvailable(FD)) 12354 continue; 12355 12356 // We have more than one result - see if it is more constrained than the 12357 // previous one. 12358 if (Result) { 12359 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12360 Result); 12361 if (!MoreConstrainedThanPrevious) { 12362 IsResultAmbiguous = true; 12363 AmbiguousDecls.push_back(FD); 12364 continue; 12365 } 12366 if (!*MoreConstrainedThanPrevious) 12367 continue; 12368 // FD is more constrained - replace Result with it. 12369 } 12370 IsResultAmbiguous = false; 12371 DAP = I.getPair(); 12372 Result = FD; 12373 } 12374 12375 if (IsResultAmbiguous) 12376 return nullptr; 12377 12378 if (Result) { 12379 SmallVector<const Expr *, 1> ResultAC; 12380 // We skipped over some ambiguous declarations which might be ambiguous with 12381 // the selected result. 12382 for (FunctionDecl *Skipped : AmbiguousDecls) 12383 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12384 return nullptr; 12385 Pair = DAP; 12386 } 12387 return Result; 12388} 12389 12390/// Given an overloaded function, tries to turn it into a non-overloaded 12391/// function reference using resolveAddressOfSingleOverloadCandidate. This 12392/// will perform access checks, diagnose the use of the resultant decl, and, if 12393/// requested, potentially perform a function-to-pointer decay. 12394/// 12395/// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12396/// Otherwise, returns true. This may emit diagnostics and return true. 12397bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12398 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12399 Expr *E = SrcExpr.get(); 12400 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload"
) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12400, __PRETTY_FUNCTION__))
; 12401 12402 DeclAccessPair DAP; 12403 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12404 if (!Found || Found->isCPUDispatchMultiVersion() || 12405 Found->isCPUSpecificMultiVersion()) 12406 return false; 12407 12408 // Emitting multiple diagnostics for a function that is both inaccessible and 12409 // unavailable is consistent with our behavior elsewhere. So, always check 12410 // for both. 12411 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12412 CheckAddressOfMemberAccess(E, DAP); 12413 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12414 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12415 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12416 else 12417 SrcExpr = Fixed; 12418 return true; 12419} 12420 12421/// Given an expression that refers to an overloaded function, try to 12422/// resolve that overloaded function expression down to a single function. 12423/// 12424/// This routine can only resolve template-ids that refer to a single function 12425/// template, where that template-id refers to a single template whose template 12426/// arguments are either provided by the template-id or have defaults, 12427/// as described in C++0x [temp.arg.explicit]p3. 12428/// 12429/// If no template-ids are found, no diagnostics are emitted and NULL is 12430/// returned. 12431FunctionDecl * 12432Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12433 bool Complain, 12434 DeclAccessPair *FoundResult) { 12435 // C++ [over.over]p1: 12436 // [...] [Note: any redundant set of parentheses surrounding the 12437 // overloaded function name is ignored (5.1). ] 12438 // C++ [over.over]p1: 12439 // [...] The overloaded function name can be preceded by the & 12440 // operator. 12441 12442 // If we didn't actually find any template-ids, we're done. 12443 if (!ovl->hasExplicitTemplateArgs()) 12444 return nullptr; 12445 12446 TemplateArgumentListInfo ExplicitTemplateArgs; 12447 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12448 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12449 12450 // Look through all of the overloaded functions, searching for one 12451 // whose type matches exactly. 12452 FunctionDecl *Matched = nullptr; 12453 for (UnresolvedSetIterator I = ovl->decls_begin(), 12454 E = ovl->decls_end(); I != E; ++I) { 12455 // C++0x [temp.arg.explicit]p3: 12456 // [...] In contexts where deduction is done and fails, or in contexts 12457 // where deduction is not done, if a template argument list is 12458 // specified and it, along with any default template arguments, 12459 // identifies a single function template specialization, then the 12460 // template-id is an lvalue for the function template specialization. 12461 FunctionTemplateDecl *FunctionTemplate 12462 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12463 12464 // C++ [over.over]p2: 12465 // If the name is a function template, template argument deduction is 12466 // done (14.8.2.2), and if the argument deduction succeeds, the 12467 // resulting template argument list is used to generate a single 12468 // function template specialization, which is added to the set of 12469 // overloaded functions considered. 12470 FunctionDecl *Specialization = nullptr; 12471 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12472 if (TemplateDeductionResult Result 12473 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12474 Specialization, Info, 12475 /*IsAddressOfFunction*/true)) { 12476 // Make a note of the failed deduction for diagnostics. 12477 // TODO: Actually use the failed-deduction info? 12478 FailedCandidates.addCandidate() 12479 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12480 MakeDeductionFailureInfo(Context, Result, Info)); 12481 continue; 12482 } 12483 12484 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12484, __PRETTY_FUNCTION__))
; 12485 12486 // Multiple matches; we can't resolve to a single declaration. 12487 if (Matched) { 12488 if (Complain) { 12489 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12490 << ovl->getName(); 12491 NoteAllOverloadCandidates(ovl); 12492 } 12493 return nullptr; 12494 } 12495 12496 Matched = Specialization; 12497 if (FoundResult) *FoundResult = I.getPair(); 12498 } 12499 12500 if (Matched && 12501 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12502 return nullptr; 12503 12504 return Matched; 12505} 12506 12507// Resolve and fix an overloaded expression that can be resolved 12508// because it identifies a single function template specialization. 12509// 12510// Last three arguments should only be supplied if Complain = true 12511// 12512// Return true if it was logically possible to so resolve the 12513// expression, regardless of whether or not it succeeded. Always 12514// returns true if 'complain' is set. 12515bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12516 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12517 bool complain, SourceRange OpRangeForComplaining, 12518 QualType DestTypeForComplaining, 12519 unsigned DiagIDForComplaining) { 12520 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12520, __PRETTY_FUNCTION__))
; 12521 12522 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12523 12524 DeclAccessPair found; 12525 ExprResult SingleFunctionExpression; 12526 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12527 ovl.Expression, /*complain*/ false, &found)) { 12528 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12529 SrcExpr = ExprError(); 12530 return true; 12531 } 12532 12533 // It is only correct to resolve to an instance method if we're 12534 // resolving a form that's permitted to be a pointer to member. 12535 // Otherwise we'll end up making a bound member expression, which 12536 // is illegal in all the contexts we resolve like this. 12537 if (!ovl.HasFormOfMemberPointer && 12538 isa<CXXMethodDecl>(fn) && 12539 cast<CXXMethodDecl>(fn)->isInstance()) { 12540 if (!complain) return false; 12541 12542 Diag(ovl.Expression->getExprLoc(), 12543 diag::err_bound_member_function) 12544 << 0 << ovl.Expression->getSourceRange(); 12545 12546 // TODO: I believe we only end up here if there's a mix of 12547 // static and non-static candidates (otherwise the expression 12548 // would have 'bound member' type, not 'overload' type). 12549 // Ideally we would note which candidate was chosen and why 12550 // the static candidates were rejected. 12551 SrcExpr = ExprError(); 12552 return true; 12553 } 12554 12555 // Fix the expression to refer to 'fn'. 12556 SingleFunctionExpression = 12557 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12558 12559 // If desired, do function-to-pointer decay. 12560 if (doFunctionPointerConverion) { 12561 SingleFunctionExpression = 12562 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12563 if (SingleFunctionExpression.isInvalid()) { 12564 SrcExpr = ExprError(); 12565 return true; 12566 } 12567 } 12568 } 12569 12570 if (!SingleFunctionExpression.isUsable()) { 12571 if (complain) { 12572 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12573 << ovl.Expression->getName() 12574 << DestTypeForComplaining 12575 << OpRangeForComplaining 12576 << ovl.Expression->getQualifierLoc().getSourceRange(); 12577 NoteAllOverloadCandidates(SrcExpr.get()); 12578 12579 SrcExpr = ExprError(); 12580 return true; 12581 } 12582 12583 return false; 12584 } 12585 12586 SrcExpr = SingleFunctionExpression; 12587 return true; 12588} 12589 12590/// Add a single candidate to the overload set. 12591static void AddOverloadedCallCandidate(Sema &S, 12592 DeclAccessPair FoundDecl, 12593 TemplateArgumentListInfo *ExplicitTemplateArgs, 12594 ArrayRef<Expr *> Args, 12595 OverloadCandidateSet &CandidateSet, 12596 bool PartialOverloading, 12597 bool KnownValid) { 12598 NamedDecl *Callee = FoundDecl.getDecl(); 12599 if (isa<UsingShadowDecl>(Callee)) 12600 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12601 12602 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12603 if (ExplicitTemplateArgs) { 12604 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12604, __PRETTY_FUNCTION__))
; 12605 return; 12606 } 12607 // Prevent ill-formed function decls to be added as overload candidates. 12608 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12609 return; 12610 12611 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12612 /*SuppressUserConversions=*/false, 12613 PartialOverloading); 12614 return; 12615 } 12616 12617 if (FunctionTemplateDecl *FuncTemplate 12618 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12619 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12620 ExplicitTemplateArgs, Args, CandidateSet, 12621 /*SuppressUserConversions=*/false, 12622 PartialOverloading); 12623 return; 12624 } 12625 12626 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12626, __PRETTY_FUNCTION__))
; 12627} 12628 12629/// Add the overload candidates named by callee and/or found by argument 12630/// dependent lookup to the given overload set. 12631void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12632 ArrayRef<Expr *> Args, 12633 OverloadCandidateSet &CandidateSet, 12634 bool PartialOverloading) { 12635 12636#ifndef NDEBUG 12637 // Verify that ArgumentDependentLookup is consistent with the rules 12638 // in C++0x [basic.lookup.argdep]p3: 12639 // 12640 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12641 // and let Y be the lookup set produced by argument dependent 12642 // lookup (defined as follows). If X contains 12643 // 12644 // -- a declaration of a class member, or 12645 // 12646 // -- a block-scope function declaration that is not a 12647 // using-declaration, or 12648 // 12649 // -- a declaration that is neither a function or a function 12650 // template 12651 // 12652 // then Y is empty. 12653 12654 if (ULE->requiresADL()) { 12655 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12656 E = ULE->decls_end(); I != E; ++I) { 12657 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12657, __PRETTY_FUNCTION__))
; 12658 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12659, __PRETTY_FUNCTION__))
12659 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12659, __PRETTY_FUNCTION__))
; 12660 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12660, __PRETTY_FUNCTION__))
; 12661 } 12662 } 12663#endif 12664 12665 // It would be nice to avoid this copy. 12666 TemplateArgumentListInfo TABuffer; 12667 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12668 if (ULE->hasExplicitTemplateArgs()) { 12669 ULE->copyTemplateArgumentsInto(TABuffer); 12670 ExplicitTemplateArgs = &TABuffer; 12671 } 12672 12673 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12674 E = ULE->decls_end(); I != E; ++I) 12675 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12676 CandidateSet, PartialOverloading, 12677 /*KnownValid*/ true); 12678 12679 if (ULE->requiresADL()) 12680 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12681 Args, ExplicitTemplateArgs, 12682 CandidateSet, PartialOverloading); 12683} 12684 12685/// Add the call candidates from the given set of lookup results to the given 12686/// overload set. Non-function lookup results are ignored. 12687void Sema::AddOverloadedCallCandidates( 12688 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12689 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12690 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12691 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12692 CandidateSet, false, /*KnownValid*/ false); 12693} 12694 12695/// Determine whether a declaration with the specified name could be moved into 12696/// a different namespace. 12697static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12698 switch (Name.getCXXOverloadedOperator()) { 12699 case OO_New: case OO_Array_New: 12700 case OO_Delete: case OO_Array_Delete: 12701 return false; 12702 12703 default: 12704 return true; 12705 } 12706} 12707 12708/// Attempt to recover from an ill-formed use of a non-dependent name in a 12709/// template, where the non-dependent name was declared after the template 12710/// was defined. This is common in code written for a compilers which do not 12711/// correctly implement two-stage name lookup. 12712/// 12713/// Returns true if a viable candidate was found and a diagnostic was issued. 12714static bool DiagnoseTwoPhaseLookup( 12715 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12716 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12717 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12718 CXXRecordDecl **FoundInClass = nullptr) { 12719 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12720 return false; 12721 12722 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12723 if (DC->isTransparentContext()) 12724 continue; 12725 12726 SemaRef.LookupQualifiedName(R, DC); 12727 12728 if (!R.empty()) { 12729 R.suppressDiagnostics(); 12730 12731 OverloadCandidateSet Candidates(FnLoc, CSK); 12732 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12733 Candidates); 12734 12735 OverloadCandidateSet::iterator Best; 12736 OverloadingResult OR = 12737 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12738 12739 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12740 // We either found non-function declarations or a best viable function 12741 // at class scope. A class-scope lookup result disables ADL. Don't 12742 // look past this, but let the caller know that we found something that 12743 // either is, or might be, usable in this class. 12744 if (FoundInClass) { 12745 *FoundInClass = RD; 12746 if (OR == OR_Success) { 12747 R.clear(); 12748 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12749 R.resolveKind(); 12750 } 12751 } 12752 return false; 12753 } 12754 12755 if (OR != OR_Success) { 12756 // There wasn't a unique best function or function template. 12757 return false; 12758 } 12759 12760 // Find the namespaces where ADL would have looked, and suggest 12761 // declaring the function there instead. 12762 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12763 Sema::AssociatedClassSet AssociatedClasses; 12764 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12765 AssociatedNamespaces, 12766 AssociatedClasses); 12767 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12768 if (canBeDeclaredInNamespace(R.getLookupName())) { 12769 DeclContext *Std = SemaRef.getStdNamespace(); 12770 for (Sema::AssociatedNamespaceSet::iterator 12771 it = AssociatedNamespaces.begin(), 12772 end = AssociatedNamespaces.end(); it != end; ++it) { 12773 // Never suggest declaring a function within namespace 'std'. 12774 if (Std && Std->Encloses(*it)) 12775 continue; 12776 12777 // Never suggest declaring a function within a namespace with a 12778 // reserved name, like __gnu_cxx. 12779 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12780 if (NS && 12781 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12782 continue; 12783 12784 SuggestedNamespaces.insert(*it); 12785 } 12786 } 12787 12788 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12789 << R.getLookupName(); 12790 if (SuggestedNamespaces.empty()) { 12791 SemaRef.Diag(Best->Function->getLocation(), 12792 diag::note_not_found_by_two_phase_lookup) 12793 << R.getLookupName() << 0; 12794 } else if (SuggestedNamespaces.size() == 1) { 12795 SemaRef.Diag(Best->Function->getLocation(), 12796 diag::note_not_found_by_two_phase_lookup) 12797 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12798 } else { 12799 // FIXME: It would be useful to list the associated namespaces here, 12800 // but the diagnostics infrastructure doesn't provide a way to produce 12801 // a localized representation of a list of items. 12802 SemaRef.Diag(Best->Function->getLocation(), 12803 diag::note_not_found_by_two_phase_lookup) 12804 << R.getLookupName() << 2; 12805 } 12806 12807 // Try to recover by calling this function. 12808 return true; 12809 } 12810 12811 R.clear(); 12812 } 12813 12814 return false; 12815} 12816 12817/// Attempt to recover from ill-formed use of a non-dependent operator in a 12818/// template, where the non-dependent operator was declared after the template 12819/// was defined. 12820/// 12821/// Returns true if a viable candidate was found and a diagnostic was issued. 12822static bool 12823DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12824 SourceLocation OpLoc, 12825 ArrayRef<Expr *> Args) { 12826 DeclarationName OpName = 12827 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12828 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12829 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12830 OverloadCandidateSet::CSK_Operator, 12831 /*ExplicitTemplateArgs=*/nullptr, Args); 12832} 12833 12834namespace { 12835class BuildRecoveryCallExprRAII { 12836 Sema &SemaRef; 12837public: 12838 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12839 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12839, __PRETTY_FUNCTION__))
; 12840 SemaRef.IsBuildingRecoveryCallExpr = true; 12841 } 12842 12843 ~BuildRecoveryCallExprRAII() { 12844 SemaRef.IsBuildingRecoveryCallExpr = false; 12845 } 12846}; 12847 12848} 12849 12850/// Attempts to recover from a call where no functions were found. 12851/// 12852/// This function will do one of three things: 12853/// * Diagnose, recover, and return a recovery expression. 12854/// * Diagnose, fail to recover, and return ExprError(). 12855/// * Do not diagnose, do not recover, and return ExprResult(). The caller is 12856/// expected to diagnose as appropriate. 12857static ExprResult 12858BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12859 UnresolvedLookupExpr *ULE, 12860 SourceLocation LParenLoc, 12861 MutableArrayRef<Expr *> Args, 12862 SourceLocation RParenLoc, 12863 bool EmptyLookup, bool AllowTypoCorrection) { 12864 // Do not try to recover if it is already building a recovery call. 12865 // This stops infinite loops for template instantiations like 12866 // 12867 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12868 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12869 if (SemaRef.IsBuildingRecoveryCallExpr) 12870 return ExprResult(); 12871 BuildRecoveryCallExprRAII RCE(SemaRef); 12872 12873 CXXScopeSpec SS; 12874 SS.Adopt(ULE->getQualifierLoc()); 12875 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12876 12877 TemplateArgumentListInfo TABuffer; 12878 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12879 if (ULE->hasExplicitTemplateArgs()) { 12880 ULE->copyTemplateArgumentsInto(TABuffer); 12881 ExplicitTemplateArgs = &TABuffer; 12882 } 12883 12884 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12885 Sema::LookupOrdinaryName); 12886 CXXRecordDecl *FoundInClass = nullptr; 12887 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 12888 OverloadCandidateSet::CSK_Normal, 12889 ExplicitTemplateArgs, Args, &FoundInClass)) { 12890 // OK, diagnosed a two-phase lookup issue. 12891 } else if (EmptyLookup) { 12892 // Try to recover from an empty lookup with typo correction. 12893 R.clear(); 12894 NoTypoCorrectionCCC NoTypoValidator{}; 12895 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12896 ExplicitTemplateArgs != nullptr, 12897 dyn_cast<MemberExpr>(Fn)); 12898 CorrectionCandidateCallback &Validator = 12899 AllowTypoCorrection 12900 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12901 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12902 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12903 Args)) 12904 return ExprError(); 12905 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 12906 // We found a usable declaration of the name in a dependent base of some 12907 // enclosing class. 12908 // FIXME: We should also explain why the candidates found by name lookup 12909 // were not viable. 12910 if (SemaRef.DiagnoseDependentMemberLookup(R)) 12911 return ExprError(); 12912 } else { 12913 // We had viable candidates and couldn't recover; let the caller diagnose 12914 // this. 12915 return ExprResult(); 12916 } 12917 12918 // If we get here, we should have issued a diagnostic and formed a recovery 12919 // lookup result. 12920 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12920, __PRETTY_FUNCTION__))
; 12921 12922 // If recovery created an ambiguity, just bail out. 12923 if (R.isAmbiguous()) { 12924 R.suppressDiagnostics(); 12925 return ExprError(); 12926 } 12927 12928 // Build an implicit member call if appropriate. Just drop the 12929 // casts and such from the call, we don't really care. 12930 ExprResult NewFn = ExprError(); 12931 if ((*R.begin())->isCXXClassMember()) 12932 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12933 ExplicitTemplateArgs, S); 12934 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12935 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12936 ExplicitTemplateArgs); 12937 else 12938 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12939 12940 if (NewFn.isInvalid()) 12941 return ExprError(); 12942 12943 // This shouldn't cause an infinite loop because we're giving it 12944 // an expression with viable lookup results, which should never 12945 // end up here. 12946 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12947 MultiExprArg(Args.data(), Args.size()), 12948 RParenLoc); 12949} 12950 12951/// Constructs and populates an OverloadedCandidateSet from 12952/// the given function. 12953/// \returns true when an the ExprResult output parameter has been set. 12954bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12955 UnresolvedLookupExpr *ULE, 12956 MultiExprArg Args, 12957 SourceLocation RParenLoc, 12958 OverloadCandidateSet *CandidateSet, 12959 ExprResult *Result) { 12960#ifndef NDEBUG 12961 if (ULE->requiresADL()) { 12962 // To do ADL, we must have found an unqualified name. 12963 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12963, __PRETTY_FUNCTION__))
; 12964 12965 // We don't perform ADL for implicit declarations of builtins. 12966 // Verify that this was correctly set up. 12967 FunctionDecl *F; 12968 if (ULE->decls_begin() != ULE->decls_end() && 12969 ULE->decls_begin() + 1 == ULE->decls_end() && 12970 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12971 F->getBuiltinID() && F->isImplicit()) 12972 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12972)
; 12973 12974 // We don't perform ADL in C. 12975 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 12975, __PRETTY_FUNCTION__))
; 12976 } 12977#endif 12978 12979 UnbridgedCastsSet UnbridgedCasts; 12980 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12981 *Result = ExprError(); 12982 return true; 12983 } 12984 12985 // Add the functions denoted by the callee to the set of candidate 12986 // functions, including those from argument-dependent lookup. 12987 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12988 12989 if (getLangOpts().MSVCCompat && 12990 CurContext->isDependentContext() && !isSFINAEContext() && 12991 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12992 12993 OverloadCandidateSet::iterator Best; 12994 if (CandidateSet->empty() || 12995 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12996 OR_No_Viable_Function) { 12997 // In Microsoft mode, if we are inside a template class member function 12998 // then create a type dependent CallExpr. The goal is to postpone name 12999 // lookup to instantiation time to be able to search into type dependent 13000 // base classes. 13001 CallExpr *CE = 13002 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue, 13003 RParenLoc, CurFPFeatureOverrides()); 13004 CE->markDependentForPostponedNameLookup(); 13005 *Result = CE; 13006 return true; 13007 } 13008 } 13009 13010 if (CandidateSet->empty()) 13011 return false; 13012 13013 UnbridgedCasts.restore(); 13014 return false; 13015} 13016 13017// Guess at what the return type for an unresolvable overload should be. 13018static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13019 OverloadCandidateSet::iterator *Best) { 13020 llvm::Optional<QualType> Result; 13021 // Adjust Type after seeing a candidate. 13022 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13023 if (!Candidate.Function) 13024 return; 13025 if (Candidate.Function->isInvalidDecl()) 13026 return; 13027 QualType T = Candidate.Function->getReturnType(); 13028 if (T.isNull()) 13029 return; 13030 if (!Result) 13031 Result = T; 13032 else if (Result != T) 13033 Result = QualType(); 13034 }; 13035 13036 // Look for an unambiguous type from a progressively larger subset. 13037 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13038 // 13039 // First, consider only the best candidate. 13040 if (Best && *Best != CS.end()) 13041 ConsiderCandidate(**Best); 13042 // Next, consider only viable candidates. 13043 if (!Result) 13044 for (const auto &C : CS) 13045 if (C.Viable) 13046 ConsiderCandidate(C); 13047 // Finally, consider all candidates. 13048 if (!Result) 13049 for (const auto &C : CS) 13050 ConsiderCandidate(C); 13051 13052 if (!Result) 13053 return QualType(); 13054 auto Value = Result.getValue(); 13055 if (Value.isNull() || Value->isUndeducedType()) 13056 return QualType(); 13057 return Value; 13058} 13059 13060/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13061/// the completed call expression. If overload resolution fails, emits 13062/// diagnostics and returns ExprError() 13063static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13064 UnresolvedLookupExpr *ULE, 13065 SourceLocation LParenLoc, 13066 MultiExprArg Args, 13067 SourceLocation RParenLoc, 13068 Expr *ExecConfig, 13069 OverloadCandidateSet *CandidateSet, 13070 OverloadCandidateSet::iterator *Best, 13071 OverloadingResult OverloadResult, 13072 bool AllowTypoCorrection) { 13073 switch (OverloadResult) { 13074 case OR_Success: { 13075 FunctionDecl *FDecl = (*Best)->Function; 13076 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13077 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13078 return ExprError(); 13079 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13080 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13081 ExecConfig, /*IsExecConfig=*/false, 13082 (*Best)->IsADLCandidate); 13083 } 13084 13085 case OR_No_Viable_Function: { 13086 // Try to recover by looking for viable functions which the user might 13087 // have meant to call. 13088 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13089 Args, RParenLoc, 13090 CandidateSet->empty(), 13091 AllowTypoCorrection); 13092 if (Recovery.isInvalid() || Recovery.isUsable()) 13093 return Recovery; 13094 13095 // If the user passes in a function that we can't take the address of, we 13096 // generally end up emitting really bad error messages. Here, we attempt to 13097 // emit better ones. 13098 for (const Expr *Arg : Args) { 13099 if (!Arg->getType()->isFunctionType()) 13100 continue; 13101 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13102 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13103 if (FD && 13104 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13105 Arg->getExprLoc())) 13106 return ExprError(); 13107 } 13108 } 13109 13110 CandidateSet->NoteCandidates( 13111 PartialDiagnosticAt( 13112 Fn->getBeginLoc(), 13113 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13114 << ULE->getName() << Fn->getSourceRange()), 13115 SemaRef, OCD_AllCandidates, Args); 13116 break; 13117 } 13118 13119 case OR_Ambiguous: 13120 CandidateSet->NoteCandidates( 13121 PartialDiagnosticAt(Fn->getBeginLoc(), 13122 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13123 << ULE->getName() << Fn->getSourceRange()), 13124 SemaRef, OCD_AmbiguousCandidates, Args); 13125 break; 13126 13127 case OR_Deleted: { 13128 CandidateSet->NoteCandidates( 13129 PartialDiagnosticAt(Fn->getBeginLoc(), 13130 SemaRef.PDiag(diag::err_ovl_deleted_call) 13131 << ULE->getName() << Fn->getSourceRange()), 13132 SemaRef, OCD_AllCandidates, Args); 13133 13134 // We emitted an error for the unavailable/deleted function call but keep 13135 // the call in the AST. 13136 FunctionDecl *FDecl = (*Best)->Function; 13137 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13138 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13139 ExecConfig, /*IsExecConfig=*/false, 13140 (*Best)->IsADLCandidate); 13141 } 13142 } 13143 13144 // Overload resolution failed, try to recover. 13145 SmallVector<Expr *, 8> SubExprs = {Fn}; 13146 SubExprs.append(Args.begin(), Args.end()); 13147 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13148 chooseRecoveryType(*CandidateSet, Best)); 13149} 13150 13151static void markUnaddressableCandidatesUnviable(Sema &S, 13152 OverloadCandidateSet &CS) { 13153 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13154 if (I->Viable && 13155 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13156 I->Viable = false; 13157 I->FailureKind = ovl_fail_addr_not_available; 13158 } 13159 } 13160} 13161 13162/// BuildOverloadedCallExpr - Given the call expression that calls Fn 13163/// (which eventually refers to the declaration Func) and the call 13164/// arguments Args/NumArgs, attempt to resolve the function call down 13165/// to a specific function. If overload resolution succeeds, returns 13166/// the call expression produced by overload resolution. 13167/// Otherwise, emits diagnostics and returns ExprError. 13168ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13169 UnresolvedLookupExpr *ULE, 13170 SourceLocation LParenLoc, 13171 MultiExprArg Args, 13172 SourceLocation RParenLoc, 13173 Expr *ExecConfig, 13174 bool AllowTypoCorrection, 13175 bool CalleesAddressIsTaken) { 13176 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13177 OverloadCandidateSet::CSK_Normal); 13178 ExprResult result; 13179 13180 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13181 &result)) 13182 return result; 13183 13184 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13185 // functions that aren't addressible are considered unviable. 13186 if (CalleesAddressIsTaken) 13187 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13188 13189 OverloadCandidateSet::iterator Best; 13190 OverloadingResult OverloadResult = 13191 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13192 13193 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13194 ExecConfig, &CandidateSet, &Best, 13195 OverloadResult, AllowTypoCorrection); 13196} 13197 13198static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13199 return Functions.size() > 1 || 13200 (Functions.size() == 1 && 13201 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13202} 13203 13204ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13205 NestedNameSpecifierLoc NNSLoc, 13206 DeclarationNameInfo DNI, 13207 const UnresolvedSetImpl &Fns, 13208 bool PerformADL) { 13209 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13210 PerformADL, IsOverloaded(Fns), 13211 Fns.begin(), Fns.end()); 13212} 13213 13214/// Create a unary operation that may resolve to an overloaded 13215/// operator. 13216/// 13217/// \param OpLoc The location of the operator itself (e.g., '*'). 13218/// 13219/// \param Opc The UnaryOperatorKind that describes this operator. 13220/// 13221/// \param Fns The set of non-member functions that will be 13222/// considered by overload resolution. The caller needs to build this 13223/// set based on the context using, e.g., 13224/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13225/// set should not contain any member functions; those will be added 13226/// by CreateOverloadedUnaryOp(). 13227/// 13228/// \param Input The input argument. 13229ExprResult 13230Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13231 const UnresolvedSetImpl &Fns, 13232 Expr *Input, bool PerformADL) { 13233 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13234 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13234, __PRETTY_FUNCTION__))
; 13235 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13236 // TODO: provide better source location info. 13237 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13238 13239 if (checkPlaceholderForOverload(*this, Input)) 13240 return ExprError(); 13241 13242 Expr *Args[2] = { Input, nullptr }; 13243 unsigned NumArgs = 1; 13244 13245 // For post-increment and post-decrement, add the implicit '0' as 13246 // the second argument, so that we know this is a post-increment or 13247 // post-decrement. 13248 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13249 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13250 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13251 SourceLocation()); 13252 NumArgs = 2; 13253 } 13254 13255 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13256 13257 if (Input->isTypeDependent()) { 13258 if (Fns.empty()) 13259 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13260 VK_RValue, OK_Ordinary, OpLoc, false, 13261 CurFPFeatureOverrides()); 13262 13263 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13264 ExprResult Fn = CreateUnresolvedLookupExpr( 13265 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13266 if (Fn.isInvalid()) 13267 return ExprError(); 13268 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13269 Context.DependentTy, VK_RValue, OpLoc, 13270 CurFPFeatureOverrides()); 13271 } 13272 13273 // Build an empty overload set. 13274 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13275 13276 // Add the candidates from the given function set. 13277 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13278 13279 // Add operator candidates that are member functions. 13280 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13281 13282 // Add candidates from ADL. 13283 if (PerformADL) { 13284 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13285 /*ExplicitTemplateArgs*/nullptr, 13286 CandidateSet); 13287 } 13288 13289 // Add builtin operator candidates. 13290 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13291 13292 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13293 13294 // Perform overload resolution. 13295 OverloadCandidateSet::iterator Best; 13296 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13297 case OR_Success: { 13298 // We found a built-in operator or an overloaded operator. 13299 FunctionDecl *FnDecl = Best->Function; 13300 13301 if (FnDecl) { 13302 Expr *Base = nullptr; 13303 // We matched an overloaded operator. Build a call to that 13304 // operator. 13305 13306 // Convert the arguments. 13307 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13308 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13309 13310 ExprResult InputRes = 13311 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13312 Best->FoundDecl, Method); 13313 if (InputRes.isInvalid()) 13314 return ExprError(); 13315 Base = Input = InputRes.get(); 13316 } else { 13317 // Convert the arguments. 13318 ExprResult InputInit 13319 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13320 Context, 13321 FnDecl->getParamDecl(0)), 13322 SourceLocation(), 13323 Input); 13324 if (InputInit.isInvalid()) 13325 return ExprError(); 13326 Input = InputInit.get(); 13327 } 13328 13329 // Build the actual expression node. 13330 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13331 Base, HadMultipleCandidates, 13332 OpLoc); 13333 if (FnExpr.isInvalid()) 13334 return ExprError(); 13335 13336 // Determine the result type. 13337 QualType ResultTy = FnDecl->getReturnType(); 13338 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13339 ResultTy = ResultTy.getNonLValueExprType(Context); 13340 13341 Args[0] = Input; 13342 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13343 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13344 CurFPFeatureOverrides(), Best->IsADLCandidate); 13345 13346 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13347 return ExprError(); 13348 13349 if (CheckFunctionCall(FnDecl, TheCall, 13350 FnDecl->getType()->castAs<FunctionProtoType>())) 13351 return ExprError(); 13352 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13353 } else { 13354 // We matched a built-in operator. Convert the arguments, then 13355 // break out so that we will build the appropriate built-in 13356 // operator node. 13357 ExprResult InputRes = PerformImplicitConversion( 13358 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13359 CCK_ForBuiltinOverloadedOp); 13360 if (InputRes.isInvalid()) 13361 return ExprError(); 13362 Input = InputRes.get(); 13363 break; 13364 } 13365 } 13366 13367 case OR_No_Viable_Function: 13368 // This is an erroneous use of an operator which can be overloaded by 13369 // a non-member function. Check for non-member operators which were 13370 // defined too late to be candidates. 13371 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13372 // FIXME: Recover by calling the found function. 13373 return ExprError(); 13374 13375 // No viable function; fall through to handling this as a 13376 // built-in operator, which will produce an error message for us. 13377 break; 13378 13379 case OR_Ambiguous: 13380 CandidateSet.NoteCandidates( 13381 PartialDiagnosticAt(OpLoc, 13382 PDiag(diag::err_ovl_ambiguous_oper_unary) 13383 << UnaryOperator::getOpcodeStr(Opc) 13384 << Input->getType() << Input->getSourceRange()), 13385 *this, OCD_AmbiguousCandidates, ArgsArray, 13386 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13387 return ExprError(); 13388 13389 case OR_Deleted: 13390 CandidateSet.NoteCandidates( 13391 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13392 << UnaryOperator::getOpcodeStr(Opc) 13393 << Input->getSourceRange()), 13394 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13395 OpLoc); 13396 return ExprError(); 13397 } 13398 13399 // Either we found no viable overloaded operator or we matched a 13400 // built-in operator. In either case, fall through to trying to 13401 // build a built-in operation. 13402 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13403} 13404 13405/// Perform lookup for an overloaded binary operator. 13406void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13407 OverloadedOperatorKind Op, 13408 const UnresolvedSetImpl &Fns, 13409 ArrayRef<Expr *> Args, bool PerformADL) { 13410 SourceLocation OpLoc = CandidateSet.getLocation(); 13411 13412 OverloadedOperatorKind ExtraOp = 13413 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13414 ? getRewrittenOverloadedOperator(Op) 13415 : OO_None; 13416 13417 // Add the candidates from the given function set. This also adds the 13418 // rewritten candidates using these functions if necessary. 13419 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13420 13421 // Add operator candidates that are member functions. 13422 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13423 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13424 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13425 OverloadCandidateParamOrder::Reversed); 13426 13427 // In C++20, also add any rewritten member candidates. 13428 if (ExtraOp) { 13429 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13430 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13431 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13432 CandidateSet, 13433 OverloadCandidateParamOrder::Reversed); 13434 } 13435 13436 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13437 // performed for an assignment operator (nor for operator[] nor operator->, 13438 // which don't get here). 13439 if (Op != OO_Equal && PerformADL) { 13440 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13441 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13442 /*ExplicitTemplateArgs*/ nullptr, 13443 CandidateSet); 13444 if (ExtraOp) { 13445 DeclarationName ExtraOpName = 13446 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13447 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13448 /*ExplicitTemplateArgs*/ nullptr, 13449 CandidateSet); 13450 } 13451 } 13452 13453 // Add builtin operator candidates. 13454 // 13455 // FIXME: We don't add any rewritten candidates here. This is strictly 13456 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13457 // resulting in our selecting a rewritten builtin candidate. For example: 13458 // 13459 // enum class E { e }; 13460 // bool operator!=(E, E) requires false; 13461 // bool k = E::e != E::e; 13462 // 13463 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13464 // it seems unreasonable to consider rewritten builtin candidates. A core 13465 // issue has been filed proposing to removed this requirement. 13466 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13467} 13468 13469/// Create a binary operation that may resolve to an overloaded 13470/// operator. 13471/// 13472/// \param OpLoc The location of the operator itself (e.g., '+'). 13473/// 13474/// \param Opc The BinaryOperatorKind that describes this operator. 13475/// 13476/// \param Fns The set of non-member functions that will be 13477/// considered by overload resolution. The caller needs to build this 13478/// set based on the context using, e.g., 13479/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13480/// set should not contain any member functions; those will be added 13481/// by CreateOverloadedBinOp(). 13482/// 13483/// \param LHS Left-hand argument. 13484/// \param RHS Right-hand argument. 13485/// \param PerformADL Whether to consider operator candidates found by ADL. 13486/// \param AllowRewrittenCandidates Whether to consider candidates found by 13487/// C++20 operator rewrites. 13488/// \param DefaultedFn If we are synthesizing a defaulted operator function, 13489/// the function in question. Such a function is never a candidate in 13490/// our overload resolution. This also enables synthesizing a three-way 13491/// comparison from < and == as described in C++20 [class.spaceship]p1. 13492ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13493 BinaryOperatorKind Opc, 13494 const UnresolvedSetImpl &Fns, Expr *LHS, 13495 Expr *RHS, bool PerformADL, 13496 bool AllowRewrittenCandidates, 13497 FunctionDecl *DefaultedFn) { 13498 Expr *Args[2] = { LHS, RHS }; 13499 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13500 13501 if (!getLangOpts().CPlusPlus20) 13502 AllowRewrittenCandidates = false; 13503 13504 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13505 13506 // If either side is type-dependent, create an appropriate dependent 13507 // expression. 13508 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13509 if (Fns.empty()) { 13510 // If there are no functions to store, just build a dependent 13511 // BinaryOperator or CompoundAssignment. 13512 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13513 return CompoundAssignOperator::Create( 13514 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13515 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13516 Context.DependentTy); 13517 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13518 Context.DependentTy, VK_RValue, OK_Ordinary, 13519 OpLoc, CurFPFeatureOverrides()); 13520 } 13521 13522 // FIXME: save results of ADL from here? 13523 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13524 // TODO: provide better source location info in DNLoc component. 13525 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13526 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13527 ExprResult Fn = CreateUnresolvedLookupExpr( 13528 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13529 if (Fn.isInvalid()) 13530 return ExprError(); 13531 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13532 Context.DependentTy, VK_RValue, OpLoc, 13533 CurFPFeatureOverrides()); 13534 } 13535 13536 // Always do placeholder-like conversions on the RHS. 13537 if (checkPlaceholderForOverload(*this, Args[1])) 13538 return ExprError(); 13539 13540 // Do placeholder-like conversion on the LHS; note that we should 13541 // not get here with a PseudoObject LHS. 13542 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13542, __PRETTY_FUNCTION__))
; 13543 if (checkPlaceholderForOverload(*this, Args[0])) 13544 return ExprError(); 13545 13546 // If this is the assignment operator, we only perform overload resolution 13547 // if the left-hand side is a class or enumeration type. This is actually 13548 // a hack. The standard requires that we do overload resolution between the 13549 // various built-in candidates, but as DR507 points out, this can lead to 13550 // problems. So we do it this way, which pretty much follows what GCC does. 13551 // Note that we go the traditional code path for compound assignment forms. 13552 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13553 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13554 13555 // If this is the .* operator, which is not overloadable, just 13556 // create a built-in binary operator. 13557 if (Opc == BO_PtrMemD) 13558 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13559 13560 // Build the overload set. 13561 OverloadCandidateSet CandidateSet( 13562 OpLoc, OverloadCandidateSet::CSK_Operator, 13563 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13564 if (DefaultedFn) 13565 CandidateSet.exclude(DefaultedFn); 13566 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13567 13568 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13569 13570 // Perform overload resolution. 13571 OverloadCandidateSet::iterator Best; 13572 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13573 case OR_Success: { 13574 // We found a built-in operator or an overloaded operator. 13575 FunctionDecl *FnDecl = Best->Function; 13576 13577 bool IsReversed = Best->isReversed(); 13578 if (IsReversed) 13579 std::swap(Args[0], Args[1]); 13580 13581 if (FnDecl) { 13582 Expr *Base = nullptr; 13583 // We matched an overloaded operator. Build a call to that 13584 // operator. 13585 13586 OverloadedOperatorKind ChosenOp = 13587 FnDecl->getDeclName().getCXXOverloadedOperator(); 13588 13589 // C++2a [over.match.oper]p9: 13590 // If a rewritten operator== candidate is selected by overload 13591 // resolution for an operator@, its return type shall be cv bool 13592 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13593 !FnDecl->getReturnType()->isBooleanType()) { 13594 bool IsExtension = 13595 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13596 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13597 : diag::err_ovl_rewrite_equalequal_not_bool) 13598 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13599 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13600 Diag(FnDecl->getLocation(), diag::note_declared_at); 13601 if (!IsExtension) 13602 return ExprError(); 13603 } 13604 13605 if (AllowRewrittenCandidates && !IsReversed && 13606 CandidateSet.getRewriteInfo().isReversible()) { 13607 // We could have reversed this operator, but didn't. Check if some 13608 // reversed form was a viable candidate, and if so, if it had a 13609 // better conversion for either parameter. If so, this call is 13610 // formally ambiguous, and allowing it is an extension. 13611 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13612 for (OverloadCandidate &Cand : CandidateSet) { 13613 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13614 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13615 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13616 if (CompareImplicitConversionSequences( 13617 *this, OpLoc, Cand.Conversions[ArgIdx], 13618 Best->Conversions[ArgIdx]) == 13619 ImplicitConversionSequence::Better) { 13620 AmbiguousWith.push_back(Cand.Function); 13621 break; 13622 } 13623 } 13624 } 13625 } 13626 13627 if (!AmbiguousWith.empty()) { 13628 bool AmbiguousWithSelf = 13629 AmbiguousWith.size() == 1 && 13630 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13631 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13632 << BinaryOperator::getOpcodeStr(Opc) 13633 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13634 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13635 if (AmbiguousWithSelf) { 13636 Diag(FnDecl->getLocation(), 13637 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13638 } else { 13639 Diag(FnDecl->getLocation(), 13640 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13641 for (auto *F : AmbiguousWith) 13642 Diag(F->getLocation(), 13643 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13644 } 13645 } 13646 } 13647 13648 // Convert the arguments. 13649 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13650 // Best->Access is only meaningful for class members. 13651 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13652 13653 ExprResult Arg1 = 13654 PerformCopyInitialization( 13655 InitializedEntity::InitializeParameter(Context, 13656 FnDecl->getParamDecl(0)), 13657 SourceLocation(), Args[1]); 13658 if (Arg1.isInvalid()) 13659 return ExprError(); 13660 13661 ExprResult Arg0 = 13662 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13663 Best->FoundDecl, Method); 13664 if (Arg0.isInvalid()) 13665 return ExprError(); 13666 Base = Args[0] = Arg0.getAs<Expr>(); 13667 Args[1] = RHS = Arg1.getAs<Expr>(); 13668 } else { 13669 // Convert the arguments. 13670 ExprResult Arg0 = PerformCopyInitialization( 13671 InitializedEntity::InitializeParameter(Context, 13672 FnDecl->getParamDecl(0)), 13673 SourceLocation(), Args[0]); 13674 if (Arg0.isInvalid()) 13675 return ExprError(); 13676 13677 ExprResult Arg1 = 13678 PerformCopyInitialization( 13679 InitializedEntity::InitializeParameter(Context, 13680 FnDecl->getParamDecl(1)), 13681 SourceLocation(), Args[1]); 13682 if (Arg1.isInvalid()) 13683 return ExprError(); 13684 Args[0] = LHS = Arg0.getAs<Expr>(); 13685 Args[1] = RHS = Arg1.getAs<Expr>(); 13686 } 13687 13688 // Build the actual expression node. 13689 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13690 Best->FoundDecl, Base, 13691 HadMultipleCandidates, OpLoc); 13692 if (FnExpr.isInvalid()) 13693 return ExprError(); 13694 13695 // Determine the result type. 13696 QualType ResultTy = FnDecl->getReturnType(); 13697 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13698 ResultTy = ResultTy.getNonLValueExprType(Context); 13699 13700 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13701 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13702 CurFPFeatureOverrides(), Best->IsADLCandidate); 13703 13704 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13705 FnDecl)) 13706 return ExprError(); 13707 13708 ArrayRef<const Expr *> ArgsArray(Args, 2); 13709 const Expr *ImplicitThis = nullptr; 13710 // Cut off the implicit 'this'. 13711 if (isa<CXXMethodDecl>(FnDecl)) { 13712 ImplicitThis = ArgsArray[0]; 13713 ArgsArray = ArgsArray.slice(1); 13714 } 13715 13716 // Check for a self move. 13717 if (Op == OO_Equal) 13718 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13719 13720 if (ImplicitThis) { 13721 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13722 QualType ThisTypeFromDecl = Context.getPointerType( 13723 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13724 13725 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13726 ThisTypeFromDecl); 13727 } 13728 13729 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13730 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13731 VariadicDoesNotApply); 13732 13733 ExprResult R = MaybeBindToTemporary(TheCall); 13734 if (R.isInvalid()) 13735 return ExprError(); 13736 13737 R = CheckForImmediateInvocation(R, FnDecl); 13738 if (R.isInvalid()) 13739 return ExprError(); 13740 13741 // For a rewritten candidate, we've already reversed the arguments 13742 // if needed. Perform the rest of the rewrite now. 13743 if ((Best->RewriteKind & CRK_DifferentOperator) || 13744 (Op == OO_Spaceship && IsReversed)) { 13745 if (Op == OO_ExclaimEqual) { 13746 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")((ChosenOp == OO_EqualEqual && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13746, __PRETTY_FUNCTION__))
; 13747 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13748 } else { 13749 assert(ChosenOp == OO_Spaceship && "unexpected operator name")((ChosenOp == OO_Spaceship && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13749, __PRETTY_FUNCTION__))
; 13750 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13751 Expr *ZeroLiteral = 13752 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13753 13754 Sema::CodeSynthesisContext Ctx; 13755 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13756 Ctx.Entity = FnDecl; 13757 pushCodeSynthesisContext(Ctx); 13758 13759 R = CreateOverloadedBinOp( 13760 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13761 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13762 /*AllowRewrittenCandidates=*/false); 13763 13764 popCodeSynthesisContext(); 13765 } 13766 if (R.isInvalid()) 13767 return ExprError(); 13768 } else { 13769 assert(ChosenOp == Op && "unexpected operator name")((ChosenOp == Op && "unexpected operator name") ? static_cast
<void> (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13769, __PRETTY_FUNCTION__))
; 13770 } 13771 13772 // Make a note in the AST if we did any rewriting. 13773 if (Best->RewriteKind != CRK_None) 13774 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13775 13776 return R; 13777 } else { 13778 // We matched a built-in operator. Convert the arguments, then 13779 // break out so that we will build the appropriate built-in 13780 // operator node. 13781 ExprResult ArgsRes0 = PerformImplicitConversion( 13782 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13783 AA_Passing, CCK_ForBuiltinOverloadedOp); 13784 if (ArgsRes0.isInvalid()) 13785 return ExprError(); 13786 Args[0] = ArgsRes0.get(); 13787 13788 ExprResult ArgsRes1 = PerformImplicitConversion( 13789 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13790 AA_Passing, CCK_ForBuiltinOverloadedOp); 13791 if (ArgsRes1.isInvalid()) 13792 return ExprError(); 13793 Args[1] = ArgsRes1.get(); 13794 break; 13795 } 13796 } 13797 13798 case OR_No_Viable_Function: { 13799 // C++ [over.match.oper]p9: 13800 // If the operator is the operator , [...] and there are no 13801 // viable functions, then the operator is assumed to be the 13802 // built-in operator and interpreted according to clause 5. 13803 if (Opc == BO_Comma) 13804 break; 13805 13806 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13807 // compare result using '==' and '<'. 13808 if (DefaultedFn && Opc == BO_Cmp) { 13809 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13810 Args[1], DefaultedFn); 13811 if (E.isInvalid() || E.isUsable()) 13812 return E; 13813 } 13814 13815 // For class as left operand for assignment or compound assignment 13816 // operator do not fall through to handling in built-in, but report that 13817 // no overloaded assignment operator found 13818 ExprResult Result = ExprError(); 13819 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13820 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13821 Args, OpLoc); 13822 if (Args[0]->getType()->isRecordType() && 13823 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13824 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13825 << BinaryOperator::getOpcodeStr(Opc) 13826 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13827 if (Args[0]->getType()->isIncompleteType()) { 13828 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13829 << Args[0]->getType() 13830 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13831 } 13832 } else { 13833 // This is an erroneous use of an operator which can be overloaded by 13834 // a non-member function. Check for non-member operators which were 13835 // defined too late to be candidates. 13836 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13837 // FIXME: Recover by calling the found function. 13838 return ExprError(); 13839 13840 // No viable function; try to create a built-in operation, which will 13841 // produce an error. Then, show the non-viable candidates. 13842 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13843 } 13844 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13845, __PRETTY_FUNCTION__))
13845 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13845, __PRETTY_FUNCTION__))
; 13846 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13847 return Result; 13848 } 13849 13850 case OR_Ambiguous: 13851 CandidateSet.NoteCandidates( 13852 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13853 << BinaryOperator::getOpcodeStr(Opc) 13854 << Args[0]->getType() 13855 << Args[1]->getType() 13856 << Args[0]->getSourceRange() 13857 << Args[1]->getSourceRange()), 13858 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13859 OpLoc); 13860 return ExprError(); 13861 13862 case OR_Deleted: 13863 if (isImplicitlyDeleted(Best->Function)) { 13864 FunctionDecl *DeletedFD = Best->Function; 13865 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13866 if (DFK.isSpecialMember()) { 13867 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13868 << Args[0]->getType() << DFK.asSpecialMember(); 13869 } else { 13870 assert(DFK.isComparison())((DFK.isComparison()) ? static_cast<void> (0) : __assert_fail
("DFK.isComparison()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13870, __PRETTY_FUNCTION__))
; 13871 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13872 << Args[0]->getType() << DeletedFD; 13873 } 13874 13875 // The user probably meant to call this special member. Just 13876 // explain why it's deleted. 13877 NoteDeletedFunction(DeletedFD); 13878 return ExprError(); 13879 } 13880 CandidateSet.NoteCandidates( 13881 PartialDiagnosticAt( 13882 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13883 << getOperatorSpelling(Best->Function->getDeclName() 13884 .getCXXOverloadedOperator()) 13885 << Args[0]->getSourceRange() 13886 << Args[1]->getSourceRange()), 13887 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13888 OpLoc); 13889 return ExprError(); 13890 } 13891 13892 // We matched a built-in operator; build it. 13893 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13894} 13895 13896ExprResult Sema::BuildSynthesizedThreeWayComparison( 13897 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13898 FunctionDecl *DefaultedFn) { 13899 const ComparisonCategoryInfo *Info = 13900 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13901 // If we're not producing a known comparison category type, we can't 13902 // synthesize a three-way comparison. Let the caller diagnose this. 13903 if (!Info) 13904 return ExprResult((Expr*)nullptr); 13905 13906 // If we ever want to perform this synthesis more generally, we will need to 13907 // apply the temporary materialization conversion to the operands. 13908 assert(LHS->isGLValue() && RHS->isGLValue() &&((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13909, __PRETTY_FUNCTION__))
13909 "cannot use prvalue expressions more than once")((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 13909, __PRETTY_FUNCTION__))
; 13910 Expr *OrigLHS = LHS; 13911 Expr *OrigRHS = RHS; 13912 13913 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13914 // each of them multiple times below. 13915 LHS = new (Context) 13916 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13917 LHS->getObjectKind(), LHS); 13918 RHS = new (Context) 13919 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13920 RHS->getObjectKind(), RHS); 13921 13922 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13923 DefaultedFn); 13924 if (Eq.isInvalid()) 13925 return ExprError(); 13926 13927 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13928 true, DefaultedFn); 13929 if (Less.isInvalid()) 13930 return ExprError(); 13931 13932 ExprResult Greater; 13933 if (Info->isPartial()) { 13934 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13935 DefaultedFn); 13936 if (Greater.isInvalid()) 13937 return ExprError(); 13938 } 13939 13940 // Form the list of comparisons we're going to perform. 13941 struct Comparison { 13942 ExprResult Cmp; 13943 ComparisonCategoryResult Result; 13944 } Comparisons[4] = 13945 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13946 : ComparisonCategoryResult::Equivalent}, 13947 {Less, ComparisonCategoryResult::Less}, 13948 {Greater, ComparisonCategoryResult::Greater}, 13949 {ExprResult(), ComparisonCategoryResult::Unordered}, 13950 }; 13951 13952 int I = Info->isPartial() ? 3 : 2; 13953 13954 // Combine the comparisons with suitable conditional expressions. 13955 ExprResult Result; 13956 for (; I >= 0; --I) { 13957 // Build a reference to the comparison category constant. 13958 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13959 // FIXME: Missing a constant for a comparison category. Diagnose this? 13960 if (!VI) 13961 return ExprResult((Expr*)nullptr); 13962 ExprResult ThisResult = 13963 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13964 if (ThisResult.isInvalid()) 13965 return ExprError(); 13966 13967 // Build a conditional unless this is the final case. 13968 if (Result.get()) { 13969 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13970 ThisResult.get(), Result.get()); 13971 if (Result.isInvalid()) 13972 return ExprError(); 13973 } else { 13974 Result = ThisResult; 13975 } 13976 } 13977 13978 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13979 // bind the OpaqueValueExprs before they're (repeatedly) used. 13980 Expr *SyntacticForm = BinaryOperator::Create( 13981 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13982 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13983 CurFPFeatureOverrides()); 13984 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13985 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13986} 13987 13988ExprResult 13989Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13990 SourceLocation RLoc, 13991 Expr *Base, Expr *Idx) { 13992 Expr *Args[2] = { Base, Idx }; 13993 DeclarationName OpName = 13994 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13995 13996 // If either side is type-dependent, create an appropriate dependent 13997 // expression. 13998 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13999 14000 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14001 // CHECKME: no 'operator' keyword? 14002 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14003 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14004 ExprResult Fn = CreateUnresolvedLookupExpr( 14005 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14006 if (Fn.isInvalid()) 14007 return ExprError(); 14008 // Can't add any actual overloads yet 14009 14010 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14011 Context.DependentTy, VK_RValue, RLoc, 14012 CurFPFeatureOverrides()); 14013 } 14014 14015 // Handle placeholders on both operands. 14016 if (checkPlaceholderForOverload(*this, Args[0])) 14017 return ExprError(); 14018 if (checkPlaceholderForOverload(*this, Args[1])) 14019 return ExprError(); 14020 14021 // Build an empty overload set. 14022 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14023 14024 // Subscript can only be overloaded as a member function. 14025 14026 // Add operator candidates that are member functions. 14027 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14028 14029 // Add builtin operator candidates. 14030 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14031 14032 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14033 14034 // Perform overload resolution. 14035 OverloadCandidateSet::iterator Best; 14036 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14037 case OR_Success: { 14038 // We found a built-in operator or an overloaded operator. 14039 FunctionDecl *FnDecl = Best->Function; 14040 14041 if (FnDecl) { 14042 // We matched an overloaded operator. Build a call to that 14043 // operator. 14044 14045 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 14046 14047 // Convert the arguments. 14048 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14049 ExprResult Arg0 = 14050 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 14051 Best->FoundDecl, Method); 14052 if (Arg0.isInvalid()) 14053 return ExprError(); 14054 Args[0] = Arg0.get(); 14055 14056 // Convert the arguments. 14057 ExprResult InputInit 14058 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14059 Context, 14060 FnDecl->getParamDecl(0)), 14061 SourceLocation(), 14062 Args[1]); 14063 if (InputInit.isInvalid()) 14064 return ExprError(); 14065 14066 Args[1] = InputInit.getAs<Expr>(); 14067 14068 // Build the actual expression node. 14069 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14070 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14071 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14072 Best->FoundDecl, 14073 Base, 14074 HadMultipleCandidates, 14075 OpLocInfo.getLoc(), 14076 OpLocInfo.getInfo()); 14077 if (FnExpr.isInvalid()) 14078 return ExprError(); 14079 14080 // Determine the result type 14081 QualType ResultTy = FnDecl->getReturnType(); 14082 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14083 ResultTy = ResultTy.getNonLValueExprType(Context); 14084 14085 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14086 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 14087 CurFPFeatureOverrides()); 14088 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14089 return ExprError(); 14090 14091 if (CheckFunctionCall(Method, TheCall, 14092 Method->getType()->castAs<FunctionProtoType>())) 14093 return ExprError(); 14094 14095 return MaybeBindToTemporary(TheCall); 14096 } else { 14097 // We matched a built-in operator. Convert the arguments, then 14098 // break out so that we will build the appropriate built-in 14099 // operator node. 14100 ExprResult ArgsRes0 = PerformImplicitConversion( 14101 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14102 AA_Passing, CCK_ForBuiltinOverloadedOp); 14103 if (ArgsRes0.isInvalid()) 14104 return ExprError(); 14105 Args[0] = ArgsRes0.get(); 14106 14107 ExprResult ArgsRes1 = PerformImplicitConversion( 14108 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14109 AA_Passing, CCK_ForBuiltinOverloadedOp); 14110 if (ArgsRes1.isInvalid()) 14111 return ExprError(); 14112 Args[1] = ArgsRes1.get(); 14113 14114 break; 14115 } 14116 } 14117 14118 case OR_No_Viable_Function: { 14119 PartialDiagnostic PD = CandidateSet.empty() 14120 ? (PDiag(diag::err_ovl_no_oper) 14121 << Args[0]->getType() << /*subscript*/ 0 14122 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 14123 : (PDiag(diag::err_ovl_no_viable_subscript) 14124 << Args[0]->getType() << Args[0]->getSourceRange() 14125 << Args[1]->getSourceRange()); 14126 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14127 OCD_AllCandidates, Args, "[]", LLoc); 14128 return ExprError(); 14129 } 14130 14131 case OR_Ambiguous: 14132 CandidateSet.NoteCandidates( 14133 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14134 << "[]" << Args[0]->getType() 14135 << Args[1]->getType() 14136 << Args[0]->getSourceRange() 14137 << Args[1]->getSourceRange()), 14138 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14139 return ExprError(); 14140 14141 case OR_Deleted: 14142 CandidateSet.NoteCandidates( 14143 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14144 << "[]" << Args[0]->getSourceRange() 14145 << Args[1]->getSourceRange()), 14146 *this, OCD_AllCandidates, Args, "[]", LLoc); 14147 return ExprError(); 14148 } 14149 14150 // We matched a built-in operator; build it. 14151 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14152} 14153 14154/// BuildCallToMemberFunction - Build a call to a member 14155/// function. MemExpr is the expression that refers to the member 14156/// function (and includes the object parameter), Args/NumArgs are the 14157/// arguments to the function call (not including the object 14158/// parameter). The caller needs to validate that the member 14159/// expression refers to a non-static member function or an overloaded 14160/// member function. 14161ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14162 SourceLocation LParenLoc, 14163 MultiExprArg Args, 14164 SourceLocation RParenLoc, 14165 bool AllowRecovery) { 14166 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14167, __PRETTY_FUNCTION__))
14167 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14167, __PRETTY_FUNCTION__))
; 14168 14169 // Dig out the member expression. This holds both the object 14170 // argument and the member function we're referring to. 14171 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14172 14173 // Determine whether this is a call to a pointer-to-member function. 14174 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14175 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14175, __PRETTY_FUNCTION__))
; 14176 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14176, __PRETTY_FUNCTION__))
; 14177 14178 QualType fnType = 14179 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14180 14181 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14182 QualType resultType = proto->getCallResultType(Context); 14183 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14184 14185 // Check that the object type isn't more qualified than the 14186 // member function we're calling. 14187 Qualifiers funcQuals = proto->getMethodQuals(); 14188 14189 QualType objectType = op->getLHS()->getType(); 14190 if (op->getOpcode() == BO_PtrMemI) 14191 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14192 Qualifiers objectQuals = objectType.getQualifiers(); 14193 14194 Qualifiers difference = objectQuals - funcQuals; 14195 difference.removeObjCGCAttr(); 14196 difference.removeAddressSpace(); 14197 if (difference) { 14198 std::string qualsString = difference.getAsString(); 14199 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14200 << fnType.getUnqualifiedType() 14201 << qualsString 14202 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14203 } 14204 14205 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14206 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14207 CurFPFeatureOverrides(), proto->getNumParams()); 14208 14209 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14210 call, nullptr)) 14211 return ExprError(); 14212 14213 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14214 return ExprError(); 14215 14216 if (CheckOtherCall(call, proto)) 14217 return ExprError(); 14218 14219 return MaybeBindToTemporary(call); 14220 } 14221 14222 // We only try to build a recovery expr at this level if we can preserve 14223 // the return type, otherwise we return ExprError() and let the caller 14224 // recover. 14225 auto BuildRecoveryExpr = [&](QualType Type) { 14226 if (!AllowRecovery) 14227 return ExprError(); 14228 std::vector<Expr *> SubExprs = {MemExprE}; 14229 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); }); 14230 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14231 Type); 14232 }; 14233 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14234 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14235 RParenLoc, CurFPFeatureOverrides()); 14236 14237 UnbridgedCastsSet UnbridgedCasts; 14238 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14239 return ExprError(); 14240 14241 MemberExpr *MemExpr; 14242 CXXMethodDecl *Method = nullptr; 14243 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14244 NestedNameSpecifier *Qualifier = nullptr; 14245 if (isa<MemberExpr>(NakedMemExpr)) { 14246 MemExpr = cast<MemberExpr>(NakedMemExpr); 14247 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14248 FoundDecl = MemExpr->getFoundDecl(); 14249 Qualifier = MemExpr->getQualifier(); 14250 UnbridgedCasts.restore(); 14251 } else { 14252 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14253 Qualifier = UnresExpr->getQualifier(); 14254 14255 QualType ObjectType = UnresExpr->getBaseType(); 14256 Expr::Classification ObjectClassification 14257 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14258 : UnresExpr->getBase()->Classify(Context); 14259 14260 // Add overload candidates 14261 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14262 OverloadCandidateSet::CSK_Normal); 14263 14264 // FIXME: avoid copy. 14265 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14266 if (UnresExpr->hasExplicitTemplateArgs()) { 14267 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14268 TemplateArgs = &TemplateArgsBuffer; 14269 } 14270 14271 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14272 E = UnresExpr->decls_end(); I != E; ++I) { 14273 14274 NamedDecl *Func = *I; 14275 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14276 if (isa<UsingShadowDecl>(Func)) 14277 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14278 14279 14280 // Microsoft supports direct constructor calls. 14281 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14282 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14283 CandidateSet, 14284 /*SuppressUserConversions*/ false); 14285 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14286 // If explicit template arguments were provided, we can't call a 14287 // non-template member function. 14288 if (TemplateArgs) 14289 continue; 14290 14291 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14292 ObjectClassification, Args, CandidateSet, 14293 /*SuppressUserConversions=*/false); 14294 } else { 14295 AddMethodTemplateCandidate( 14296 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14297 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14298 /*SuppressUserConversions=*/false); 14299 } 14300 } 14301 14302 DeclarationName DeclName = UnresExpr->getMemberName(); 14303 14304 UnbridgedCasts.restore(); 14305 14306 OverloadCandidateSet::iterator Best; 14307 bool Succeeded = false; 14308 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14309 Best)) { 14310 case OR_Success: 14311 Method = cast<CXXMethodDecl>(Best->Function); 14312 FoundDecl = Best->FoundDecl; 14313 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14314 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14315 break; 14316 // If FoundDecl is different from Method (such as if one is a template 14317 // and the other a specialization), make sure DiagnoseUseOfDecl is 14318 // called on both. 14319 // FIXME: This would be more comprehensively addressed by modifying 14320 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14321 // being used. 14322 if (Method != FoundDecl.getDecl() && 14323 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14324 break; 14325 Succeeded = true; 14326 break; 14327 14328 case OR_No_Viable_Function: 14329 CandidateSet.NoteCandidates( 14330 PartialDiagnosticAt( 14331 UnresExpr->getMemberLoc(), 14332 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14333 << DeclName << MemExprE->getSourceRange()), 14334 *this, OCD_AllCandidates, Args); 14335 break; 14336 case OR_Ambiguous: 14337 CandidateSet.NoteCandidates( 14338 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14339 PDiag(diag::err_ovl_ambiguous_member_call) 14340 << DeclName << MemExprE->getSourceRange()), 14341 *this, OCD_AmbiguousCandidates, Args); 14342 break; 14343 case OR_Deleted: 14344 CandidateSet.NoteCandidates( 14345 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14346 PDiag(diag::err_ovl_deleted_member_call) 14347 << DeclName << MemExprE->getSourceRange()), 14348 *this, OCD_AllCandidates, Args); 14349 break; 14350 } 14351 // Overload resolution fails, try to recover. 14352 if (!Succeeded) 14353 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14354 14355 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14356 14357 // If overload resolution picked a static member, build a 14358 // non-member call based on that function. 14359 if (Method->isStatic()) { 14360 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14361 RParenLoc); 14362 } 14363 14364 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14365 } 14366 14367 QualType ResultType = Method->getReturnType(); 14368 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14369 ResultType = ResultType.getNonLValueExprType(Context); 14370 14371 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14371, __PRETTY_FUNCTION__))
; 14372 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14373 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14374 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14375 CurFPFeatureOverrides(), Proto->getNumParams()); 14376 14377 // Check for a valid return type. 14378 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14379 TheCall, Method)) 14380 return BuildRecoveryExpr(ResultType); 14381 14382 // Convert the object argument (for a non-static member function call). 14383 // We only need to do this if there was actually an overload; otherwise 14384 // it was done at lookup. 14385 if (!Method->isStatic()) { 14386 ExprResult ObjectArg = 14387 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14388 FoundDecl, Method); 14389 if (ObjectArg.isInvalid()) 14390 return ExprError(); 14391 MemExpr->setBase(ObjectArg.get()); 14392 } 14393 14394 // Convert the rest of the arguments 14395 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14396 RParenLoc)) 14397 return BuildRecoveryExpr(ResultType); 14398 14399 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14400 14401 if (CheckFunctionCall(Method, TheCall, Proto)) 14402 return ExprError(); 14403 14404 // In the case the method to call was not selected by the overloading 14405 // resolution process, we still need to handle the enable_if attribute. Do 14406 // that here, so it will not hide previous -- and more relevant -- errors. 14407 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14408 if (const EnableIfAttr *Attr = 14409 CheckEnableIf(Method, LParenLoc, Args, true)) { 14410 Diag(MemE->getMemberLoc(), 14411 diag::err_ovl_no_viable_member_function_in_call) 14412 << Method << Method->getSourceRange(); 14413 Diag(Method->getLocation(), 14414 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14415 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14416 return ExprError(); 14417 } 14418 } 14419 14420 if ((isa<CXXConstructorDecl>(CurContext) || 14421 isa<CXXDestructorDecl>(CurContext)) && 14422 TheCall->getMethodDecl()->isPure()) { 14423 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14424 14425 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14426 MemExpr->performsVirtualDispatch(getLangOpts())) { 14427 Diag(MemExpr->getBeginLoc(), 14428 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14429 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14430 << MD->getParent(); 14431 14432 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14433 if (getLangOpts().AppleKext) 14434 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14435 << MD->getParent() << MD->getDeclName(); 14436 } 14437 } 14438 14439 if (CXXDestructorDecl *DD = 14440 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14441 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14442 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14443 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14444 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14445 MemExpr->getMemberLoc()); 14446 } 14447 14448 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14449 TheCall->getMethodDecl()); 14450} 14451 14452/// BuildCallToObjectOfClassType - Build a call to an object of class 14453/// type (C++ [over.call.object]), which can end up invoking an 14454/// overloaded function call operator (@c operator()) or performing a 14455/// user-defined conversion on the object argument. 14456ExprResult 14457Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14458 SourceLocation LParenLoc, 14459 MultiExprArg Args, 14460 SourceLocation RParenLoc) { 14461 if (checkPlaceholderForOverload(*this, Obj)) 14462 return ExprError(); 14463 ExprResult Object = Obj; 14464 14465 UnbridgedCastsSet UnbridgedCasts; 14466 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14467 return ExprError(); 14468 14469 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14470, __PRETTY_FUNCTION__))
14470 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14470, __PRETTY_FUNCTION__))
; 14471 14472 // C++ [over.call.object]p1: 14473 // If the primary-expression E in the function call syntax 14474 // evaluates to a class object of type "cv T", then the set of 14475 // candidate functions includes at least the function call 14476 // operators of T. The function call operators of T are obtained by 14477 // ordinary lookup of the name operator() in the context of 14478 // (E).operator(). 14479 OverloadCandidateSet CandidateSet(LParenLoc, 14480 OverloadCandidateSet::CSK_Operator); 14481 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14482 14483 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14484 diag::err_incomplete_object_call, Object.get())) 14485 return true; 14486 14487 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14488 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14489 LookupQualifiedName(R, Record->getDecl()); 14490 R.suppressDiagnostics(); 14491 14492 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14493 Oper != OperEnd; ++Oper) { 14494 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14495 Object.get()->Classify(Context), Args, CandidateSet, 14496 /*SuppressUserConversion=*/false); 14497 } 14498 14499 // C++ [over.call.object]p2: 14500 // In addition, for each (non-explicit in C++0x) conversion function 14501 // declared in T of the form 14502 // 14503 // operator conversion-type-id () cv-qualifier; 14504 // 14505 // where cv-qualifier is the same cv-qualification as, or a 14506 // greater cv-qualification than, cv, and where conversion-type-id 14507 // denotes the type "pointer to function of (P1,...,Pn) returning 14508 // R", or the type "reference to pointer to function of 14509 // (P1,...,Pn) returning R", or the type "reference to function 14510 // of (P1,...,Pn) returning R", a surrogate call function [...] 14511 // is also considered as a candidate function. Similarly, 14512 // surrogate call functions are added to the set of candidate 14513 // functions for each conversion function declared in an 14514 // accessible base class provided the function is not hidden 14515 // within T by another intervening declaration. 14516 const auto &Conversions = 14517 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14518 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14519 NamedDecl *D = *I; 14520 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14521 if (isa<UsingShadowDecl>(D)) 14522 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14523 14524 // Skip over templated conversion functions; they aren't 14525 // surrogates. 14526 if (isa<FunctionTemplateDecl>(D)) 14527 continue; 14528 14529 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14530 if (!Conv->isExplicit()) { 14531 // Strip the reference type (if any) and then the pointer type (if 14532 // any) to get down to what might be a function type. 14533 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14534 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14535 ConvType = ConvPtrType->getPointeeType(); 14536 14537 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14538 { 14539 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14540 Object.get(), Args, CandidateSet); 14541 } 14542 } 14543 } 14544 14545 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14546 14547 // Perform overload resolution. 14548 OverloadCandidateSet::iterator Best; 14549 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14550 Best)) { 14551 case OR_Success: 14552 // Overload resolution succeeded; we'll build the appropriate call 14553 // below. 14554 break; 14555 14556 case OR_No_Viable_Function: { 14557 PartialDiagnostic PD = 14558 CandidateSet.empty() 14559 ? (PDiag(diag::err_ovl_no_oper) 14560 << Object.get()->getType() << /*call*/ 1 14561 << Object.get()->getSourceRange()) 14562 : (PDiag(diag::err_ovl_no_viable_object_call) 14563 << Object.get()->getType() << Object.get()->getSourceRange()); 14564 CandidateSet.NoteCandidates( 14565 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14566 OCD_AllCandidates, Args); 14567 break; 14568 } 14569 case OR_Ambiguous: 14570 CandidateSet.NoteCandidates( 14571 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14572 PDiag(diag::err_ovl_ambiguous_object_call) 14573 << Object.get()->getType() 14574 << Object.get()->getSourceRange()), 14575 *this, OCD_AmbiguousCandidates, Args); 14576 break; 14577 14578 case OR_Deleted: 14579 CandidateSet.NoteCandidates( 14580 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14581 PDiag(diag::err_ovl_deleted_object_call) 14582 << Object.get()->getType() 14583 << Object.get()->getSourceRange()), 14584 *this, OCD_AllCandidates, Args); 14585 break; 14586 } 14587 14588 if (Best == CandidateSet.end()) 14589 return true; 14590 14591 UnbridgedCasts.restore(); 14592 14593 if (Best->Function == nullptr) { 14594 // Since there is no function declaration, this is one of the 14595 // surrogate candidates. Dig out the conversion function. 14596 CXXConversionDecl *Conv 14597 = cast<CXXConversionDecl>( 14598 Best->Conversions[0].UserDefined.ConversionFunction); 14599 14600 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14601 Best->FoundDecl); 14602 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14603 return ExprError(); 14604 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14605, __PRETTY_FUNCTION__))
14605 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14605, __PRETTY_FUNCTION__))
; 14606 // We selected one of the surrogate functions that converts the 14607 // object parameter to a function pointer. Perform the conversion 14608 // on the object argument, then let BuildCallExpr finish the job. 14609 14610 // Create an implicit member expr to refer to the conversion operator. 14611 // and then call it. 14612 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14613 Conv, HadMultipleCandidates); 14614 if (Call.isInvalid()) 14615 return ExprError(); 14616 // Record usage of conversion in an implicit cast. 14617 Call = ImplicitCastExpr::Create( 14618 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14619 nullptr, VK_RValue, CurFPFeatureOverrides()); 14620 14621 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14622 } 14623 14624 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14625 14626 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14627 // that calls this method, using Object for the implicit object 14628 // parameter and passing along the remaining arguments. 14629 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14630 14631 // An error diagnostic has already been printed when parsing the declaration. 14632 if (Method->isInvalidDecl()) 14633 return ExprError(); 14634 14635 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14636 unsigned NumParams = Proto->getNumParams(); 14637 14638 DeclarationNameInfo OpLocInfo( 14639 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14640 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14641 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14642 Obj, HadMultipleCandidates, 14643 OpLocInfo.getLoc(), 14644 OpLocInfo.getInfo()); 14645 if (NewFn.isInvalid()) 14646 return true; 14647 14648 // The number of argument slots to allocate in the call. If we have default 14649 // arguments we need to allocate space for them as well. We additionally 14650 // need one more slot for the object parameter. 14651 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14652 14653 // Build the full argument list for the method call (the implicit object 14654 // parameter is placed at the beginning of the list). 14655 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14656 14657 bool IsError = false; 14658 14659 // Initialize the implicit object parameter. 14660 ExprResult ObjRes = 14661 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14662 Best->FoundDecl, Method); 14663 if (ObjRes.isInvalid()) 14664 IsError = true; 14665 else 14666 Object = ObjRes; 14667 MethodArgs[0] = Object.get(); 14668 14669 // Check the argument types. 14670 for (unsigned i = 0; i != NumParams; i++) { 14671 Expr *Arg; 14672 if (i < Args.size()) { 14673 Arg = Args[i]; 14674 14675 // Pass the argument. 14676 14677 ExprResult InputInit 14678 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14679 Context, 14680 Method->getParamDecl(i)), 14681 SourceLocation(), Arg); 14682 14683 IsError |= InputInit.isInvalid(); 14684 Arg = InputInit.getAs<Expr>(); 14685 } else { 14686 ExprResult DefArg 14687 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14688 if (DefArg.isInvalid()) { 14689 IsError = true; 14690 break; 14691 } 14692 14693 Arg = DefArg.getAs<Expr>(); 14694 } 14695 14696 MethodArgs[i + 1] = Arg; 14697 } 14698 14699 // If this is a variadic call, handle args passed through "...". 14700 if (Proto->isVariadic()) { 14701 // Promote the arguments (C99 6.5.2.2p7). 14702 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14703 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14704 nullptr); 14705 IsError |= Arg.isInvalid(); 14706 MethodArgs[i + 1] = Arg.get(); 14707 } 14708 } 14709 14710 if (IsError) 14711 return true; 14712 14713 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14714 14715 // Once we've built TheCall, all of the expressions are properly owned. 14716 QualType ResultTy = Method->getReturnType(); 14717 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14718 ResultTy = ResultTy.getNonLValueExprType(Context); 14719 14720 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14721 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14722 CurFPFeatureOverrides()); 14723 14724 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14725 return true; 14726 14727 if (CheckFunctionCall(Method, TheCall, Proto)) 14728 return true; 14729 14730 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14731} 14732 14733/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14734/// (if one exists), where @c Base is an expression of class type and 14735/// @c Member is the name of the member we're trying to find. 14736ExprResult 14737Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14738 bool *NoArrowOperatorFound) { 14739 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14740, __PRETTY_FUNCTION__))
14740 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 14740, __PRETTY_FUNCTION__))
; 14741 14742 if (checkPlaceholderForOverload(*this, Base)) 14743 return ExprError(); 14744 14745 SourceLocation Loc = Base->getExprLoc(); 14746 14747 // C++ [over.ref]p1: 14748 // 14749 // [...] An expression x->m is interpreted as (x.operator->())->m 14750 // for a class object x of type T if T::operator->() exists and if 14751 // the operator is selected as the best match function by the 14752 // overload resolution mechanism (13.3). 14753 DeclarationName OpName = 14754 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14755 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14756 14757 if (RequireCompleteType(Loc, Base->getType(), 14758 diag::err_typecheck_incomplete_tag, Base)) 14759 return ExprError(); 14760 14761 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14762 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14763 R.suppressDiagnostics(); 14764 14765 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14766 Oper != OperEnd; ++Oper) { 14767 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14768 None, CandidateSet, /*SuppressUserConversion=*/false); 14769 } 14770 14771 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14772 14773 // Perform overload resolution. 14774 OverloadCandidateSet::iterator Best; 14775 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14776 case OR_Success: 14777 // Overload resolution succeeded; we'll build the call below. 14778 break; 14779 14780 case OR_No_Viable_Function: { 14781 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14782 if (CandidateSet.empty()) { 14783 QualType BaseType = Base->getType(); 14784 if (NoArrowOperatorFound) { 14785 // Report this specific error to the caller instead of emitting a 14786 // diagnostic, as requested. 14787 *NoArrowOperatorFound = true; 14788 return ExprError(); 14789 } 14790 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14791 << BaseType << Base->getSourceRange(); 14792 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14793 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14794 << FixItHint::CreateReplacement(OpLoc, "."); 14795 } 14796 } else 14797 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14798 << "operator->" << Base->getSourceRange(); 14799 CandidateSet.NoteCandidates(*this, Base, Cands); 14800 return ExprError(); 14801 } 14802 case OR_Ambiguous: 14803 CandidateSet.NoteCandidates( 14804 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14805 << "->" << Base->getType() 14806 << Base->getSourceRange()), 14807 *this, OCD_AmbiguousCandidates, Base); 14808 return ExprError(); 14809 14810 case OR_Deleted: 14811 CandidateSet.NoteCandidates( 14812 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14813 << "->" << Base->getSourceRange()), 14814 *this, OCD_AllCandidates, Base); 14815 return ExprError(); 14816 } 14817 14818 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14819 14820 // Convert the object parameter. 14821 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14822 ExprResult BaseResult = 14823 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14824 Best->FoundDecl, Method); 14825 if (BaseResult.isInvalid()) 14826 return ExprError(); 14827 Base = BaseResult.get(); 14828 14829 // Build the operator call. 14830 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14831 Base, HadMultipleCandidates, OpLoc); 14832 if (FnExpr.isInvalid()) 14833 return ExprError(); 14834 14835 QualType ResultTy = Method->getReturnType(); 14836 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14837 ResultTy = ResultTy.getNonLValueExprType(Context); 14838 CXXOperatorCallExpr *TheCall = 14839 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14840 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14841 14842 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14843 return ExprError(); 14844 14845 if (CheckFunctionCall(Method, TheCall, 14846 Method->getType()->castAs<FunctionProtoType>())) 14847 return ExprError(); 14848 14849 return MaybeBindToTemporary(TheCall); 14850} 14851 14852/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14853/// a literal operator described by the provided lookup results. 14854ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14855 DeclarationNameInfo &SuffixInfo, 14856 ArrayRef<Expr*> Args, 14857 SourceLocation LitEndLoc, 14858 TemplateArgumentListInfo *TemplateArgs) { 14859 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14860 14861 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14862 OverloadCandidateSet::CSK_Normal); 14863 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14864 TemplateArgs); 14865 14866 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14867 14868 // Perform overload resolution. This will usually be trivial, but might need 14869 // to perform substitutions for a literal operator template. 14870 OverloadCandidateSet::iterator Best; 14871 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14872 case OR_Success: 14873 case OR_Deleted: 14874 break; 14875 14876 case OR_No_Viable_Function: 14877 CandidateSet.NoteCandidates( 14878 PartialDiagnosticAt(UDSuffixLoc, 14879 PDiag(diag::err_ovl_no_viable_function_in_call) 14880 << R.getLookupName()), 14881 *this, OCD_AllCandidates, Args); 14882 return ExprError(); 14883 14884 case OR_Ambiguous: 14885 CandidateSet.NoteCandidates( 14886 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14887 << R.getLookupName()), 14888 *this, OCD_AmbiguousCandidates, Args); 14889 return ExprError(); 14890 } 14891 14892 FunctionDecl *FD = Best->Function; 14893 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14894 nullptr, HadMultipleCandidates, 14895 SuffixInfo.getLoc(), 14896 SuffixInfo.getInfo()); 14897 if (Fn.isInvalid()) 14898 return true; 14899 14900 // Check the argument types. This should almost always be a no-op, except 14901 // that array-to-pointer decay is applied to string literals. 14902 Expr *ConvArgs[2]; 14903 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14904 ExprResult InputInit = PerformCopyInitialization( 14905 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14906 SourceLocation(), Args[ArgIdx]); 14907 if (InputInit.isInvalid()) 14908 return true; 14909 ConvArgs[ArgIdx] = InputInit.get(); 14910 } 14911 14912 QualType ResultTy = FD->getReturnType(); 14913 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14914 ResultTy = ResultTy.getNonLValueExprType(Context); 14915 14916 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14917 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14918 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14919 14920 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14921 return ExprError(); 14922 14923 if (CheckFunctionCall(FD, UDL, nullptr)) 14924 return ExprError(); 14925 14926 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14927} 14928 14929/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14930/// given LookupResult is non-empty, it is assumed to describe a member which 14931/// will be invoked. Otherwise, the function will be found via argument 14932/// dependent lookup. 14933/// CallExpr is set to a valid expression and FRS_Success returned on success, 14934/// otherwise CallExpr is set to ExprError() and some non-success value 14935/// is returned. 14936Sema::ForRangeStatus 14937Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14938 SourceLocation RangeLoc, 14939 const DeclarationNameInfo &NameInfo, 14940 LookupResult &MemberLookup, 14941 OverloadCandidateSet *CandidateSet, 14942 Expr *Range, ExprResult *CallExpr) { 14943 Scope *S = nullptr; 14944 14945 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14946 if (!MemberLookup.empty()) { 14947 ExprResult MemberRef = 14948 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14949 /*IsPtr=*/false, CXXScopeSpec(), 14950 /*TemplateKWLoc=*/SourceLocation(), 14951 /*FirstQualifierInScope=*/nullptr, 14952 MemberLookup, 14953 /*TemplateArgs=*/nullptr, S); 14954 if (MemberRef.isInvalid()) { 14955 *CallExpr = ExprError(); 14956 return FRS_DiagnosticIssued; 14957 } 14958 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14959 if (CallExpr->isInvalid()) { 14960 *CallExpr = ExprError(); 14961 return FRS_DiagnosticIssued; 14962 } 14963 } else { 14964 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14965 NestedNameSpecifierLoc(), 14966 NameInfo, UnresolvedSet<0>()); 14967 if (FnR.isInvalid()) 14968 return FRS_DiagnosticIssued; 14969 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14970 14971 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14972 CandidateSet, CallExpr); 14973 if (CandidateSet->empty() || CandidateSetError) { 14974 *CallExpr = ExprError(); 14975 return FRS_NoViableFunction; 14976 } 14977 OverloadCandidateSet::iterator Best; 14978 OverloadingResult OverloadResult = 14979 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14980 14981 if (OverloadResult == OR_No_Viable_Function) { 14982 *CallExpr = ExprError(); 14983 return FRS_NoViableFunction; 14984 } 14985 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14986 Loc, nullptr, CandidateSet, &Best, 14987 OverloadResult, 14988 /*AllowTypoCorrection=*/false); 14989 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14990 *CallExpr = ExprError(); 14991 return FRS_DiagnosticIssued; 14992 } 14993 } 14994 return FRS_Success; 14995} 14996 14997 14998/// FixOverloadedFunctionReference - E is an expression that refers to 14999/// a C++ overloaded function (possibly with some parentheses and 15000/// perhaps a '&' around it). We have resolved the overloaded function 15001/// to the function declaration Fn, so patch up the expression E to 15002/// refer (possibly indirectly) to Fn. Returns the new expr. 15003Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15004 FunctionDecl *Fn) { 15005 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15006 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15007 Found, Fn); 15008 if (SubExpr == PE->getSubExpr()) 15009 return PE; 15010 15011 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15012 } 15013 15014 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15015 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15016 Found, Fn); 15017 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15019, __PRETTY_FUNCTION__))
15018 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15019, __PRETTY_FUNCTION__))
15019 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15019, __PRETTY_FUNCTION__))
; 15020 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15020, __PRETTY_FUNCTION__))
; 15021 if (SubExpr == ICE->getSubExpr()) 15022 return ICE; 15023 15024 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15025 SubExpr, nullptr, ICE->getValueKind(), 15026 CurFPFeatureOverrides()); 15027 } 15028 15029 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15030 if (!GSE->isResultDependent()) { 15031 Expr *SubExpr = 15032 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15033 if (SubExpr == GSE->getResultExpr()) 15034 return GSE; 15035 15036 // Replace the resulting type information before rebuilding the generic 15037 // selection expression. 15038 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15039 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15040 unsigned ResultIdx = GSE->getResultIndex(); 15041 AssocExprs[ResultIdx] = SubExpr; 15042 15043 return GenericSelectionExpr::Create( 15044 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15045 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15046 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15047 ResultIdx); 15048 } 15049 // Rather than fall through to the unreachable, return the original generic 15050 // selection expression. 15051 return GSE; 15052 } 15053 15054 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15055 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15056, __PRETTY_FUNCTION__))
15056 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15056, __PRETTY_FUNCTION__))
; 15057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15058 if (Method->isStatic()) { 15059 // Do nothing: static member functions aren't any different 15060 // from non-member functions. 15061 } else { 15062 // Fix the subexpression, which really has to be an 15063 // UnresolvedLookupExpr holding an overloaded member function 15064 // or template. 15065 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15066 Found, Fn); 15067 if (SubExpr == UnOp->getSubExpr()) 15068 return UnOp; 15069 15070 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15071, __PRETTY_FUNCTION__))
15071 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15071, __PRETTY_FUNCTION__))
; 15072 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15073, __PRETTY_FUNCTION__))
15073 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15073, __PRETTY_FUNCTION__))
; 15074 15075 // We have taken the address of a pointer to member 15076 // function. Perform the computation here so that we get the 15077 // appropriate pointer to member type. 15078 QualType ClassType 15079 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15080 QualType MemPtrType 15081 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15082 // Under the MS ABI, lock down the inheritance model now. 15083 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15084 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15085 15086 return UnaryOperator::Create( 15087 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 15088 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15089 } 15090 } 15091 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15092 Found, Fn); 15093 if (SubExpr == UnOp->getSubExpr()) 15094 return UnOp; 15095 15096 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf, 15097 Context.getPointerType(SubExpr->getType()), 15098 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), 15099 false, CurFPFeatureOverrides()); 15100 } 15101 15102 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15103 // FIXME: avoid copy. 15104 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15105 if (ULE->hasExplicitTemplateArgs()) { 15106 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15107 TemplateArgs = &TemplateArgsBuffer; 15108 } 15109 15110 DeclRefExpr *DRE = 15111 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15112 ULE->getQualifierLoc(), Found.getDecl(), 15113 ULE->getTemplateKeywordLoc(), TemplateArgs); 15114 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15115 return DRE; 15116 } 15117 15118 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15119 // FIXME: avoid copy. 15120 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15121 if (MemExpr->hasExplicitTemplateArgs()) { 15122 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15123 TemplateArgs = &TemplateArgsBuffer; 15124 } 15125 15126 Expr *Base; 15127 15128 // If we're filling in a static method where we used to have an 15129 // implicit member access, rewrite to a simple decl ref. 15130 if (MemExpr->isImplicitAccess()) { 15131 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15132 DeclRefExpr *DRE = BuildDeclRefExpr( 15133 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15134 MemExpr->getQualifierLoc(), Found.getDecl(), 15135 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15136 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15137 return DRE; 15138 } else { 15139 SourceLocation Loc = MemExpr->getMemberLoc(); 15140 if (MemExpr->getQualifier()) 15141 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15142 Base = 15143 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15144 } 15145 } else 15146 Base = MemExpr->getBase(); 15147 15148 ExprValueKind valueKind; 15149 QualType type; 15150 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15151 valueKind = VK_LValue; 15152 type = Fn->getType(); 15153 } else { 15154 valueKind = VK_RValue; 15155 type = Context.BoundMemberTy; 15156 } 15157 15158 return BuildMemberExpr( 15159 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15160 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15161 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15162 type, valueKind, OK_Ordinary, TemplateArgs); 15163 } 15164 15165 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaOverload.cpp"
, 15165)
; 15166} 15167 15168ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15169 DeclAccessPair Found, 15170 FunctionDecl *Fn) { 15171 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15172}

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class TemplateParameterList;
65class Type;
66
67enum {
68 TypeAlignmentInBits = 4,
69 TypeAlignment = 1 << TypeAlignmentInBits
70};
71
72namespace serialization {
73 template <class T> class AbstractTypeReader;
74 template <class T> class AbstractTypeWriter;
75}
76
77} // namespace clang
78
79namespace llvm {
80
81 template <typename T>
82 struct PointerLikeTypeTraits;
83 template<>
84 struct PointerLikeTypeTraits< ::clang::Type*> {
85 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87 static inline ::clang::Type *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::Type*>(P);
89 }
90
91 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92 };
93
94 template<>
95 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
96 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99 return static_cast< ::clang::ExtQuals*>(P);
100 }
101
102 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103 };
104
105} // namespace llvm
106
107namespace clang {
108
109class ASTContext;
110template <typename> class CanQual;
111class CXXRecordDecl;
112class DeclContext;
113class EnumDecl;
114class Expr;
115class ExtQualsTypeCommonBase;
116class FunctionDecl;
117class IdentifierInfo;
118class NamedDecl;
119class ObjCInterfaceDecl;
120class ObjCProtocolDecl;
121class ObjCTypeParamDecl;
122struct PrintingPolicy;
123class RecordDecl;
124class Stmt;
125class TagDecl;
126class TemplateArgument;
127class TemplateArgumentListInfo;
128class TemplateArgumentLoc;
129class TemplateTypeParmDecl;
130class TypedefNameDecl;
131class UnresolvedUsingTypenameDecl;
132
133using CanQualType = CanQual<Type>;
134
135// Provide forward declarations for all of the *Type classes.
136#define TYPE(Class, Base) class Class##Type;
137#include "clang/AST/TypeNodes.inc"
138
139/// The collection of all-type qualifiers we support.
140/// Clang supports five independent qualifiers:
141/// * C99: const, volatile, and restrict
142/// * MS: __unaligned
143/// * Embedded C (TR18037): address spaces
144/// * Objective C: the GC attributes (none, weak, or strong)
145class Qualifiers {
146public:
147 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148 Const = 0x1,
149 Restrict = 0x2,
150 Volatile = 0x4,
151 CVRMask = Const | Volatile | Restrict
152 };
153
154 enum GC {
155 GCNone = 0,
156 Weak,
157 Strong
158 };
159
160 enum ObjCLifetime {
161 /// There is no lifetime qualification on this type.
162 OCL_None,
163
164 /// This object can be modified without requiring retains or
165 /// releases.
166 OCL_ExplicitNone,
167
168 /// Assigning into this object requires the old value to be
169 /// released and the new value to be retained. The timing of the
170 /// release of the old value is inexact: it may be moved to
171 /// immediately after the last known point where the value is
172 /// live.
173 OCL_Strong,
174
175 /// Reading or writing from this object requires a barrier call.
176 OCL_Weak,
177
178 /// Assigning into this object requires a lifetime extension.
179 OCL_Autoreleasing
180 };
181
182 enum {
183 /// The maximum supported address space number.
184 /// 23 bits should be enough for anyone.
185 MaxAddressSpace = 0x7fffffu,
186
187 /// The width of the "fast" qualifier mask.
188 FastWidth = 3,
189
190 /// The fast qualifier mask.
191 FastMask = (1 << FastWidth) - 1
192 };
193
194 /// Returns the common set of qualifiers while removing them from
195 /// the given sets.
196 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
197 // If both are only CVR-qualified, bit operations are sufficient.
198 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
199 Qualifiers Q;
200 Q.Mask = L.Mask & R.Mask;
201 L.Mask &= ~Q.Mask;
202 R.Mask &= ~Q.Mask;
203 return Q;
204 }
205
206 Qualifiers Q;
207 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208 Q.addCVRQualifiers(CommonCRV);
209 L.removeCVRQualifiers(CommonCRV);
210 R.removeCVRQualifiers(CommonCRV);
211
212 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
213 Q.setObjCGCAttr(L.getObjCGCAttr());
214 L.removeObjCGCAttr();
215 R.removeObjCGCAttr();
216 }
217
218 if (L.getObjCLifetime() == R.getObjCLifetime()) {
219 Q.setObjCLifetime(L.getObjCLifetime());
220 L.removeObjCLifetime();
221 R.removeObjCLifetime();
222 }
223
224 if (L.getAddressSpace() == R.getAddressSpace()) {
225 Q.setAddressSpace(L.getAddressSpace());
226 L.removeAddressSpace();
227 R.removeAddressSpace();
228 }
229 return Q;
230 }
231
232 static Qualifiers fromFastMask(unsigned Mask) {
233 Qualifiers Qs;
234 Qs.addFastQualifiers(Mask);
235 return Qs;
236 }
237
238 static Qualifiers fromCVRMask(unsigned CVR) {
239 Qualifiers Qs;
240 Qs.addCVRQualifiers(CVR);
241 return Qs;
242 }
243
244 static Qualifiers fromCVRUMask(unsigned CVRU) {
245 Qualifiers Qs;
246 Qs.addCVRUQualifiers(CVRU);
247 return Qs;
248 }
249
250 // Deserialize qualifiers from an opaque representation.
251 static Qualifiers fromOpaqueValue(unsigned opaque) {
252 Qualifiers Qs;
253 Qs.Mask = opaque;
254 return Qs;
255 }
256
257 // Serialize these qualifiers into an opaque representation.
258 unsigned getAsOpaqueValue() const {
259 return Mask;
260 }
261
262 bool hasConst() const { return Mask & Const; }
263 bool hasOnlyConst() const { return Mask == Const; }
264 void removeConst() { Mask &= ~Const; }
265 void addConst() { Mask |= Const; }
266
267 bool hasVolatile() const { return Mask & Volatile; }
268 bool hasOnlyVolatile() const { return Mask == Volatile; }
269 void removeVolatile() { Mask &= ~Volatile; }
270 void addVolatile() { Mask |= Volatile; }
271
272 bool hasRestrict() const { return Mask & Restrict; }
273 bool hasOnlyRestrict() const { return Mask == Restrict; }
274 void removeRestrict() { Mask &= ~Restrict; }
275 void addRestrict() { Mask |= Restrict; }
276
277 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280
281 void setCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 282, __PRETTY_FUNCTION__))
;
283 Mask = (Mask & ~CVRMask) | mask;
284 }
285 void removeCVRQualifiers(unsigned mask) {
286 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 286, __PRETTY_FUNCTION__))
;
287 Mask &= ~mask;
288 }
289 void removeCVRQualifiers() {
290 removeCVRQualifiers(CVRMask);
291 }
292 void addCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 293, __PRETTY_FUNCTION__))
;
294 Mask |= mask;
295 }
296 void addCVRUQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 297, __PRETTY_FUNCTION__))
;
298 Mask |= mask;
299 }
300
301 bool hasUnaligned() const { return Mask & UMask; }
302 void setUnaligned(bool flag) {
303 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304 }
305 void removeUnaligned() { Mask &= ~UMask; }
306 void addUnaligned() { Mask |= UMask; }
307
308 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310 void setObjCGCAttr(GC type) {
311 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312 }
313 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314 void addObjCGCAttr(GC type) {
315 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 315, __PRETTY_FUNCTION__))
;
316 setObjCGCAttr(type);
317 }
318 Qualifiers withoutObjCGCAttr() const {
319 Qualifiers qs = *this;
320 qs.removeObjCGCAttr();
321 return qs;
322 }
323 Qualifiers withoutObjCLifetime() const {
324 Qualifiers qs = *this;
325 qs.removeObjCLifetime();
326 return qs;
327 }
328 Qualifiers withoutAddressSpace() const {
329 Qualifiers qs = *this;
330 qs.removeAddressSpace();
331 return qs;
332 }
333
334 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
335 ObjCLifetime getObjCLifetime() const {
336 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337 }
338 void setObjCLifetime(ObjCLifetime type) {
339 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340 }
341 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
342 void addObjCLifetime(ObjCLifetime type) {
343 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 344, __PRETTY_FUNCTION__))
;
345 Mask |= (type << LifetimeShift);
346 }
347
348 /// True if the lifetime is neither None or ExplicitNone.
349 bool hasNonTrivialObjCLifetime() const {
350 ObjCLifetime lifetime = getObjCLifetime();
351 return (lifetime > OCL_ExplicitNone);
352 }
353
354 /// True if the lifetime is either strong or weak.
355 bool hasStrongOrWeakObjCLifetime() const {
356 ObjCLifetime lifetime = getObjCLifetime();
357 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
358 }
359
360 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
361 LangAS getAddressSpace() const {
362 return static_cast<LangAS>(Mask >> AddressSpaceShift);
363 }
364 bool hasTargetSpecificAddressSpace() const {
365 return isTargetAddressSpace(getAddressSpace());
366 }
367 /// Get the address space attribute value to be printed by diagnostics.
368 unsigned getAddressSpaceAttributePrintValue() const {
369 auto Addr = getAddressSpace();
370 // This function is not supposed to be used with language specific
371 // address spaces. If that happens, the diagnostic message should consider
372 // printing the QualType instead of the address space value.
373 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 373, __PRETTY_FUNCTION__))
;
374 if (Addr != LangAS::Default)
375 return toTargetAddressSpace(Addr);
376 // TODO: The diagnostic messages where Addr may be 0 should be fixed
377 // since it cannot differentiate the situation where 0 denotes the default
378 // address space or user specified __attribute__((address_space(0))).
379 return 0;
380 }
381 void setAddressSpace(LangAS space) {
382 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 382, __PRETTY_FUNCTION__))
;
383 Mask = (Mask & ~AddressSpaceMask)
384 | (((uint32_t) space) << AddressSpaceShift);
385 }
386 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
387 void addAddressSpace(LangAS space) {
388 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 388, __PRETTY_FUNCTION__))
;
389 setAddressSpace(space);
390 }
391
392 // Fast qualifiers are those that can be allocated directly
393 // on a QualType object.
394 bool hasFastQualifiers() const { return getFastQualifiers(); }
395 unsigned getFastQualifiers() const { return Mask & FastMask; }
396 void setFastQualifiers(unsigned mask) {
397 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 397, __PRETTY_FUNCTION__))
;
398 Mask = (Mask & ~FastMask) | mask;
399 }
400 void removeFastQualifiers(unsigned mask) {
401 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 401, __PRETTY_FUNCTION__))
;
402 Mask &= ~mask;
403 }
404 void removeFastQualifiers() {
405 removeFastQualifiers(FastMask);
406 }
407 void addFastQualifiers(unsigned mask) {
408 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 408, __PRETTY_FUNCTION__))
;
409 Mask |= mask;
410 }
411
412 /// Return true if the set contains any qualifiers which require an ExtQuals
413 /// node to be allocated.
414 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
415 Qualifiers getNonFastQualifiers() const {
416 Qualifiers Quals = *this;
417 Quals.setFastQualifiers(0);
418 return Quals;
419 }
420
421 /// Return true if the set contains any qualifiers.
422 bool hasQualifiers() const { return Mask; }
423 bool empty() const { return !Mask; }
424
425 /// Add the qualifiers from the given set to this set.
426 void addQualifiers(Qualifiers Q) {
427 // If the other set doesn't have any non-boolean qualifiers, just
428 // bit-or it in.
429 if (!(Q.Mask & ~CVRMask))
430 Mask |= Q.Mask;
431 else {
432 Mask |= (Q.Mask & CVRMask);
433 if (Q.hasAddressSpace())
434 addAddressSpace(Q.getAddressSpace());
435 if (Q.hasObjCGCAttr())
436 addObjCGCAttr(Q.getObjCGCAttr());
437 if (Q.hasObjCLifetime())
438 addObjCLifetime(Q.getObjCLifetime());
439 }
440 }
441
442 /// Remove the qualifiers from the given set from this set.
443 void removeQualifiers(Qualifiers Q) {
444 // If the other set doesn't have any non-boolean qualifiers, just
445 // bit-and the inverse in.
446 if (!(Q.Mask & ~CVRMask))
447 Mask &= ~Q.Mask;
448 else {
449 Mask &= ~(Q.Mask & CVRMask);
450 if (getObjCGCAttr() == Q.getObjCGCAttr())
451 removeObjCGCAttr();
452 if (getObjCLifetime() == Q.getObjCLifetime())
453 removeObjCLifetime();
454 if (getAddressSpace() == Q.getAddressSpace())
455 removeAddressSpace();
456 }
457 }
458
459 /// Add the qualifiers from the given set to this set, given that
460 /// they don't conflict.
461 void addConsistentQualifiers(Qualifiers qs) {
462 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 463, __PRETTY_FUNCTION__))
463 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 463, __PRETTY_FUNCTION__))
;
464 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 465, __PRETTY_FUNCTION__))
465 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 465, __PRETTY_FUNCTION__))
;
466 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 467, __PRETTY_FUNCTION__))
467 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 467, __PRETTY_FUNCTION__))
;
468 Mask |= qs.Mask;
469 }
470
471 /// Returns true if address space A is equal to or a superset of B.
472 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473 /// overlapping address spaces.
474 /// CL1.1 or CL1.2:
475 /// every address space is a superset of itself.
476 /// CL2.0 adds:
477 /// __generic is a superset of any address space except for __constant.
478 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
479 // Address spaces must match exactly.
480 return A == B ||
481 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482 // for __constant can be used as __generic.
483 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
484 // We also define global_device and global_host address spaces,
485 // to distinguish global pointers allocated on host from pointers
486 // allocated on device, which are a subset of __global.
487 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
488 B == LangAS::opencl_global_host)) ||
489 // Consider pointer size address spaces to be equivalent to default.
490 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
491 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
492 }
493
494 /// Returns true if the address space in these qualifiers is equal to or
495 /// a superset of the address space in the argument qualifiers.
496 bool isAddressSpaceSupersetOf(Qualifiers other) const {
497 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
498 }
499
500 /// Determines if these qualifiers compatibly include another set.
501 /// Generally this answers the question of whether an object with the other
502 /// qualifiers can be safely used as an object with these qualifiers.
503 bool compatiblyIncludes(Qualifiers other) const {
504 return isAddressSpaceSupersetOf(other) &&
505 // ObjC GC qualifiers can match, be added, or be removed, but can't
506 // be changed.
507 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
508 !other.hasObjCGCAttr()) &&
509 // ObjC lifetime qualifiers must match exactly.
510 getObjCLifetime() == other.getObjCLifetime() &&
511 // CVR qualifiers may subset.
512 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
513 // U qualifier may superset.
514 (!other.hasUnaligned() || hasUnaligned());
515 }
516
517 /// Determines if these qualifiers compatibly include another set of
518 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
519 ///
520 /// One set of Objective-C lifetime qualifiers compatibly includes the other
521 /// if the lifetime qualifiers match, or if both are non-__weak and the
522 /// including set also contains the 'const' qualifier, or both are non-__weak
523 /// and one is None (which can only happen in non-ARC modes).
524 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
525 if (getObjCLifetime() == other.getObjCLifetime())
526 return true;
527
528 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
529 return false;
530
531 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
532 return true;
533
534 return hasConst();
535 }
536
537 /// Determine whether this set of qualifiers is a strict superset of
538 /// another set of qualifiers, not considering qualifier compatibility.
539 bool isStrictSupersetOf(Qualifiers Other) const;
540
541 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
542 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
543
544 explicit operator bool() const { return hasQualifiers(); }
545
546 Qualifiers &operator+=(Qualifiers R) {
547 addQualifiers(R);
548 return *this;
549 }
550
551 // Union two qualifier sets. If an enumerated qualifier appears
552 // in both sets, use the one from the right.
553 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
554 L += R;
555 return L;
556 }
557
558 Qualifiers &operator-=(Qualifiers R) {
559 removeQualifiers(R);
560 return *this;
561 }
562
563 /// Compute the difference between two qualifier sets.
564 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
565 L -= R;
566 return L;
567 }
568
569 std::string getAsString() const;
570 std::string getAsString(const PrintingPolicy &Policy) const;
571
572 static std::string getAddrSpaceAsString(LangAS AS);
573
574 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
575 void print(raw_ostream &OS, const PrintingPolicy &Policy,
576 bool appendSpaceIfNonEmpty = false) const;
577
578 void Profile(llvm::FoldingSetNodeID &ID) const {
579 ID.AddInteger(Mask);
580 }
581
582private:
583 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
584 // |C R V|U|GCAttr|Lifetime|AddressSpace|
585 uint32_t Mask = 0;
586
587 static const uint32_t UMask = 0x8;
588 static const uint32_t UShift = 3;
589 static const uint32_t GCAttrMask = 0x30;
590 static const uint32_t GCAttrShift = 4;
591 static const uint32_t LifetimeMask = 0x1C0;
592 static const uint32_t LifetimeShift = 6;
593 static const uint32_t AddressSpaceMask =
594 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
595 static const uint32_t AddressSpaceShift = 9;
596};
597
598/// A std::pair-like structure for storing a qualified type split
599/// into its local qualifiers and its locally-unqualified type.
600struct SplitQualType {
601 /// The locally-unqualified type.
602 const Type *Ty = nullptr;
603
604 /// The local qualifiers.
605 Qualifiers Quals;
606
607 SplitQualType() = default;
608 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
609
610 SplitQualType getSingleStepDesugaredType() const; // end of this file
611
612 // Make std::tie work.
613 std::pair<const Type *,Qualifiers> asPair() const {
614 return std::pair<const Type *, Qualifiers>(Ty, Quals);
615 }
616
617 friend bool operator==(SplitQualType a, SplitQualType b) {
618 return a.Ty == b.Ty && a.Quals == b.Quals;
619 }
620 friend bool operator!=(SplitQualType a, SplitQualType b) {
621 return a.Ty != b.Ty || a.Quals != b.Quals;
622 }
623};
624
625/// The kind of type we are substituting Objective-C type arguments into.
626///
627/// The kind of substitution affects the replacement of type parameters when
628/// no concrete type information is provided, e.g., when dealing with an
629/// unspecialized type.
630enum class ObjCSubstitutionContext {
631 /// An ordinary type.
632 Ordinary,
633
634 /// The result type of a method or function.
635 Result,
636
637 /// The parameter type of a method or function.
638 Parameter,
639
640 /// The type of a property.
641 Property,
642
643 /// The superclass of a type.
644 Superclass,
645};
646
647/// A (possibly-)qualified type.
648///
649/// For efficiency, we don't store CV-qualified types as nodes on their
650/// own: instead each reference to a type stores the qualifiers. This
651/// greatly reduces the number of nodes we need to allocate for types (for
652/// example we only need one for 'int', 'const int', 'volatile int',
653/// 'const volatile int', etc).
654///
655/// As an added efficiency bonus, instead of making this a pair, we
656/// just store the two bits we care about in the low bits of the
657/// pointer. To handle the packing/unpacking, we make QualType be a
658/// simple wrapper class that acts like a smart pointer. A third bit
659/// indicates whether there are extended qualifiers present, in which
660/// case the pointer points to a special structure.
661class QualType {
662 friend class QualifierCollector;
663
664 // Thankfully, these are efficiently composable.
665 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
666 Qualifiers::FastWidth> Value;
667
668 const ExtQuals *getExtQualsUnsafe() const {
669 return Value.getPointer().get<const ExtQuals*>();
670 }
671
672 const Type *getTypePtrUnsafe() const {
673 return Value.getPointer().get<const Type*>();
674 }
675
676 const ExtQualsTypeCommonBase *getCommonPtr() const {
677 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 677, __PRETTY_FUNCTION__))
;
678 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
679 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
680 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
681 }
682
683public:
684 QualType() = default;
685 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
686 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
687
688 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
689 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
690
691 /// Retrieves a pointer to the underlying (unqualified) type.
692 ///
693 /// This function requires that the type not be NULL. If the type might be
694 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
695 const Type *getTypePtr() const;
696
697 const Type *getTypePtrOrNull() const;
698
699 /// Retrieves a pointer to the name of the base type.
700 const IdentifierInfo *getBaseTypeIdentifier() const;
701
702 /// Divides a QualType into its unqualified type and a set of local
703 /// qualifiers.
704 SplitQualType split() const;
705
706 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
707
708 static QualType getFromOpaquePtr(const void *Ptr) {
709 QualType T;
710 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
711 return T;
712 }
713
714 const Type &operator*() const {
715 return *getTypePtr();
716 }
717
718 const Type *operator->() const {
719 return getTypePtr();
720 }
721
722 bool isCanonical() const;
723 bool isCanonicalAsParam() const;
724
725 /// Return true if this QualType doesn't point to a type yet.
726 bool isNull() const {
727 return Value.getPointer().isNull();
728 }
729
730 /// Determine whether this particular QualType instance has the
731 /// "const" qualifier set, without looking through typedefs that may have
732 /// added "const" at a different level.
733 bool isLocalConstQualified() const {
734 return (getLocalFastQualifiers() & Qualifiers::Const);
735 }
736
737 /// Determine whether this type is const-qualified.
738 bool isConstQualified() const;
739
740 /// Determine whether this particular QualType instance has the
741 /// "restrict" qualifier set, without looking through typedefs that may have
742 /// added "restrict" at a different level.
743 bool isLocalRestrictQualified() const {
744 return (getLocalFastQualifiers() & Qualifiers::Restrict);
745 }
746
747 /// Determine whether this type is restrict-qualified.
748 bool isRestrictQualified() const;
749
750 /// Determine whether this particular QualType instance has the
751 /// "volatile" qualifier set, without looking through typedefs that may have
752 /// added "volatile" at a different level.
753 bool isLocalVolatileQualified() const {
754 return (getLocalFastQualifiers() & Qualifiers::Volatile);
755 }
756
757 /// Determine whether this type is volatile-qualified.
758 bool isVolatileQualified() const;
759
760 /// Determine whether this particular QualType instance has any
761 /// qualifiers, without looking through any typedefs that might add
762 /// qualifiers at a different level.
763 bool hasLocalQualifiers() const {
764 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
765 }
766
767 /// Determine whether this type has any qualifiers.
768 bool hasQualifiers() const;
769
770 /// Determine whether this particular QualType instance has any
771 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
772 /// instance.
773 bool hasLocalNonFastQualifiers() const {
774 return Value.getPointer().is<const ExtQuals*>();
775 }
776
777 /// Retrieve the set of qualifiers local to this particular QualType
778 /// instance, not including any qualifiers acquired through typedefs or
779 /// other sugar.
780 Qualifiers getLocalQualifiers() const;
781
782 /// Retrieve the set of qualifiers applied to this type.
783 Qualifiers getQualifiers() const;
784
785 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
786 /// local to this particular QualType instance, not including any qualifiers
787 /// acquired through typedefs or other sugar.
788 unsigned getLocalCVRQualifiers() const {
789 return getLocalFastQualifiers();
790 }
791
792 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
793 /// applied to this type.
794 unsigned getCVRQualifiers() const;
795
796 bool isConstant(const ASTContext& Ctx) const {
797 return QualType::isConstant(*this, Ctx);
798 }
799
800 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
801 bool isPODType(const ASTContext &Context) const;
802
803 /// Return true if this is a POD type according to the rules of the C++98
804 /// standard, regardless of the current compilation's language.
805 bool isCXX98PODType(const ASTContext &Context) const;
806
807 /// Return true if this is a POD type according to the more relaxed rules
808 /// of the C++11 standard, regardless of the current compilation's language.
809 /// (C++0x [basic.types]p9). Note that, unlike
810 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
811 bool isCXX11PODType(const ASTContext &Context) const;
812
813 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
814 bool isTrivialType(const ASTContext &Context) const;
815
816 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
817 bool isTriviallyCopyableType(const ASTContext &Context) const;
818
819
820 /// Returns true if it is a class and it might be dynamic.
821 bool mayBeDynamicClass() const;
822
823 /// Returns true if it is not a class or if the class might not be dynamic.
824 bool mayBeNotDynamicClass() const;
825
826 // Don't promise in the API that anything besides 'const' can be
827 // easily added.
828
829 /// Add the `const` type qualifier to this QualType.
830 void addConst() {
831 addFastQualifiers(Qualifiers::Const);
832 }
833 QualType withConst() const {
834 return withFastQualifiers(Qualifiers::Const);
835 }
836
837 /// Add the `volatile` type qualifier to this QualType.
838 void addVolatile() {
839 addFastQualifiers(Qualifiers::Volatile);
840 }
841 QualType withVolatile() const {
842 return withFastQualifiers(Qualifiers::Volatile);
843 }
844
845 /// Add the `restrict` qualifier to this QualType.
846 void addRestrict() {
847 addFastQualifiers(Qualifiers::Restrict);
848 }
849 QualType withRestrict() const {
850 return withFastQualifiers(Qualifiers::Restrict);
851 }
852
853 QualType withCVRQualifiers(unsigned CVR) const {
854 return withFastQualifiers(CVR);
855 }
856
857 void addFastQualifiers(unsigned TQs) {
858 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 859, __PRETTY_FUNCTION__))
859 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 859, __PRETTY_FUNCTION__))
;
860 Value.setInt(Value.getInt() | TQs);
861 }
862
863 void removeLocalConst();
864 void removeLocalVolatile();
865 void removeLocalRestrict();
866 void removeLocalCVRQualifiers(unsigned Mask);
867
868 void removeLocalFastQualifiers() { Value.setInt(0); }
869 void removeLocalFastQualifiers(unsigned Mask) {
870 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 870, __PRETTY_FUNCTION__))
;
871 Value.setInt(Value.getInt() & ~Mask);
872 }
873
874 // Creates a type with the given qualifiers in addition to any
875 // qualifiers already on this type.
876 QualType withFastQualifiers(unsigned TQs) const {
877 QualType T = *this;
878 T.addFastQualifiers(TQs);
879 return T;
880 }
881
882 // Creates a type with exactly the given fast qualifiers, removing
883 // any existing fast qualifiers.
884 QualType withExactLocalFastQualifiers(unsigned TQs) const {
885 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
886 }
887
888 // Removes fast qualifiers, but leaves any extended qualifiers in place.
889 QualType withoutLocalFastQualifiers() const {
890 QualType T = *this;
891 T.removeLocalFastQualifiers();
892 return T;
893 }
894
895 QualType getCanonicalType() const;
896
897 /// Return this type with all of the instance-specific qualifiers
898 /// removed, but without removing any qualifiers that may have been applied
899 /// through typedefs.
900 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
901
902 /// Retrieve the unqualified variant of the given type,
903 /// removing as little sugar as possible.
904 ///
905 /// This routine looks through various kinds of sugar to find the
906 /// least-desugared type that is unqualified. For example, given:
907 ///
908 /// \code
909 /// typedef int Integer;
910 /// typedef const Integer CInteger;
911 /// typedef CInteger DifferenceType;
912 /// \endcode
913 ///
914 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
915 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
916 ///
917 /// The resulting type might still be qualified if it's sugar for an array
918 /// type. To strip qualifiers even from within a sugared array type, use
919 /// ASTContext::getUnqualifiedArrayType.
920 inline QualType getUnqualifiedType() const;
921
922 /// Retrieve the unqualified variant of the given type, removing as little
923 /// sugar as possible.
924 ///
925 /// Like getUnqualifiedType(), but also returns the set of
926 /// qualifiers that were built up.
927 ///
928 /// The resulting type might still be qualified if it's sugar for an array
929 /// type. To strip qualifiers even from within a sugared array type, use
930 /// ASTContext::getUnqualifiedArrayType.
931 inline SplitQualType getSplitUnqualifiedType() const;
932
933 /// Determine whether this type is more qualified than the other
934 /// given type, requiring exact equality for non-CVR qualifiers.
935 bool isMoreQualifiedThan(QualType Other) const;
936
937 /// Determine whether this type is at least as qualified as the other
938 /// given type, requiring exact equality for non-CVR qualifiers.
939 bool isAtLeastAsQualifiedAs(QualType Other) const;
940
941 QualType getNonReferenceType() const;
942
943 /// Determine the type of a (typically non-lvalue) expression with the
944 /// specified result type.
945 ///
946 /// This routine should be used for expressions for which the return type is
947 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
948 /// an lvalue. It removes a top-level reference (since there are no
949 /// expressions of reference type) and deletes top-level cvr-qualifiers
950 /// from non-class types (in C++) or all types (in C).
951 QualType getNonLValueExprType(const ASTContext &Context) const;
952
953 /// Remove an outer pack expansion type (if any) from this type. Used as part
954 /// of converting the type of a declaration to the type of an expression that
955 /// references that expression. It's meaningless for an expression to have a
956 /// pack expansion type.
957 QualType getNonPackExpansionType() const;
958
959 /// Return the specified type with any "sugar" removed from
960 /// the type. This takes off typedefs, typeof's etc. If the outer level of
961 /// the type is already concrete, it returns it unmodified. This is similar
962 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
963 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
964 /// concrete.
965 ///
966 /// Qualifiers are left in place.
967 QualType getDesugaredType(const ASTContext &Context) const {
968 return getDesugaredType(*this, Context);
969 }
970
971 SplitQualType getSplitDesugaredType() const {
972 return getSplitDesugaredType(*this);
973 }
974
975 /// Return the specified type with one level of "sugar" removed from
976 /// the type.
977 ///
978 /// This routine takes off the first typedef, typeof, etc. If the outer level
979 /// of the type is already concrete, it returns it unmodified.
980 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
981 return getSingleStepDesugaredTypeImpl(*this, Context);
982 }
983
984 /// Returns the specified type after dropping any
985 /// outer-level parentheses.
986 QualType IgnoreParens() const {
987 if (isa<ParenType>(*this))
988 return QualType::IgnoreParens(*this);
989 return *this;
990 }
991
992 /// Indicate whether the specified types and qualifiers are identical.
993 friend bool operator==(const QualType &LHS, const QualType &RHS) {
994 return LHS.Value == RHS.Value;
995 }
996 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
997 return LHS.Value != RHS.Value;
998 }
999 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1000 return LHS.Value < RHS.Value;
1001 }
1002
1003 static std::string getAsString(SplitQualType split,
1004 const PrintingPolicy &Policy) {
1005 return getAsString(split.Ty, split.Quals, Policy);
1006 }
1007 static std::string getAsString(const Type *ty, Qualifiers qs,
1008 const PrintingPolicy &Policy);
1009
1010 std::string getAsString() const;
1011 std::string getAsString(const PrintingPolicy &Policy) const;
1012
1013 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1014 const Twine &PlaceHolder = Twine(),
1015 unsigned Indentation = 0) const;
1016
1017 static void print(SplitQualType split, raw_ostream &OS,
1018 const PrintingPolicy &policy, const Twine &PlaceHolder,
1019 unsigned Indentation = 0) {
1020 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1021 }
1022
1023 static void print(const Type *ty, Qualifiers qs,
1024 raw_ostream &OS, const PrintingPolicy &policy,
1025 const Twine &PlaceHolder,
1026 unsigned Indentation = 0);
1027
1028 void getAsStringInternal(std::string &Str,
1029 const PrintingPolicy &Policy) const;
1030
1031 static void getAsStringInternal(SplitQualType split, std::string &out,
1032 const PrintingPolicy &policy) {
1033 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1034 }
1035
1036 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1037 std::string &out,
1038 const PrintingPolicy &policy);
1039
1040 class StreamedQualTypeHelper {
1041 const QualType &T;
1042 const PrintingPolicy &Policy;
1043 const Twine &PlaceHolder;
1044 unsigned Indentation;
1045
1046 public:
1047 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1048 const Twine &PlaceHolder, unsigned Indentation)
1049 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1050 Indentation(Indentation) {}
1051
1052 friend raw_ostream &operator<<(raw_ostream &OS,
1053 const StreamedQualTypeHelper &SQT) {
1054 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1055 return OS;
1056 }
1057 };
1058
1059 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1060 const Twine &PlaceHolder = Twine(),
1061 unsigned Indentation = 0) const {
1062 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1063 }
1064
1065 void dump(const char *s) const;
1066 void dump() const;
1067 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1068
1069 void Profile(llvm::FoldingSetNodeID &ID) const {
1070 ID.AddPointer(getAsOpaquePtr());
1071 }
1072
1073 /// Check if this type has any address space qualifier.
1074 inline bool hasAddressSpace() const;
1075
1076 /// Return the address space of this type.
1077 inline LangAS getAddressSpace() const;
1078
1079 /// Returns true if address space qualifiers overlap with T address space
1080 /// qualifiers.
1081 /// OpenCL C defines conversion rules for pointers to different address spaces
1082 /// and notion of overlapping address spaces.
1083 /// CL1.1 or CL1.2:
1084 /// address spaces overlap iff they are they same.
1085 /// OpenCL C v2.0 s6.5.5 adds:
1086 /// __generic overlaps with any address space except for __constant.
1087 bool isAddressSpaceOverlapping(QualType T) const {
1088 Qualifiers Q = getQualifiers();
1089 Qualifiers TQ = T.getQualifiers();
1090 // Address spaces overlap if at least one of them is a superset of another
1091 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1092 }
1093
1094 /// Returns gc attribute of this type.
1095 inline Qualifiers::GC getObjCGCAttr() const;
1096
1097 /// true when Type is objc's weak.
1098 bool isObjCGCWeak() const {
1099 return getObjCGCAttr() == Qualifiers::Weak;
1100 }
1101
1102 /// true when Type is objc's strong.
1103 bool isObjCGCStrong() const {
1104 return getObjCGCAttr() == Qualifiers::Strong;
1105 }
1106
1107 /// Returns lifetime attribute of this type.
1108 Qualifiers::ObjCLifetime getObjCLifetime() const {
1109 return getQualifiers().getObjCLifetime();
1110 }
1111
1112 bool hasNonTrivialObjCLifetime() const {
1113 return getQualifiers().hasNonTrivialObjCLifetime();
1114 }
1115
1116 bool hasStrongOrWeakObjCLifetime() const {
1117 return getQualifiers().hasStrongOrWeakObjCLifetime();
1118 }
1119
1120 // true when Type is objc's weak and weak is enabled but ARC isn't.
1121 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1122
1123 enum PrimitiveDefaultInitializeKind {
1124 /// The type does not fall into any of the following categories. Note that
1125 /// this case is zero-valued so that values of this enum can be used as a
1126 /// boolean condition for non-triviality.
1127 PDIK_Trivial,
1128
1129 /// The type is an Objective-C retainable pointer type that is qualified
1130 /// with the ARC __strong qualifier.
1131 PDIK_ARCStrong,
1132
1133 /// The type is an Objective-C retainable pointer type that is qualified
1134 /// with the ARC __weak qualifier.
1135 PDIK_ARCWeak,
1136
1137 /// The type is a struct containing a field whose type is not PCK_Trivial.
1138 PDIK_Struct
1139 };
1140
1141 /// Functions to query basic properties of non-trivial C struct types.
1142
1143 /// Check if this is a non-trivial type that would cause a C struct
1144 /// transitively containing this type to be non-trivial to default initialize
1145 /// and return the kind.
1146 PrimitiveDefaultInitializeKind
1147 isNonTrivialToPrimitiveDefaultInitialize() const;
1148
1149 enum PrimitiveCopyKind {
1150 /// The type does not fall into any of the following categories. Note that
1151 /// this case is zero-valued so that values of this enum can be used as a
1152 /// boolean condition for non-triviality.
1153 PCK_Trivial,
1154
1155 /// The type would be trivial except that it is volatile-qualified. Types
1156 /// that fall into one of the other non-trivial cases may additionally be
1157 /// volatile-qualified.
1158 PCK_VolatileTrivial,
1159
1160 /// The type is an Objective-C retainable pointer type that is qualified
1161 /// with the ARC __strong qualifier.
1162 PCK_ARCStrong,
1163
1164 /// The type is an Objective-C retainable pointer type that is qualified
1165 /// with the ARC __weak qualifier.
1166 PCK_ARCWeak,
1167
1168 /// The type is a struct containing a field whose type is neither
1169 /// PCK_Trivial nor PCK_VolatileTrivial.
1170 /// Note that a C++ struct type does not necessarily match this; C++ copying
1171 /// semantics are too complex to express here, in part because they depend
1172 /// on the exact constructor or assignment operator that is chosen by
1173 /// overload resolution to do the copy.
1174 PCK_Struct
1175 };
1176
1177 /// Check if this is a non-trivial type that would cause a C struct
1178 /// transitively containing this type to be non-trivial to copy and return the
1179 /// kind.
1180 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1181
1182 /// Check if this is a non-trivial type that would cause a C struct
1183 /// transitively containing this type to be non-trivial to destructively
1184 /// move and return the kind. Destructive move in this context is a C++-style
1185 /// move in which the source object is placed in a valid but unspecified state
1186 /// after it is moved, as opposed to a truly destructive move in which the
1187 /// source object is placed in an uninitialized state.
1188 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1189
1190 enum DestructionKind {
1191 DK_none,
1192 DK_cxx_destructor,
1193 DK_objc_strong_lifetime,
1194 DK_objc_weak_lifetime,
1195 DK_nontrivial_c_struct
1196 };
1197
1198 /// Returns a nonzero value if objects of this type require
1199 /// non-trivial work to clean up after. Non-zero because it's
1200 /// conceivable that qualifiers (objc_gc(weak)?) could make
1201 /// something require destruction.
1202 DestructionKind isDestructedType() const {
1203 return isDestructedTypeImpl(*this);
1204 }
1205
1206 /// Check if this is or contains a C union that is non-trivial to
1207 /// default-initialize, which is a union that has a member that is non-trivial
1208 /// to default-initialize. If this returns true,
1209 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1210 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1211
1212 /// Check if this is or contains a C union that is non-trivial to destruct,
1213 /// which is a union that has a member that is non-trivial to destruct. If
1214 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1215 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1216
1217 /// Check if this is or contains a C union that is non-trivial to copy, which
1218 /// is a union that has a member that is non-trivial to copy. If this returns
1219 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1220 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1221
1222 /// Determine whether expressions of the given type are forbidden
1223 /// from being lvalues in C.
1224 ///
1225 /// The expression types that are forbidden to be lvalues are:
1226 /// - 'void', but not qualified void
1227 /// - function types
1228 ///
1229 /// The exact rule here is C99 6.3.2.1:
1230 /// An lvalue is an expression with an object type or an incomplete
1231 /// type other than void.
1232 bool isCForbiddenLValueType() const;
1233
1234 /// Substitute type arguments for the Objective-C type parameters used in the
1235 /// subject type.
1236 ///
1237 /// \param ctx ASTContext in which the type exists.
1238 ///
1239 /// \param typeArgs The type arguments that will be substituted for the
1240 /// Objective-C type parameters in the subject type, which are generally
1241 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1242 /// parameters will be replaced with their bounds or id/Class, as appropriate
1243 /// for the context.
1244 ///
1245 /// \param context The context in which the subject type was written.
1246 ///
1247 /// \returns the resulting type.
1248 QualType substObjCTypeArgs(ASTContext &ctx,
1249 ArrayRef<QualType> typeArgs,
1250 ObjCSubstitutionContext context) const;
1251
1252 /// Substitute type arguments from an object type for the Objective-C type
1253 /// parameters used in the subject type.
1254 ///
1255 /// This operation combines the computation of type arguments for
1256 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1257 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1258 /// callers that need to perform a single substitution in isolation.
1259 ///
1260 /// \param objectType The type of the object whose member type we're
1261 /// substituting into. For example, this might be the receiver of a message
1262 /// or the base of a property access.
1263 ///
1264 /// \param dc The declaration context from which the subject type was
1265 /// retrieved, which indicates (for example) which type parameters should
1266 /// be substituted.
1267 ///
1268 /// \param context The context in which the subject type was written.
1269 ///
1270 /// \returns the subject type after replacing all of the Objective-C type
1271 /// parameters with their corresponding arguments.
1272 QualType substObjCMemberType(QualType objectType,
1273 const DeclContext *dc,
1274 ObjCSubstitutionContext context) const;
1275
1276 /// Strip Objective-C "__kindof" types from the given type.
1277 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1278
1279 /// Remove all qualifiers including _Atomic.
1280 QualType getAtomicUnqualifiedType() const;
1281
1282private:
1283 // These methods are implemented in a separate translation unit;
1284 // "static"-ize them to avoid creating temporary QualTypes in the
1285 // caller.
1286 static bool isConstant(QualType T, const ASTContext& Ctx);
1287 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1288 static SplitQualType getSplitDesugaredType(QualType T);
1289 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1290 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1291 const ASTContext &C);
1292 static QualType IgnoreParens(QualType T);
1293 static DestructionKind isDestructedTypeImpl(QualType type);
1294
1295 /// Check if \param RD is or contains a non-trivial C union.
1296 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1297 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1298 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1299};
1300
1301} // namespace clang
1302
1303namespace llvm {
1304
1305/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1306/// to a specific Type class.
1307template<> struct simplify_type< ::clang::QualType> {
1308 using SimpleType = const ::clang::Type *;
1309
1310 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1311 return Val.getTypePtr();
1312 }
1313};
1314
1315// Teach SmallPtrSet that QualType is "basically a pointer".
1316template<>
1317struct PointerLikeTypeTraits<clang::QualType> {
1318 static inline void *getAsVoidPointer(clang::QualType P) {
1319 return P.getAsOpaquePtr();
1320 }
1321
1322 static inline clang::QualType getFromVoidPointer(void *P) {
1323 return clang::QualType::getFromOpaquePtr(P);
1324 }
1325
1326 // Various qualifiers go in low bits.
1327 static constexpr int NumLowBitsAvailable = 0;
1328};
1329
1330} // namespace llvm
1331
1332namespace clang {
1333
1334/// Base class that is common to both the \c ExtQuals and \c Type
1335/// classes, which allows \c QualType to access the common fields between the
1336/// two.
1337class ExtQualsTypeCommonBase {
1338 friend class ExtQuals;
1339 friend class QualType;
1340 friend class Type;
1341
1342 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1343 /// a self-referential pointer (for \c Type).
1344 ///
1345 /// This pointer allows an efficient mapping from a QualType to its
1346 /// underlying type pointer.
1347 const Type *const BaseType;
1348
1349 /// The canonical type of this type. A QualType.
1350 QualType CanonicalType;
1351
1352 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1353 : BaseType(baseType), CanonicalType(canon) {}
1354};
1355
1356/// We can encode up to four bits in the low bits of a
1357/// type pointer, but there are many more type qualifiers that we want
1358/// to be able to apply to an arbitrary type. Therefore we have this
1359/// struct, intended to be heap-allocated and used by QualType to
1360/// store qualifiers.
1361///
1362/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1363/// in three low bits on the QualType pointer; a fourth bit records whether
1364/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1365/// Objective-C GC attributes) are much more rare.
1366class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1367 // NOTE: changing the fast qualifiers should be straightforward as
1368 // long as you don't make 'const' non-fast.
1369 // 1. Qualifiers:
1370 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1371 // Fast qualifiers must occupy the low-order bits.
1372 // b) Update Qualifiers::FastWidth and FastMask.
1373 // 2. QualType:
1374 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1375 // b) Update remove{Volatile,Restrict}, defined near the end of
1376 // this header.
1377 // 3. ASTContext:
1378 // a) Update get{Volatile,Restrict}Type.
1379
1380 /// The immutable set of qualifiers applied by this node. Always contains
1381 /// extended qualifiers.
1382 Qualifiers Quals;
1383
1384 ExtQuals *this_() { return this; }
1385
1386public:
1387 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1388 : ExtQualsTypeCommonBase(baseType,
1389 canon.isNull() ? QualType(this_(), 0) : canon),
1390 Quals(quals) {
1391 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1392, __PRETTY_FUNCTION__))
1392 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1392, __PRETTY_FUNCTION__))
;
1393 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1394, __PRETTY_FUNCTION__))
1394 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1394, __PRETTY_FUNCTION__))
;
1395 }
1396
1397 Qualifiers getQualifiers() const { return Quals; }
1398
1399 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1400 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1401
1402 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1403 Qualifiers::ObjCLifetime getObjCLifetime() const {
1404 return Quals.getObjCLifetime();
1405 }
1406
1407 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1408 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1409
1410 const Type *getBaseType() const { return BaseType; }
1411
1412public:
1413 void Profile(llvm::FoldingSetNodeID &ID) const {
1414 Profile(ID, getBaseType(), Quals);
1415 }
1416
1417 static void Profile(llvm::FoldingSetNodeID &ID,
1418 const Type *BaseType,
1419 Qualifiers Quals) {
1420 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1420, __PRETTY_FUNCTION__))
;
1421 ID.AddPointer(BaseType);
1422 Quals.Profile(ID);
1423 }
1424};
1425
1426/// The kind of C++11 ref-qualifier associated with a function type.
1427/// This determines whether a member function's "this" object can be an
1428/// lvalue, rvalue, or neither.
1429enum RefQualifierKind {
1430 /// No ref-qualifier was provided.
1431 RQ_None = 0,
1432
1433 /// An lvalue ref-qualifier was provided (\c &).
1434 RQ_LValue,
1435
1436 /// An rvalue ref-qualifier was provided (\c &&).
1437 RQ_RValue
1438};
1439
1440/// Which keyword(s) were used to create an AutoType.
1441enum class AutoTypeKeyword {
1442 /// auto
1443 Auto,
1444
1445 /// decltype(auto)
1446 DecltypeAuto,
1447
1448 /// __auto_type (GNU extension)
1449 GNUAutoType
1450};
1451
1452/// The base class of the type hierarchy.
1453///
1454/// A central concept with types is that each type always has a canonical
1455/// type. A canonical type is the type with any typedef names stripped out
1456/// of it or the types it references. For example, consider:
1457///
1458/// typedef int foo;
1459/// typedef foo* bar;
1460/// 'int *' 'foo *' 'bar'
1461///
1462/// There will be a Type object created for 'int'. Since int is canonical, its
1463/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1464/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1465/// there is a PointerType that represents 'int*', which, like 'int', is
1466/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1467/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1468/// is also 'int*'.
1469///
1470/// Non-canonical types are useful for emitting diagnostics, without losing
1471/// information about typedefs being used. Canonical types are useful for type
1472/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1473/// about whether something has a particular form (e.g. is a function type),
1474/// because they implicitly, recursively, strip all typedefs out of a type.
1475///
1476/// Types, once created, are immutable.
1477///
1478class alignas(8) Type : public ExtQualsTypeCommonBase {
1479public:
1480 enum TypeClass {
1481#define TYPE(Class, Base) Class,
1482#define LAST_TYPE(Class) TypeLast = Class
1483#define ABSTRACT_TYPE(Class, Base)
1484#include "clang/AST/TypeNodes.inc"
1485 };
1486
1487private:
1488 /// Bitfields required by the Type class.
1489 class TypeBitfields {
1490 friend class Type;
1491 template <class T> friend class TypePropertyCache;
1492
1493 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1494 unsigned TC : 8;
1495
1496 /// Store information on the type dependency.
1497 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1498
1499 /// True if the cache (i.e. the bitfields here starting with
1500 /// 'Cache') is valid.
1501 mutable unsigned CacheValid : 1;
1502
1503 /// Linkage of this type.
1504 mutable unsigned CachedLinkage : 3;
1505
1506 /// Whether this type involves and local or unnamed types.
1507 mutable unsigned CachedLocalOrUnnamed : 1;
1508
1509 /// Whether this type comes from an AST file.
1510 mutable unsigned FromAST : 1;
1511
1512 bool isCacheValid() const {
1513 return CacheValid;
1514 }
1515
1516 Linkage getLinkage() const {
1517 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1517, __PRETTY_FUNCTION__))
;
1518 return static_cast<Linkage>(CachedLinkage);
1519 }
1520
1521 bool hasLocalOrUnnamedType() const {
1522 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1522, __PRETTY_FUNCTION__))
;
1523 return CachedLocalOrUnnamed;
1524 }
1525 };
1526 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1527
1528protected:
1529 // These classes allow subclasses to somewhat cleanly pack bitfields
1530 // into Type.
1531
1532 class ArrayTypeBitfields {
1533 friend class ArrayType;
1534
1535 unsigned : NumTypeBits;
1536
1537 /// CVR qualifiers from declarations like
1538 /// 'int X[static restrict 4]'. For function parameters only.
1539 unsigned IndexTypeQuals : 3;
1540
1541 /// Storage class qualifiers from declarations like
1542 /// 'int X[static restrict 4]'. For function parameters only.
1543 /// Actually an ArrayType::ArraySizeModifier.
1544 unsigned SizeModifier : 3;
1545 };
1546
1547 class ConstantArrayTypeBitfields {
1548 friend class ConstantArrayType;
1549
1550 unsigned : NumTypeBits + 3 + 3;
1551
1552 /// Whether we have a stored size expression.
1553 unsigned HasStoredSizeExpr : 1;
1554 };
1555
1556 class BuiltinTypeBitfields {
1557 friend class BuiltinType;
1558
1559 unsigned : NumTypeBits;
1560
1561 /// The kind (BuiltinType::Kind) of builtin type this is.
1562 unsigned Kind : 8;
1563 };
1564
1565 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1566 /// Only common bits are stored here. Additional uncommon bits are stored
1567 /// in a trailing object after FunctionProtoType.
1568 class FunctionTypeBitfields {
1569 friend class FunctionProtoType;
1570 friend class FunctionType;
1571
1572 unsigned : NumTypeBits;
1573
1574 /// Extra information which affects how the function is called, like
1575 /// regparm and the calling convention.
1576 unsigned ExtInfo : 13;
1577
1578 /// The ref-qualifier associated with a \c FunctionProtoType.
1579 ///
1580 /// This is a value of type \c RefQualifierKind.
1581 unsigned RefQualifier : 2;
1582
1583 /// Used only by FunctionProtoType, put here to pack with the
1584 /// other bitfields.
1585 /// The qualifiers are part of FunctionProtoType because...
1586 ///
1587 /// C++ 8.3.5p4: The return type, the parameter type list and the
1588 /// cv-qualifier-seq, [...], are part of the function type.
1589 unsigned FastTypeQuals : Qualifiers::FastWidth;
1590 /// Whether this function has extended Qualifiers.
1591 unsigned HasExtQuals : 1;
1592
1593 /// The number of parameters this function has, not counting '...'.
1594 /// According to [implimits] 8 bits should be enough here but this is
1595 /// somewhat easy to exceed with metaprogramming and so we would like to
1596 /// keep NumParams as wide as reasonably possible.
1597 unsigned NumParams : 16;
1598
1599 /// The type of exception specification this function has.
1600 unsigned ExceptionSpecType : 4;
1601
1602 /// Whether this function has extended parameter information.
1603 unsigned HasExtParameterInfos : 1;
1604
1605 /// Whether the function is variadic.
1606 unsigned Variadic : 1;
1607
1608 /// Whether this function has a trailing return type.
1609 unsigned HasTrailingReturn : 1;
1610 };
1611
1612 class ObjCObjectTypeBitfields {
1613 friend class ObjCObjectType;
1614
1615 unsigned : NumTypeBits;
1616
1617 /// The number of type arguments stored directly on this object type.
1618 unsigned NumTypeArgs : 7;
1619
1620 /// The number of protocols stored directly on this object type.
1621 unsigned NumProtocols : 6;
1622
1623 /// Whether this is a "kindof" type.
1624 unsigned IsKindOf : 1;
1625 };
1626
1627 class ReferenceTypeBitfields {
1628 friend class ReferenceType;
1629
1630 unsigned : NumTypeBits;
1631
1632 /// True if the type was originally spelled with an lvalue sigil.
1633 /// This is never true of rvalue references but can also be false
1634 /// on lvalue references because of C++0x [dcl.typedef]p9,
1635 /// as follows:
1636 ///
1637 /// typedef int &ref; // lvalue, spelled lvalue
1638 /// typedef int &&rvref; // rvalue
1639 /// ref &a; // lvalue, inner ref, spelled lvalue
1640 /// ref &&a; // lvalue, inner ref
1641 /// rvref &a; // lvalue, inner ref, spelled lvalue
1642 /// rvref &&a; // rvalue, inner ref
1643 unsigned SpelledAsLValue : 1;
1644
1645 /// True if the inner type is a reference type. This only happens
1646 /// in non-canonical forms.
1647 unsigned InnerRef : 1;
1648 };
1649
1650 class TypeWithKeywordBitfields {
1651 friend class TypeWithKeyword;
1652
1653 unsigned : NumTypeBits;
1654
1655 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1656 unsigned Keyword : 8;
1657 };
1658
1659 enum { NumTypeWithKeywordBits = 8 };
1660
1661 class ElaboratedTypeBitfields {
1662 friend class ElaboratedType;
1663
1664 unsigned : NumTypeBits;
1665 unsigned : NumTypeWithKeywordBits;
1666
1667 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1668 unsigned HasOwnedTagDecl : 1;
1669 };
1670
1671 class VectorTypeBitfields {
1672 friend class VectorType;
1673 friend class DependentVectorType;
1674
1675 unsigned : NumTypeBits;
1676
1677 /// The kind of vector, either a generic vector type or some
1678 /// target-specific vector type such as for AltiVec or Neon.
1679 unsigned VecKind : 3;
1680 /// The number of elements in the vector.
1681 uint32_t NumElements;
1682 };
1683
1684 class AttributedTypeBitfields {
1685 friend class AttributedType;
1686
1687 unsigned : NumTypeBits;
1688
1689 /// An AttributedType::Kind
1690 unsigned AttrKind : 32 - NumTypeBits;
1691 };
1692
1693 class AutoTypeBitfields {
1694 friend class AutoType;
1695
1696 unsigned : NumTypeBits;
1697
1698 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1699 /// or '__auto_type'? AutoTypeKeyword value.
1700 unsigned Keyword : 2;
1701
1702 /// The number of template arguments in the type-constraints, which is
1703 /// expected to be able to hold at least 1024 according to [implimits].
1704 /// However as this limit is somewhat easy to hit with template
1705 /// metaprogramming we'd prefer to keep it as large as possible.
1706 /// At the moment it has been left as a non-bitfield since this type
1707 /// safely fits in 64 bits as an unsigned, so there is no reason to
1708 /// introduce the performance impact of a bitfield.
1709 unsigned NumArgs;
1710 };
1711
1712 class SubstTemplateTypeParmPackTypeBitfields {
1713 friend class SubstTemplateTypeParmPackType;
1714
1715 unsigned : NumTypeBits;
1716
1717 /// The number of template arguments in \c Arguments, which is
1718 /// expected to be able to hold at least 1024 according to [implimits].
1719 /// However as this limit is somewhat easy to hit with template
1720 /// metaprogramming we'd prefer to keep it as large as possible.
1721 /// At the moment it has been left as a non-bitfield since this type
1722 /// safely fits in 64 bits as an unsigned, so there is no reason to
1723 /// introduce the performance impact of a bitfield.
1724 unsigned NumArgs;
1725 };
1726
1727 class TemplateSpecializationTypeBitfields {
1728 friend class TemplateSpecializationType;
1729
1730 unsigned : NumTypeBits;
1731
1732 /// Whether this template specialization type is a substituted type alias.
1733 unsigned TypeAlias : 1;
1734
1735 /// The number of template arguments named in this class template
1736 /// specialization, which is expected to be able to hold at least 1024
1737 /// according to [implimits]. However, as this limit is somewhat easy to
1738 /// hit with template metaprogramming we'd prefer to keep it as large
1739 /// as possible. At the moment it has been left as a non-bitfield since
1740 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1741 /// to introduce the performance impact of a bitfield.
1742 unsigned NumArgs;
1743 };
1744
1745 class DependentTemplateSpecializationTypeBitfields {
1746 friend class DependentTemplateSpecializationType;
1747
1748 unsigned : NumTypeBits;
1749 unsigned : NumTypeWithKeywordBits;
1750
1751 /// The number of template arguments named in this class template
1752 /// specialization, which is expected to be able to hold at least 1024
1753 /// according to [implimits]. However, as this limit is somewhat easy to
1754 /// hit with template metaprogramming we'd prefer to keep it as large
1755 /// as possible. At the moment it has been left as a non-bitfield since
1756 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1757 /// to introduce the performance impact of a bitfield.
1758 unsigned NumArgs;
1759 };
1760
1761 class PackExpansionTypeBitfields {
1762 friend class PackExpansionType;
1763
1764 unsigned : NumTypeBits;
1765
1766 /// The number of expansions that this pack expansion will
1767 /// generate when substituted (+1), which is expected to be able to
1768 /// hold at least 1024 according to [implimits]. However, as this limit
1769 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1770 /// keep it as large as possible. At the moment it has been left as a
1771 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1772 /// there is no reason to introduce the performance impact of a bitfield.
1773 ///
1774 /// This field will only have a non-zero value when some of the parameter
1775 /// packs that occur within the pattern have been substituted but others
1776 /// have not.
1777 unsigned NumExpansions;
1778 };
1779
1780 union {
1781 TypeBitfields TypeBits;
1782 ArrayTypeBitfields ArrayTypeBits;
1783 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1784 AttributedTypeBitfields AttributedTypeBits;
1785 AutoTypeBitfields AutoTypeBits;
1786 BuiltinTypeBitfields BuiltinTypeBits;
1787 FunctionTypeBitfields FunctionTypeBits;
1788 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1789 ReferenceTypeBitfields ReferenceTypeBits;
1790 TypeWithKeywordBitfields TypeWithKeywordBits;
1791 ElaboratedTypeBitfields ElaboratedTypeBits;
1792 VectorTypeBitfields VectorTypeBits;
1793 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1794 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1795 DependentTemplateSpecializationTypeBitfields
1796 DependentTemplateSpecializationTypeBits;
1797 PackExpansionTypeBitfields PackExpansionTypeBits;
1798 };
1799
1800private:
1801 template <class T> friend class TypePropertyCache;
1802
1803 /// Set whether this type comes from an AST file.
1804 void setFromAST(bool V = true) const {
1805 TypeBits.FromAST = V;
1806 }
1807
1808protected:
1809 friend class ASTContext;
1810
1811 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1812 : ExtQualsTypeCommonBase(this,
1813 canon.isNull() ? QualType(this_(), 0) : canon) {
1814 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1815 "changing bitfields changed sizeof(Type)!");
1816 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1817 "Insufficient alignment!");
1818 TypeBits.TC = tc;
1819 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1820 TypeBits.CacheValid = false;
1821 TypeBits.CachedLocalOrUnnamed = false;
1822 TypeBits.CachedLinkage = NoLinkage;
1823 TypeBits.FromAST = false;
1824 }
1825
1826 // silence VC++ warning C4355: 'this' : used in base member initializer list
1827 Type *this_() { return this; }
1828
1829 void setDependence(TypeDependence D) {
1830 TypeBits.Dependence = static_cast<unsigned>(D);
1831 }
1832
1833 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1834
1835public:
1836 friend class ASTReader;
1837 friend class ASTWriter;
1838 template <class T> friend class serialization::AbstractTypeReader;
1839 template <class T> friend class serialization::AbstractTypeWriter;
1840
1841 Type(const Type &) = delete;
1842 Type(Type &&) = delete;
1843 Type &operator=(const Type &) = delete;
1844 Type &operator=(Type &&) = delete;
1845
1846 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1847
1848 /// Whether this type comes from an AST file.
1849 bool isFromAST() const { return TypeBits.FromAST; }
1850
1851 /// Whether this type is or contains an unexpanded parameter
1852 /// pack, used to support C++0x variadic templates.
1853 ///
1854 /// A type that contains a parameter pack shall be expanded by the
1855 /// ellipsis operator at some point. For example, the typedef in the
1856 /// following example contains an unexpanded parameter pack 'T':
1857 ///
1858 /// \code
1859 /// template<typename ...T>
1860 /// struct X {
1861 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1862 /// };
1863 /// \endcode
1864 ///
1865 /// Note that this routine does not specify which
1866 bool containsUnexpandedParameterPack() const {
1867 return getDependence() & TypeDependence::UnexpandedPack;
1868 }
1869
1870 /// Determines if this type would be canonical if it had no further
1871 /// qualification.
1872 bool isCanonicalUnqualified() const {
1873 return CanonicalType == QualType(this, 0);
1874 }
1875
1876 /// Pull a single level of sugar off of this locally-unqualified type.
1877 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1878 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1879 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1880
1881 /// As an extension, we classify types as one of "sized" or "sizeless";
1882 /// every type is one or the other. Standard types are all sized;
1883 /// sizeless types are purely an extension.
1884 ///
1885 /// Sizeless types contain data with no specified size, alignment,
1886 /// or layout.
1887 bool isSizelessType() const;
1888 bool isSizelessBuiltinType() const;
1889
1890 /// Determines if this is a sizeless type supported by the
1891 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1892 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1893 bool isVLSTBuiltinType() const;
1894
1895 /// Returns the representative type for the element of an SVE builtin type.
1896 /// This is used to represent fixed-length SVE vectors created with the
1897 /// 'arm_sve_vector_bits' type attribute as VectorType.
1898 QualType getSveEltType(const ASTContext &Ctx) const;
1899
1900 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1901 /// object types, function types, and incomplete types.
1902
1903 /// Return true if this is an incomplete type.
1904 /// A type that can describe objects, but which lacks information needed to
1905 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1906 /// routine will need to determine if the size is actually required.
1907 ///
1908 /// Def If non-null, and the type refers to some kind of declaration
1909 /// that can be completed (such as a C struct, C++ class, or Objective-C
1910 /// class), will be set to the declaration.
1911 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1912
1913 /// Return true if this is an incomplete or object
1914 /// type, in other words, not a function type.
1915 bool isIncompleteOrObjectType() const {
1916 return !isFunctionType();
1917 }
1918
1919 /// Determine whether this type is an object type.
1920 bool isObjectType() const {
1921 // C++ [basic.types]p8:
1922 // An object type is a (possibly cv-qualified) type that is not a
1923 // function type, not a reference type, and not a void type.
1924 return !isReferenceType() && !isFunctionType() && !isVoidType();
1925 }
1926
1927 /// Return true if this is a literal type
1928 /// (C++11 [basic.types]p10)
1929 bool isLiteralType(const ASTContext &Ctx) const;
1930
1931 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1932 bool isStructuralType() const;
1933
1934 /// Test if this type is a standard-layout type.
1935 /// (C++0x [basic.type]p9)
1936 bool isStandardLayoutType() const;
1937
1938 /// Helper methods to distinguish type categories. All type predicates
1939 /// operate on the canonical type, ignoring typedefs and qualifiers.
1940
1941 /// Returns true if the type is a builtin type.
1942 bool isBuiltinType() const;
1943
1944 /// Test for a particular builtin type.
1945 bool isSpecificBuiltinType(unsigned K) const;
1946
1947 /// Test for a type which does not represent an actual type-system type but
1948 /// is instead used as a placeholder for various convenient purposes within
1949 /// Clang. All such types are BuiltinTypes.
1950 bool isPlaceholderType() const;
1951 const BuiltinType *getAsPlaceholderType() const;
1952
1953 /// Test for a specific placeholder type.
1954 bool isSpecificPlaceholderType(unsigned K) const;
1955
1956 /// Test for a placeholder type other than Overload; see
1957 /// BuiltinType::isNonOverloadPlaceholderType.
1958 bool isNonOverloadPlaceholderType() const;
1959
1960 /// isIntegerType() does *not* include complex integers (a GCC extension).
1961 /// isComplexIntegerType() can be used to test for complex integers.
1962 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1963 bool isEnumeralType() const;
1964
1965 /// Determine whether this type is a scoped enumeration type.
1966 bool isScopedEnumeralType() const;
1967 bool isBooleanType() const;
1968 bool isCharType() const;
1969 bool isWideCharType() const;
1970 bool isChar8Type() const;
1971 bool isChar16Type() const;
1972 bool isChar32Type() const;
1973 bool isAnyCharacterType() const;
1974 bool isIntegralType(const ASTContext &Ctx) const;
1975
1976 /// Determine whether this type is an integral or enumeration type.
1977 bool isIntegralOrEnumerationType() const;
1978
1979 /// Determine whether this type is an integral or unscoped enumeration type.
1980 bool isIntegralOrUnscopedEnumerationType() const;
1981 bool isUnscopedEnumerationType() const;
1982
1983 /// Floating point categories.
1984 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1985 /// isComplexType() does *not* include complex integers (a GCC extension).
1986 /// isComplexIntegerType() can be used to test for complex integers.
1987 bool isComplexType() const; // C99 6.2.5p11 (complex)
1988 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1989 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1990 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1991 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1992 bool isBFloat16Type() const;
1993 bool isFloat128Type() const;
1994 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1995 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1996 bool isVoidType() const; // C99 6.2.5p19
1997 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1998 bool isAggregateType() const;
1999 bool isFundamentalType() const;
2000 bool isCompoundType() const;
2001
2002 // Type Predicates: Check to see if this type is structurally the specified
2003 // type, ignoring typedefs and qualifiers.
2004 bool isFunctionType() const;
2005 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2006 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2007 bool isPointerType() const;
2008 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2009 bool isBlockPointerType() const;
2010 bool isVoidPointerType() const;
2011 bool isReferenceType() const;
2012 bool isLValueReferenceType() const;
2013 bool isRValueReferenceType() const;
2014 bool isObjectPointerType() const;
2015 bool isFunctionPointerType() const;
2016 bool isFunctionReferenceType() const;
2017 bool isMemberPointerType() const;
2018 bool isMemberFunctionPointerType() const;
2019 bool isMemberDataPointerType() const;
2020 bool isArrayType() const;
2021 bool isConstantArrayType() const;
2022 bool isIncompleteArrayType() const;
2023 bool isVariableArrayType() const;
2024 bool isDependentSizedArrayType() const;
2025 bool isRecordType() const;
2026 bool isClassType() const;
2027 bool isStructureType() const;
2028 bool isObjCBoxableRecordType() const;
2029 bool isInterfaceType() const;
2030 bool isStructureOrClassType() const;
2031 bool isUnionType() const;
2032 bool isComplexIntegerType() const; // GCC _Complex integer type.
2033 bool isVectorType() const; // GCC vector type.
2034 bool isExtVectorType() const; // Extended vector type.
2035 bool isMatrixType() const; // Matrix type.
2036 bool isConstantMatrixType() const; // Constant matrix type.
2037 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2038 bool isObjCObjectPointerType() const; // pointer to ObjC object
2039 bool isObjCRetainableType() const; // ObjC object or block pointer
2040 bool isObjCLifetimeType() const; // (array of)* retainable type
2041 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2042 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2043 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2044 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2045 // for the common case.
2046 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2047 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2048 bool isObjCQualifiedIdType() const; // id<foo>
2049 bool isObjCQualifiedClassType() const; // Class<foo>
2050 bool isObjCObjectOrInterfaceType() const;
2051 bool isObjCIdType() const; // id
2052 bool isDecltypeType() const;
2053 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2054 /// qualifier?
2055 ///
2056 /// This approximates the answer to the following question: if this
2057 /// translation unit were compiled in ARC, would this type be qualified
2058 /// with __unsafe_unretained?
2059 bool isObjCInertUnsafeUnretainedType() const {
2060 return hasAttr(attr::ObjCInertUnsafeUnretained);
2061 }
2062
2063 /// Whether the type is Objective-C 'id' or a __kindof type of an
2064 /// object type, e.g., __kindof NSView * or __kindof id
2065 /// <NSCopying>.
2066 ///
2067 /// \param bound Will be set to the bound on non-id subtype types,
2068 /// which will be (possibly specialized) Objective-C class type, or
2069 /// null for 'id.
2070 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2071 const ObjCObjectType *&bound) const;
2072
2073 bool isObjCClassType() const; // Class
2074
2075 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2076 /// Class type, e.g., __kindof Class <NSCopying>.
2077 ///
2078 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2079 /// here because Objective-C's type system cannot express "a class
2080 /// object for a subclass of NSFoo".
2081 bool isObjCClassOrClassKindOfType() const;
2082
2083 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2084 bool isObjCSelType() const; // Class
2085 bool isObjCBuiltinType() const; // 'id' or 'Class'
2086 bool isObjCARCBridgableType() const;
2087 bool isCARCBridgableType() const;
2088 bool isTemplateTypeParmType() const; // C++ template type parameter
2089 bool isNullPtrType() const; // C++11 std::nullptr_t
2090 bool isNothrowT() const; // C++ std::nothrow_t
2091 bool isAlignValT() const; // C++17 std::align_val_t
2092 bool isStdByteType() const; // C++17 std::byte
2093 bool isAtomicType() const; // C11 _Atomic()
2094 bool isUndeducedAutoType() const; // C++11 auto or
2095 // C++14 decltype(auto)
2096 bool isTypedefNameType() const; // typedef or alias template
2097
2098#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2099 bool is##Id##Type() const;
2100#include "clang/Basic/OpenCLImageTypes.def"
2101
2102 bool isImageType() const; // Any OpenCL image type
2103
2104 bool isSamplerT() const; // OpenCL sampler_t
2105 bool isEventT() const; // OpenCL event_t
2106 bool isClkEventT() const; // OpenCL clk_event_t
2107 bool isQueueT() const; // OpenCL queue_t
2108 bool isReserveIDT() const; // OpenCL reserve_id_t
2109
2110#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2111 bool is##Id##Type() const;
2112#include "clang/Basic/OpenCLExtensionTypes.def"
2113 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2114 bool isOCLIntelSubgroupAVCType() const;
2115 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2116
2117 bool isPipeType() const; // OpenCL pipe type
2118 bool isExtIntType() const; // Extended Int Type
2119 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2120
2121 /// Determines if this type, which must satisfy
2122 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2123 /// than implicitly __strong.
2124 bool isObjCARCImplicitlyUnretainedType() const;
2125
2126 /// Check if the type is the CUDA device builtin surface type.
2127 bool isCUDADeviceBuiltinSurfaceType() const;
2128 /// Check if the type is the CUDA device builtin texture type.
2129 bool isCUDADeviceBuiltinTextureType() const;
2130
2131 /// Return the implicit lifetime for this type, which must not be dependent.
2132 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2133
2134 enum ScalarTypeKind {
2135 STK_CPointer,
2136 STK_BlockPointer,
2137 STK_ObjCObjectPointer,
2138 STK_MemberPointer,
2139 STK_Bool,
2140 STK_Integral,
2141 STK_Floating,
2142 STK_IntegralComplex,
2143 STK_FloatingComplex,
2144 STK_FixedPoint
2145 };
2146
2147 /// Given that this is a scalar type, classify it.
2148 ScalarTypeKind getScalarTypeKind() const;
2149
2150 TypeDependence getDependence() const {
2151 return static_cast<TypeDependence>(TypeBits.Dependence);
2152 }
2153
2154 /// Whether this type is an error type.
2155 bool containsErrors() const {
2156 return getDependence() & TypeDependence::Error;
2157 }
2158
2159 /// Whether this type is a dependent type, meaning that its definition
2160 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2161 bool isDependentType() const {
2162 return getDependence() & TypeDependence::Dependent;
2163 }
2164
2165 /// Determine whether this type is an instantiation-dependent type,
2166 /// meaning that the type involves a template parameter (even if the
2167 /// definition does not actually depend on the type substituted for that
2168 /// template parameter).
2169 bool isInstantiationDependentType() const {
2170 return getDependence() & TypeDependence::Instantiation;
2171 }
2172
2173 /// Determine whether this type is an undeduced type, meaning that
2174 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2175 /// deduced.
2176 bool isUndeducedType() const;
2177
2178 /// Whether this type is a variably-modified type (C99 6.7.5).
2179 bool isVariablyModifiedType() const {
2180 return getDependence() & TypeDependence::VariablyModified;
2181 }
2182
2183 /// Whether this type involves a variable-length array type
2184 /// with a definite size.
2185 bool hasSizedVLAType() const;
2186
2187 /// Whether this type is or contains a local or unnamed type.
2188 bool hasUnnamedOrLocalType() const;
2189
2190 bool isOverloadableType() const;
2191
2192 /// Determine wither this type is a C++ elaborated-type-specifier.
2193 bool isElaboratedTypeSpecifier() const;
2194
2195 bool canDecayToPointerType() const;
2196
2197 /// Whether this type is represented natively as a pointer. This includes
2198 /// pointers, references, block pointers, and Objective-C interface,
2199 /// qualified id, and qualified interface types, as well as nullptr_t.
2200 bool hasPointerRepresentation() const;
2201
2202 /// Whether this type can represent an objective pointer type for the
2203 /// purpose of GC'ability
2204 bool hasObjCPointerRepresentation() const;
2205
2206 /// Determine whether this type has an integer representation
2207 /// of some sort, e.g., it is an integer type or a vector.
2208 bool hasIntegerRepresentation() const;
2209
2210 /// Determine whether this type has an signed integer representation
2211 /// of some sort, e.g., it is an signed integer type or a vector.
2212 bool hasSignedIntegerRepresentation() const;
2213
2214 /// Determine whether this type has an unsigned integer representation
2215 /// of some sort, e.g., it is an unsigned integer type or a vector.
2216 bool hasUnsignedIntegerRepresentation() const;
2217
2218 /// Determine whether this type has a floating-point representation
2219 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2220 bool hasFloatingRepresentation() const;
2221
2222 // Type Checking Functions: Check to see if this type is structurally the
2223 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2224 // the best type we can.
2225 const RecordType *getAsStructureType() const;
2226 /// NOTE: getAs*ArrayType are methods on ASTContext.
2227 const RecordType *getAsUnionType() const;
2228 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2229 const ObjCObjectType *getAsObjCInterfaceType() const;
2230
2231 // The following is a convenience method that returns an ObjCObjectPointerType
2232 // for object declared using an interface.
2233 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2234 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2235 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2236 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2237
2238 /// Retrieves the CXXRecordDecl that this type refers to, either
2239 /// because the type is a RecordType or because it is the injected-class-name
2240 /// type of a class template or class template partial specialization.
2241 CXXRecordDecl *getAsCXXRecordDecl() const;
2242
2243 /// Retrieves the RecordDecl this type refers to.
2244 RecordDecl *getAsRecordDecl() const;
2245
2246 /// Retrieves the TagDecl that this type refers to, either
2247 /// because the type is a TagType or because it is the injected-class-name
2248 /// type of a class template or class template partial specialization.
2249 TagDecl *getAsTagDecl() const;
2250
2251 /// If this is a pointer or reference to a RecordType, return the
2252 /// CXXRecordDecl that the type refers to.
2253 ///
2254 /// If this is not a pointer or reference, or the type being pointed to does
2255 /// not refer to a CXXRecordDecl, returns NULL.
2256 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2257
2258 /// Get the DeducedType whose type will be deduced for a variable with
2259 /// an initializer of this type. This looks through declarators like pointer
2260 /// types, but not through decltype or typedefs.
2261 DeducedType *getContainedDeducedType() const;
2262
2263 /// Get the AutoType whose type will be deduced for a variable with
2264 /// an initializer of this type. This looks through declarators like pointer
2265 /// types, but not through decltype or typedefs.
2266 AutoType *getContainedAutoType() const {
2267 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2268 }
2269
2270 /// Determine whether this type was written with a leading 'auto'
2271 /// corresponding to a trailing return type (possibly for a nested
2272 /// function type within a pointer to function type or similar).
2273 bool hasAutoForTrailingReturnType() const;
2274
2275 /// Member-template getAs<specific type>'. Look through sugar for
2276 /// an instance of \<specific type>. This scheme will eventually
2277 /// replace the specific getAsXXXX methods above.
2278 ///
2279 /// There are some specializations of this member template listed
2280 /// immediately following this class.
2281 template <typename T> const T *getAs() const;
2282
2283 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2284 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2285 /// This is used when you need to walk over sugar nodes that represent some
2286 /// kind of type adjustment from a type that was written as a \<specific type>
2287 /// to another type that is still canonically a \<specific type>.
2288 template <typename T> const T *getAsAdjusted() const;
2289
2290 /// A variant of getAs<> for array types which silently discards
2291 /// qualifiers from the outermost type.
2292 const ArrayType *getAsArrayTypeUnsafe() const;
2293
2294 /// Member-template castAs<specific type>. Look through sugar for
2295 /// the underlying instance of \<specific type>.
2296 ///
2297 /// This method has the same relationship to getAs<T> as cast<T> has
2298 /// to dyn_cast<T>; which is to say, the underlying type *must*
2299 /// have the intended type, and this method will never return null.
2300 template <typename T> const T *castAs() const;
2301
2302 /// A variant of castAs<> for array type which silently discards
2303 /// qualifiers from the outermost type.
2304 const ArrayType *castAsArrayTypeUnsafe() const;
2305
2306 /// Determine whether this type had the specified attribute applied to it
2307 /// (looking through top-level type sugar).
2308 bool hasAttr(attr::Kind AK) const;
2309
2310 /// Get the base element type of this type, potentially discarding type
2311 /// qualifiers. This should never be used when type qualifiers
2312 /// are meaningful.
2313 const Type *getBaseElementTypeUnsafe() const;
2314
2315 /// If this is an array type, return the element type of the array,
2316 /// potentially with type qualifiers missing.
2317 /// This should never be used when type qualifiers are meaningful.
2318 const Type *getArrayElementTypeNoTypeQual() const;
2319
2320 /// If this is a pointer type, return the pointee type.
2321 /// If this is an array type, return the array element type.
2322 /// This should never be used when type qualifiers are meaningful.
2323 const Type *getPointeeOrArrayElementType() const;
2324
2325 /// If this is a pointer, ObjC object pointer, or block
2326 /// pointer, this returns the respective pointee.
2327 QualType getPointeeType() const;
2328
2329 /// Return the specified type with any "sugar" removed from the type,
2330 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2331 const Type *getUnqualifiedDesugaredType() const;
2332
2333 /// More type predicates useful for type checking/promotion
2334 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2335
2336 /// Return true if this is an integer type that is
2337 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2338 /// or an enum decl which has a signed representation.
2339 bool isSignedIntegerType() const;
2340
2341 /// Return true if this is an integer type that is
2342 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2343 /// or an enum decl which has an unsigned representation.
2344 bool isUnsignedIntegerType() const;
2345
2346 /// Determines whether this is an integer type that is signed or an
2347 /// enumeration types whose underlying type is a signed integer type.
2348 bool isSignedIntegerOrEnumerationType() const;
2349
2350 /// Determines whether this is an integer type that is unsigned or an
2351 /// enumeration types whose underlying type is a unsigned integer type.
2352 bool isUnsignedIntegerOrEnumerationType() const;
2353
2354 /// Return true if this is a fixed point type according to
2355 /// ISO/IEC JTC1 SC22 WG14 N1169.
2356 bool isFixedPointType() const;
2357
2358 /// Return true if this is a fixed point or integer type.
2359 bool isFixedPointOrIntegerType() const;
2360
2361 /// Return true if this is a saturated fixed point type according to
2362 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2363 bool isSaturatedFixedPointType() const;
2364
2365 /// Return true if this is a saturated fixed point type according to
2366 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2367 bool isUnsaturatedFixedPointType() const;
2368
2369 /// Return true if this is a fixed point type that is signed according
2370 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2371 bool isSignedFixedPointType() const;
2372
2373 /// Return true if this is a fixed point type that is unsigned according
2374 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2375 bool isUnsignedFixedPointType() const;
2376
2377 /// Return true if this is not a variable sized type,
2378 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2379 /// incomplete types.
2380 bool isConstantSizeType() const;
2381
2382 /// Returns true if this type can be represented by some
2383 /// set of type specifiers.
2384 bool isSpecifierType() const;
2385
2386 /// Determine the linkage of this type.
2387 Linkage getLinkage() const;
2388
2389 /// Determine the visibility of this type.
2390 Visibility getVisibility() const {
2391 return getLinkageAndVisibility().getVisibility();
2392 }
2393
2394 /// Return true if the visibility was explicitly set is the code.
2395 bool isVisibilityExplicit() const {
2396 return getLinkageAndVisibility().isVisibilityExplicit();
2397 }
2398
2399 /// Determine the linkage and visibility of this type.
2400 LinkageInfo getLinkageAndVisibility() const;
2401
2402 /// True if the computed linkage is valid. Used for consistency
2403 /// checking. Should always return true.
2404 bool isLinkageValid() const;
2405
2406 /// Determine the nullability of the given type.
2407 ///
2408 /// Note that nullability is only captured as sugar within the type
2409 /// system, not as part of the canonical type, so nullability will
2410 /// be lost by canonicalization and desugaring.
2411 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2412
2413 /// Determine whether the given type can have a nullability
2414 /// specifier applied to it, i.e., if it is any kind of pointer type.
2415 ///
2416 /// \param ResultIfUnknown The value to return if we don't yet know whether
2417 /// this type can have nullability because it is dependent.
2418 bool canHaveNullability(bool ResultIfUnknown = true) const;
2419
2420 /// Retrieve the set of substitutions required when accessing a member
2421 /// of the Objective-C receiver type that is declared in the given context.
2422 ///
2423 /// \c *this is the type of the object we're operating on, e.g., the
2424 /// receiver for a message send or the base of a property access, and is
2425 /// expected to be of some object or object pointer type.
2426 ///
2427 /// \param dc The declaration context for which we are building up a
2428 /// substitution mapping, which should be an Objective-C class, extension,
2429 /// category, or method within.
2430 ///
2431 /// \returns an array of type arguments that can be substituted for
2432 /// the type parameters of the given declaration context in any type described
2433 /// within that context, or an empty optional to indicate that no
2434 /// substitution is required.
2435 Optional<ArrayRef<QualType>>
2436 getObjCSubstitutions(const DeclContext *dc) const;
2437
2438 /// Determines if this is an ObjC interface type that may accept type
2439 /// parameters.
2440 bool acceptsObjCTypeParams() const;
2441
2442 const char *getTypeClassName() const;
2443
2444 QualType getCanonicalTypeInternal() const {
2445 return CanonicalType;
2446 }
2447
2448 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2449 void dump() const;
2450 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2451};
2452
2453/// This will check for a TypedefType by removing any existing sugar
2454/// until it reaches a TypedefType or a non-sugared type.
2455template <> const TypedefType *Type::getAs() const;
2456
2457/// This will check for a TemplateSpecializationType by removing any
2458/// existing sugar until it reaches a TemplateSpecializationType or a
2459/// non-sugared type.
2460template <> const TemplateSpecializationType *Type::getAs() const;
2461
2462/// This will check for an AttributedType by removing any existing sugar
2463/// until it reaches an AttributedType or a non-sugared type.
2464template <> const AttributedType *Type::getAs() const;
2465
2466// We can do canonical leaf types faster, because we don't have to
2467// worry about preserving child type decoration.
2468#define TYPE(Class, Base)
2469#define LEAF_TYPE(Class) \
2470template <> inline const Class##Type *Type::getAs() const { \
2471 return dyn_cast<Class##Type>(CanonicalType); \
2472} \
2473template <> inline const Class##Type *Type::castAs() const { \
2474 return cast<Class##Type>(CanonicalType); \
2475}
2476#include "clang/AST/TypeNodes.inc"
2477
2478/// This class is used for builtin types like 'int'. Builtin
2479/// types are always canonical and have a literal name field.
2480class BuiltinType : public Type {
2481public:
2482 enum Kind {
2483// OpenCL image types
2484#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2485#include "clang/Basic/OpenCLImageTypes.def"
2486// OpenCL extension types
2487#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2488#include "clang/Basic/OpenCLExtensionTypes.def"
2489// SVE Types
2490#define SVE_TYPE(Name, Id, SingletonId) Id,
2491#include "clang/Basic/AArch64SVEACLETypes.def"
2492// PPC MMA Types
2493#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2494#include "clang/Basic/PPCTypes.def"
2495// RVV Types
2496#define RVV_TYPE(Name, Id, SingletonId) Id,
2497#include "clang/Basic/RISCVVTypes.def"
2498// All other builtin types
2499#define BUILTIN_TYPE(Id, SingletonId) Id,
2500#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2501#include "clang/AST/BuiltinTypes.def"
2502 };
2503
2504private:
2505 friend class ASTContext; // ASTContext creates these.
2506
2507 BuiltinType(Kind K)
2508 : Type(Builtin, QualType(),
2509 K == Dependent ? TypeDependence::DependentInstantiation
2510 : TypeDependence::None) {
2511 BuiltinTypeBits.Kind = K;
2512 }
2513
2514public:
2515 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2516 StringRef getName(const PrintingPolicy &Policy) const;
2517
2518 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2519 // The StringRef is null-terminated.
2520 StringRef str = getName(Policy);
2521 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 2521, __PRETTY_FUNCTION__))
;
2522 return str.data();
2523 }
2524
2525 bool isSugared() const { return false; }
2526 QualType desugar() const { return QualType(this, 0); }
2527
2528 bool isInteger() const {
2529 return getKind() >= Bool && getKind() <= Int128;
2530 }
2531
2532 bool isSignedInteger() const {
2533 return getKind() >= Char_S && getKind() <= Int128;
2534 }
2535
2536 bool isUnsignedInteger() const {
2537 return getKind() >= Bool && getKind() <= UInt128;
2538 }
2539
2540 bool isFloatingPoint() const {
2541 return getKind() >= Half && getKind() <= Float128;
2542 }
2543
2544 /// Determines whether the given kind corresponds to a placeholder type.
2545 static bool isPlaceholderTypeKind(Kind K) {
2546 return K >= Overload;
2547 }
2548
2549 /// Determines whether this type is a placeholder type, i.e. a type
2550 /// which cannot appear in arbitrary positions in a fully-formed
2551 /// expression.
2552 bool isPlaceholderType() const {
2553 return isPlaceholderTypeKind(getKind());
2554 }
2555
2556 /// Determines whether this type is a placeholder type other than
2557 /// Overload. Most placeholder types require only syntactic
2558 /// information about their context in order to be resolved (e.g.
2559 /// whether it is a call expression), which means they can (and
2560 /// should) be resolved in an earlier "phase" of analysis.
2561 /// Overload expressions sometimes pick up further information
2562 /// from their context, like whether the context expects a
2563 /// specific function-pointer type, and so frequently need
2564 /// special treatment.
2565 bool isNonOverloadPlaceholderType() const {
2566 return getKind() > Overload;
2567 }
2568
2569 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2570};
2571
2572/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2573/// types (_Complex float etc) as well as the GCC integer complex extensions.
2574class ComplexType : public Type, public llvm::FoldingSetNode {
2575 friend class ASTContext; // ASTContext creates these.
2576
2577 QualType ElementType;
2578
2579 ComplexType(QualType Element, QualType CanonicalPtr)
2580 : Type(Complex, CanonicalPtr, Element->getDependence()),
2581 ElementType(Element) {}
2582
2583public:
2584 QualType getElementType() const { return ElementType; }
2585
2586 bool isSugared() const { return false; }
2587 QualType desugar() const { return QualType(this, 0); }
2588
2589 void Profile(llvm::FoldingSetNodeID &ID) {
2590 Profile(ID, getElementType());
2591 }
2592
2593 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2594 ID.AddPointer(Element.getAsOpaquePtr());
2595 }
2596
2597 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2598};
2599
2600/// Sugar for parentheses used when specifying types.
2601class ParenType : public Type, public llvm::FoldingSetNode {
2602 friend class ASTContext; // ASTContext creates these.
2603
2604 QualType Inner;
2605
2606 ParenType(QualType InnerType, QualType CanonType)
2607 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2608
2609public:
2610 QualType getInnerType() const { return Inner; }
2611
2612 bool isSugared() const { return true; }
2613 QualType desugar() const { return getInnerType(); }
2614
2615 void Profile(llvm::FoldingSetNodeID &ID) {
2616 Profile(ID, getInnerType());
2617 }
2618
2619 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2620 Inner.Profile(ID);
2621 }
2622
2623 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2624};
2625
2626/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2627class PointerType : public Type, public llvm::FoldingSetNode {
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 QualType PointeeType;
2631
2632 PointerType(QualType Pointee, QualType CanonicalPtr)
2633 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2634 PointeeType(Pointee) {}
2635
2636public:
2637 QualType getPointeeType() const { return PointeeType; }
2638
2639 bool isSugared() const { return false; }
2640 QualType desugar() const { return QualType(this, 0); }
2641
2642 void Profile(llvm::FoldingSetNodeID &ID) {
2643 Profile(ID, getPointeeType());
2644 }
2645
2646 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2647 ID.AddPointer(Pointee.getAsOpaquePtr());
2648 }
2649
2650 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2651};
2652
2653/// Represents a type which was implicitly adjusted by the semantic
2654/// engine for arbitrary reasons. For example, array and function types can
2655/// decay, and function types can have their calling conventions adjusted.
2656class AdjustedType : public Type, public llvm::FoldingSetNode {
2657 QualType OriginalTy;
2658 QualType AdjustedTy;
2659
2660protected:
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2664 QualType CanonicalPtr)
2665 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2666 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2667
2668public:
2669 QualType getOriginalType() const { return OriginalTy; }
2670 QualType getAdjustedType() const { return AdjustedTy; }
2671
2672 bool isSugared() const { return true; }
2673 QualType desugar() const { return AdjustedTy; }
2674
2675 void Profile(llvm::FoldingSetNodeID &ID) {
2676 Profile(ID, OriginalTy, AdjustedTy);
2677 }
2678
2679 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2680 ID.AddPointer(Orig.getAsOpaquePtr());
2681 ID.AddPointer(New.getAsOpaquePtr());
2682 }
2683
2684 static bool classof(const Type *T) {
2685 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2686 }
2687};
2688
2689/// Represents a pointer type decayed from an array or function type.
2690class DecayedType : public AdjustedType {
2691 friend class ASTContext; // ASTContext creates these.
2692
2693 inline
2694 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2695
2696public:
2697 QualType getDecayedType() const { return getAdjustedType(); }
2698
2699 inline QualType getPointeeType() const;
2700
2701 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2702};
2703
2704/// Pointer to a block type.
2705/// This type is to represent types syntactically represented as
2706/// "void (^)(int)", etc. Pointee is required to always be a function type.
2707class BlockPointerType : public Type, public llvm::FoldingSetNode {
2708 friend class ASTContext; // ASTContext creates these.
2709
2710 // Block is some kind of pointer type
2711 QualType PointeeType;
2712
2713 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2714 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2715 PointeeType(Pointee) {}
2716
2717public:
2718 // Get the pointee type. Pointee is required to always be a function type.
2719 QualType getPointeeType() const { return PointeeType; }
2720
2721 bool isSugared() const { return false; }
2722 QualType desugar() const { return QualType(this, 0); }
2723
2724 void Profile(llvm::FoldingSetNodeID &ID) {
2725 Profile(ID, getPointeeType());
2726 }
2727
2728 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2729 ID.AddPointer(Pointee.getAsOpaquePtr());
2730 }
2731
2732 static bool classof(const Type *T) {
2733 return T->getTypeClass() == BlockPointer;
2734 }
2735};
2736
2737/// Base for LValueReferenceType and RValueReferenceType
2738class ReferenceType : public Type, public llvm::FoldingSetNode {
2739 QualType PointeeType;
2740
2741protected:
2742 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2743 bool SpelledAsLValue)
2744 : Type(tc, CanonicalRef, Referencee->getDependence()),
2745 PointeeType(Referencee) {
2746 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2747 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2748 }
2749
2750public:
2751 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2752 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2753
2754 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2755
2756 QualType getPointeeType() const {
2757 // FIXME: this might strip inner qualifiers; okay?
2758 const ReferenceType *T = this;
2759 while (T->isInnerRef())
2760 T = T->PointeeType->castAs<ReferenceType>();
2761 return T->PointeeType;
2762 }
2763
2764 void Profile(llvm::FoldingSetNodeID &ID) {
2765 Profile(ID, PointeeType, isSpelledAsLValue());
2766 }
2767
2768 static void Profile(llvm::FoldingSetNodeID &ID,
2769 QualType Referencee,
2770 bool SpelledAsLValue) {
2771 ID.AddPointer(Referencee.getAsOpaquePtr());
2772 ID.AddBoolean(SpelledAsLValue);
2773 }
2774
2775 static bool classof(const Type *T) {
2776 return T->getTypeClass() == LValueReference ||
2777 T->getTypeClass() == RValueReference;
2778 }
2779};
2780
2781/// An lvalue reference type, per C++11 [dcl.ref].
2782class LValueReferenceType : public ReferenceType {
2783 friend class ASTContext; // ASTContext creates these
2784
2785 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2786 bool SpelledAsLValue)
2787 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2788 SpelledAsLValue) {}
2789
2790public:
2791 bool isSugared() const { return false; }
2792 QualType desugar() const { return QualType(this, 0); }
2793
2794 static bool classof(const Type *T) {
2795 return T->getTypeClass() == LValueReference;
2796 }
2797};
2798
2799/// An rvalue reference type, per C++11 [dcl.ref].
2800class RValueReferenceType : public ReferenceType {
2801 friend class ASTContext; // ASTContext creates these
2802
2803 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2804 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2805
2806public:
2807 bool isSugared() const { return false; }
2808 QualType desugar() const { return QualType(this, 0); }
2809
2810 static bool classof(const Type *T) {
2811 return T->getTypeClass() == RValueReference;
2812 }
2813};
2814
2815/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2816///
2817/// This includes both pointers to data members and pointer to member functions.
2818class MemberPointerType : public Type, public llvm::FoldingSetNode {
2819 friend class ASTContext; // ASTContext creates these.
2820
2821 QualType PointeeType;
2822
2823 /// The class of which the pointee is a member. Must ultimately be a
2824 /// RecordType, but could be a typedef or a template parameter too.
2825 const Type *Class;
2826
2827 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2828 : Type(MemberPointer, CanonicalPtr,
2829 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2830 Pointee->getDependence()),
2831 PointeeType(Pointee), Class(Cls) {}
2832
2833public:
2834 QualType getPointeeType() const { return PointeeType; }
2835
2836 /// Returns true if the member type (i.e. the pointee type) is a
2837 /// function type rather than a data-member type.
2838 bool isMemberFunctionPointer() const {
2839 return PointeeType->isFunctionProtoType();
2840 }
2841
2842 /// Returns true if the member type (i.e. the pointee type) is a
2843 /// data type rather than a function type.
2844 bool isMemberDataPointer() const {
2845 return !PointeeType->isFunctionProtoType();
2846 }
2847
2848 const Type *getClass() const { return Class; }
2849 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2850
2851 bool isSugared() const { return false; }
2852 QualType desugar() const { return QualType(this, 0); }
2853
2854 void Profile(llvm::FoldingSetNodeID &ID) {
2855 Profile(ID, getPointeeType(), getClass());
2856 }
2857
2858 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2859 const Type *Class) {
2860 ID.AddPointer(Pointee.getAsOpaquePtr());
2861 ID.AddPointer(Class);
2862 }
2863
2864 static bool classof(const Type *T) {
2865 return T->getTypeClass() == MemberPointer;
2866 }
2867};
2868
2869/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2870class ArrayType : public Type, public llvm::FoldingSetNode {
2871public:
2872 /// Capture whether this is a normal array (e.g. int X[4])
2873 /// an array with a static size (e.g. int X[static 4]), or an array
2874 /// with a star size (e.g. int X[*]).
2875 /// 'static' is only allowed on function parameters.
2876 enum ArraySizeModifier {
2877 Normal, Static, Star
2878 };
2879
2880private:
2881 /// The element type of the array.
2882 QualType ElementType;
2883
2884protected:
2885 friend class ASTContext; // ASTContext creates these.
2886
2887 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2888 unsigned tq, const Expr *sz = nullptr);
2889
2890public:
2891 QualType getElementType() const { return ElementType; }
2892
2893 ArraySizeModifier getSizeModifier() const {
2894 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2895 }
2896
2897 Qualifiers getIndexTypeQualifiers() const {
2898 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2899 }
2900
2901 unsigned getIndexTypeCVRQualifiers() const {
2902 return ArrayTypeBits.IndexTypeQuals;
2903 }
2904
2905 static bool classof(const Type *T) {
2906 return T->getTypeClass() == ConstantArray ||
2907 T->getTypeClass() == VariableArray ||
2908 T->getTypeClass() == IncompleteArray ||
2909 T->getTypeClass() == DependentSizedArray;
2910 }
2911};
2912
2913/// Represents the canonical version of C arrays with a specified constant size.
2914/// For example, the canonical type for 'int A[4 + 4*100]' is a
2915/// ConstantArrayType where the element type is 'int' and the size is 404.
2916class ConstantArrayType final
2917 : public ArrayType,
2918 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2919 friend class ASTContext; // ASTContext creates these.
2920 friend TrailingObjects;
2921
2922 llvm::APInt Size; // Allows us to unique the type.
2923
2924 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2925 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2926 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2927 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2928 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2929 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 2929, __PRETTY_FUNCTION__))
;
2930 *getTrailingObjects<const Expr*>() = sz;
2931 }
2932 }
2933
2934 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2935 return ConstantArrayTypeBits.HasStoredSizeExpr;
2936 }
2937
2938public:
2939 const llvm::APInt &getSize() const { return Size; }
2940 const Expr *getSizeExpr() const {
2941 return ConstantArrayTypeBits.HasStoredSizeExpr
2942 ? *getTrailingObjects<const Expr *>()
2943 : nullptr;
2944 }
2945 bool isSugared() const { return false; }
2946 QualType desugar() const { return QualType(this, 0); }
2947
2948 /// Determine the number of bits required to address a member of
2949 // an array with the given element type and number of elements.
2950 static unsigned getNumAddressingBits(const ASTContext &Context,
2951 QualType ElementType,
2952 const llvm::APInt &NumElements);
2953
2954 /// Determine the maximum number of active bits that an array's size
2955 /// can require, which limits the maximum size of the array.
2956 static unsigned getMaxSizeBits(const ASTContext &Context);
2957
2958 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2959 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2960 getSizeModifier(), getIndexTypeCVRQualifiers());
2961 }
2962
2963 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2964 QualType ET, const llvm::APInt &ArraySize,
2965 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2966 unsigned TypeQuals);
2967
2968 static bool classof(const Type *T) {
2969 return T->getTypeClass() == ConstantArray;
2970 }
2971};
2972
2973/// Represents a C array with an unspecified size. For example 'int A[]' has
2974/// an IncompleteArrayType where the element type is 'int' and the size is
2975/// unspecified.
2976class IncompleteArrayType : public ArrayType {
2977 friend class ASTContext; // ASTContext creates these.
2978
2979 IncompleteArrayType(QualType et, QualType can,
2980 ArraySizeModifier sm, unsigned tq)
2981 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2982
2983public:
2984 friend class StmtIteratorBase;
2985
2986 bool isSugared() const { return false; }
2987 QualType desugar() const { return QualType(this, 0); }
2988
2989 static bool classof(const Type *T) {
2990 return T->getTypeClass() == IncompleteArray;
2991 }
2992
2993 void Profile(llvm::FoldingSetNodeID &ID) {
2994 Profile(ID, getElementType(), getSizeModifier(),
2995 getIndexTypeCVRQualifiers());
2996 }
2997
2998 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2999 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3000 ID.AddPointer(ET.getAsOpaquePtr());
3001 ID.AddInteger(SizeMod);
3002 ID.AddInteger(TypeQuals);
3003 }
3004};
3005
3006/// Represents a C array with a specified size that is not an
3007/// integer-constant-expression. For example, 'int s[x+foo()]'.
3008/// Since the size expression is an arbitrary expression, we store it as such.
3009///
3010/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3011/// should not be: two lexically equivalent variable array types could mean
3012/// different things, for example, these variables do not have the same type
3013/// dynamically:
3014///
3015/// void foo(int x) {
3016/// int Y[x];
3017/// ++x;
3018/// int Z[x];
3019/// }
3020class VariableArrayType : public ArrayType {
3021 friend class ASTContext; // ASTContext creates these.
3022
3023 /// An assignment-expression. VLA's are only permitted within
3024 /// a function block.
3025 Stmt *SizeExpr;
3026
3027 /// The range spanned by the left and right array brackets.
3028 SourceRange Brackets;
3029
3030 VariableArrayType(QualType et, QualType can, Expr *e,
3031 ArraySizeModifier sm, unsigned tq,
3032 SourceRange brackets)
3033 : ArrayType(VariableArray, et, can, sm, tq, e),
3034 SizeExpr((Stmt*) e), Brackets(brackets) {}
3035
3036public:
3037 friend class StmtIteratorBase;
3038
3039 Expr *getSizeExpr() const {
3040 // We use C-style casts instead of cast<> here because we do not wish
3041 // to have a dependency of Type.h on Stmt.h/Expr.h.
3042 return (Expr*) SizeExpr;
3043 }
3044
3045 SourceRange getBracketsRange() const { return Brackets; }
3046 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3047 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3048
3049 bool isSugared() const { return false; }
3050 QualType desugar() const { return QualType(this, 0); }
3051
3052 static bool classof(const Type *T) {
3053 return T->getTypeClass() == VariableArray;
3054 }
3055
3056 void Profile(llvm::FoldingSetNodeID &ID) {
3057 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 3057)
;
3058 }
3059};
3060
3061/// Represents an array type in C++ whose size is a value-dependent expression.
3062///
3063/// For example:
3064/// \code
3065/// template<typename T, int Size>
3066/// class array {
3067/// T data[Size];
3068/// };
3069/// \endcode
3070///
3071/// For these types, we won't actually know what the array bound is
3072/// until template instantiation occurs, at which point this will
3073/// become either a ConstantArrayType or a VariableArrayType.
3074class DependentSizedArrayType : public ArrayType {
3075 friend class ASTContext; // ASTContext creates these.
3076
3077 const ASTContext &Context;
3078
3079 /// An assignment expression that will instantiate to the
3080 /// size of the array.
3081 ///
3082 /// The expression itself might be null, in which case the array
3083 /// type will have its size deduced from an initializer.
3084 Stmt *SizeExpr;
3085
3086 /// The range spanned by the left and right array brackets.
3087 SourceRange Brackets;
3088
3089 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3090 Expr *e, ArraySizeModifier sm, unsigned tq,
3091 SourceRange brackets);
3092
3093public:
3094 friend class StmtIteratorBase;
3095
3096 Expr *getSizeExpr() const {
3097 // We use C-style casts instead of cast<> here because we do not wish
3098 // to have a dependency of Type.h on Stmt.h/Expr.h.
3099 return (Expr*) SizeExpr;
3100 }
3101
3102 SourceRange getBracketsRange() const { return Brackets; }
3103 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3104 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3105
3106 bool isSugared() const { return false; }
3107 QualType desugar() const { return QualType(this, 0); }
3108
3109 static bool classof(const Type *T) {
3110 return T->getTypeClass() == DependentSizedArray;
3111 }
3112
3113 void Profile(llvm::FoldingSetNodeID &ID) {
3114 Profile(ID, Context, getElementType(),
3115 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3116 }
3117
3118 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3119 QualType ET, ArraySizeModifier SizeMod,
3120 unsigned TypeQuals, Expr *E);
3121};
3122
3123/// Represents an extended address space qualifier where the input address space
3124/// value is dependent. Non-dependent address spaces are not represented with a
3125/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3126///
3127/// For example:
3128/// \code
3129/// template<typename T, int AddrSpace>
3130/// class AddressSpace {
3131/// typedef T __attribute__((address_space(AddrSpace))) type;
3132/// }
3133/// \endcode
3134class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3135 friend class ASTContext;
3136
3137 const ASTContext &Context;
3138 Expr *AddrSpaceExpr;
3139 QualType PointeeType;
3140 SourceLocation loc;
3141
3142 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3143 QualType can, Expr *AddrSpaceExpr,
3144 SourceLocation loc);
3145
3146public:
3147 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3148 QualType getPointeeType() const { return PointeeType; }
3149 SourceLocation getAttributeLoc() const { return loc; }
3150
3151 bool isSugared() const { return false; }
3152 QualType desugar() const { return QualType(this, 0); }
3153
3154 static bool classof(const Type *T) {
3155 return T->getTypeClass() == DependentAddressSpace;
3156 }
3157
3158 void Profile(llvm::FoldingSetNodeID &ID) {
3159 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3160 }
3161
3162 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3163 QualType PointeeType, Expr *AddrSpaceExpr);
3164};
3165
3166/// Represents an extended vector type where either the type or size is
3167/// dependent.
3168///
3169/// For example:
3170/// \code
3171/// template<typename T, int Size>
3172/// class vector {
3173/// typedef T __attribute__((ext_vector_type(Size))) type;
3174/// }
3175/// \endcode
3176class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3177 friend class ASTContext;
3178
3179 const ASTContext &Context;
3180 Expr *SizeExpr;
3181
3182 /// The element type of the array.
3183 QualType ElementType;
3184
3185 SourceLocation loc;
3186
3187 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3188 QualType can, Expr *SizeExpr, SourceLocation loc);
3189
3190public:
3191 Expr *getSizeExpr() const { return SizeExpr; }
3192 QualType getElementType() const { return ElementType; }
3193 SourceLocation getAttributeLoc() const { return loc; }
3194
3195 bool isSugared() const { return false; }
3196 QualType desugar() const { return QualType(this, 0); }
3197
3198 static bool classof(const Type *T) {
3199 return T->getTypeClass() == DependentSizedExtVector;
3200 }
3201
3202 void Profile(llvm::FoldingSetNodeID &ID) {
3203 Profile(ID, Context, getElementType(), getSizeExpr());
3204 }
3205
3206 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3207 QualType ElementType, Expr *SizeExpr);
3208};
3209
3210
3211/// Represents a GCC generic vector type. This type is created using
3212/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3213/// bytes; or from an Altivec __vector or vector declaration.
3214/// Since the constructor takes the number of vector elements, the
3215/// client is responsible for converting the size into the number of elements.
3216class VectorType : public Type, public llvm::FoldingSetNode {
3217public:
3218 enum VectorKind {
3219 /// not a target-specific vector type
3220 GenericVector,
3221
3222 /// is AltiVec vector
3223 AltiVecVector,
3224
3225 /// is AltiVec 'vector Pixel'
3226 AltiVecPixel,
3227
3228 /// is AltiVec 'vector bool ...'
3229 AltiVecBool,
3230
3231 /// is ARM Neon vector
3232 NeonVector,
3233
3234 /// is ARM Neon polynomial vector
3235 NeonPolyVector,
3236
3237 /// is AArch64 SVE fixed-length data vector
3238 SveFixedLengthDataVector,
3239
3240 /// is AArch64 SVE fixed-length predicate vector
3241 SveFixedLengthPredicateVector
3242 };
3243
3244protected:
3245 friend class ASTContext; // ASTContext creates these.
3246
3247 /// The element type of the vector.
3248 QualType ElementType;
3249
3250 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3251 VectorKind vecKind);
3252
3253 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3254 QualType canonType, VectorKind vecKind);
3255
3256public:
3257 QualType getElementType() const { return ElementType; }
3258 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3259
3260 bool isSugared() const { return false; }
3261 QualType desugar() const { return QualType(this, 0); }
3262
3263 VectorKind getVectorKind() const {
3264 return VectorKind(VectorTypeBits.VecKind);
3265 }
3266
3267 void Profile(llvm::FoldingSetNodeID &ID) {
3268 Profile(ID, getElementType(), getNumElements(),
3269 getTypeClass(), getVectorKind());
3270 }
3271
3272 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3273 unsigned NumElements, TypeClass TypeClass,
3274 VectorKind VecKind) {
3275 ID.AddPointer(ElementType.getAsOpaquePtr());
3276 ID.AddInteger(NumElements);
3277 ID.AddInteger(TypeClass);
3278 ID.AddInteger(VecKind);
3279 }
3280
3281 static bool classof(const Type *T) {
3282 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3283 }
3284};
3285
3286/// Represents a vector type where either the type or size is dependent.
3287////
3288/// For example:
3289/// \code
3290/// template<typename T, int Size>
3291/// class vector {
3292/// typedef T __attribute__((vector_size(Size))) type;
3293/// }
3294/// \endcode
3295class DependentVectorType : public Type, public llvm::FoldingSetNode {
3296 friend class ASTContext;
3297
3298 const ASTContext &Context;
3299 QualType ElementType;
3300 Expr *SizeExpr;
3301 SourceLocation Loc;
3302
3303 DependentVectorType(const ASTContext &Context, QualType ElementType,
3304 QualType CanonType, Expr *SizeExpr,
3305 SourceLocation Loc, VectorType::VectorKind vecKind);
3306
3307public:
3308 Expr *getSizeExpr() const { return SizeExpr; }
3309 QualType getElementType() const { return ElementType; }
3310 SourceLocation getAttributeLoc() const { return Loc; }
3311 VectorType::VectorKind getVectorKind() const {
3312 return VectorType::VectorKind(VectorTypeBits.VecKind);
3313 }
3314
3315 bool isSugared() const { return false; }
3316 QualType desugar() const { return QualType(this, 0); }
3317
3318 static bool classof(const Type *T) {
3319 return T->getTypeClass() == DependentVector;
3320 }
3321
3322 void Profile(llvm::FoldingSetNodeID &ID) {
3323 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3324 }
3325
3326 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3327 QualType ElementType, const Expr *SizeExpr,
3328 VectorType::VectorKind VecKind);
3329};
3330
3331/// ExtVectorType - Extended vector type. This type is created using
3332/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3333/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3334/// class enables syntactic extensions, like Vector Components for accessing
3335/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3336/// Shading Language).
3337class ExtVectorType : public VectorType {
3338 friend class ASTContext; // ASTContext creates these.
3339
3340 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3341 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3342
3343public:
3344 static int getPointAccessorIdx(char c) {
3345 switch (c) {
3346 default: return -1;
3347 case 'x': case 'r': return 0;
3348 case 'y': case 'g': return 1;
3349 case 'z': case 'b': return 2;
3350 case 'w': case 'a': return 3;
3351 }
3352 }
3353
3354 static int getNumericAccessorIdx(char c) {
3355 switch (c) {
3356 default: return -1;
3357 case '0': return 0;
3358 case '1': return 1;
3359 case '2': return 2;
3360 case '3': return 3;
3361 case '4': return 4;
3362 case '5': return 5;
3363 case '6': return 6;
3364 case '7': return 7;
3365 case '8': return 8;
3366 case '9': return 9;
3367 case 'A':
3368 case 'a': return 10;
3369 case 'B':
3370 case 'b': return 11;
3371 case 'C':
3372 case 'c': return 12;
3373 case 'D':
3374 case 'd': return 13;
3375 case 'E':
3376 case 'e': return 14;
3377 case 'F':
3378 case 'f': return 15;
3379 }
3380 }
3381
3382 static int getAccessorIdx(char c, bool isNumericAccessor) {
3383 if (isNumericAccessor)
3384 return getNumericAccessorIdx(c);
3385 else
3386 return getPointAccessorIdx(c);
3387 }
3388
3389 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3390 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3391 return unsigned(idx-1) < getNumElements();
3392 return false;
3393 }
3394
3395 bool isSugared() const { return false; }
3396 QualType desugar() const { return QualType(this, 0); }
3397
3398 static bool classof(const Type *T) {
3399 return T->getTypeClass() == ExtVector;
3400 }
3401};
3402
3403/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3404/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3405/// number of rows and "columns" specifies the number of columns.
3406class MatrixType : public Type, public llvm::FoldingSetNode {
3407protected:
3408 friend class ASTContext;
3409
3410 /// The element type of the matrix.
3411 QualType ElementType;
3412
3413 MatrixType(QualType ElementTy, QualType CanonElementTy);
3414
3415 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3416 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3417
3418public:
3419 /// Returns type of the elements being stored in the matrix
3420 QualType getElementType() const { return ElementType; }
3421
3422 /// Valid elements types are the following:
3423 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3424 /// and _Bool
3425 /// * the standard floating types float or double
3426 /// * a half-precision floating point type, if one is supported on the target
3427 static bool isValidElementType(QualType T) {
3428 return T->isDependentType() ||
3429 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3430 }
3431
3432 bool isSugared() const { return false; }
3433 QualType desugar() const { return QualType(this, 0); }
3434
3435 static bool classof(const Type *T) {
3436 return T->getTypeClass() == ConstantMatrix ||
3437 T->getTypeClass() == DependentSizedMatrix;
3438 }
3439};
3440
3441/// Represents a concrete matrix type with constant number of rows and columns
3442class ConstantMatrixType final : public MatrixType {
3443protected:
3444 friend class ASTContext;
3445
3446 /// The element type of the matrix.
3447 // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3448 QualType ElementType;
3449
3450 /// Number of rows and columns.
3451 unsigned NumRows;
3452 unsigned NumColumns;
3453
3454 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3455
3456 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3457 unsigned NColumns, QualType CanonElementType);
3458
3459 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3460 unsigned NColumns, QualType CanonElementType);
3461
3462public:
3463 /// Returns the number of rows in the matrix.
3464 unsigned getNumRows() const { return NumRows; }
3465
3466 /// Returns the number of columns in the matrix.
3467 unsigned getNumColumns() const { return NumColumns; }
3468
3469 /// Returns the number of elements required to embed the matrix into a vector.
3470 unsigned getNumElementsFlattened() const {
3471 return getNumRows() * getNumColumns();
3472 }
3473
3474 /// Returns true if \p NumElements is a valid matrix dimension.
3475 static constexpr bool isDimensionValid(size_t NumElements) {
3476 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3477 }
3478
3479 /// Returns the maximum number of elements per dimension.
3480 static constexpr unsigned getMaxElementsPerDimension() {
3481 return MaxElementsPerDimension;
3482 }
3483
3484 void Profile(llvm::FoldingSetNodeID &ID) {
3485 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3486 getTypeClass());
3487 }
3488
3489 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3490 unsigned NumRows, unsigned NumColumns,
3491 TypeClass TypeClass) {
3492 ID.AddPointer(ElementType.getAsOpaquePtr());
3493 ID.AddInteger(NumRows);
3494 ID.AddInteger(NumColumns);
3495 ID.AddInteger(TypeClass);
3496 }
3497
3498 static bool classof(const Type *T) {
3499 return T->getTypeClass() == ConstantMatrix;
3500 }
3501};
3502
3503/// Represents a matrix type where the type and the number of rows and columns
3504/// is dependent on a template.
3505class DependentSizedMatrixType final : public MatrixType {
3506 friend class ASTContext;
3507
3508 const ASTContext &Context;
3509 Expr *RowExpr;
3510 Expr *ColumnExpr;
3511
3512 SourceLocation loc;
3513
3514 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3515 QualType CanonicalType, Expr *RowExpr,
3516 Expr *ColumnExpr, SourceLocation loc);
3517
3518public:
3519 QualType getElementType() const { return ElementType; }
3520 Expr *getRowExpr() const { return RowExpr; }
3521 Expr *getColumnExpr() const { return ColumnExpr; }
3522 SourceLocation getAttributeLoc() const { return loc; }
3523
3524 bool isSugared() const { return false; }
3525 QualType desugar() const { return QualType(this, 0); }
3526
3527 static bool classof(const Type *T) {
3528 return T->getTypeClass() == DependentSizedMatrix;
3529 }
3530
3531 void Profile(llvm::FoldingSetNodeID &ID) {
3532 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3533 }
3534
3535 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3536 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3537};
3538
3539/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3540/// class of FunctionNoProtoType and FunctionProtoType.
3541class FunctionType : public Type {
3542 // The type returned by the function.
3543 QualType ResultType;
3544
3545public:
3546 /// Interesting information about a specific parameter that can't simply
3547 /// be reflected in parameter's type. This is only used by FunctionProtoType
3548 /// but is in FunctionType to make this class available during the
3549 /// specification of the bases of FunctionProtoType.
3550 ///
3551 /// It makes sense to model language features this way when there's some
3552 /// sort of parameter-specific override (such as an attribute) that
3553 /// affects how the function is called. For example, the ARC ns_consumed
3554 /// attribute changes whether a parameter is passed at +0 (the default)
3555 /// or +1 (ns_consumed). This must be reflected in the function type,
3556 /// but isn't really a change to the parameter type.
3557 ///
3558 /// One serious disadvantage of modelling language features this way is
3559 /// that they generally do not work with language features that attempt
3560 /// to destructure types. For example, template argument deduction will
3561 /// not be able to match a parameter declared as
3562 /// T (*)(U)
3563 /// against an argument of type
3564 /// void (*)(__attribute__((ns_consumed)) id)
3565 /// because the substitution of T=void, U=id into the former will
3566 /// not produce the latter.
3567 class ExtParameterInfo {
3568 enum {
3569 ABIMask = 0x0F,
3570 IsConsumed = 0x10,
3571 HasPassObjSize = 0x20,
3572 IsNoEscape = 0x40,
3573 };
3574 unsigned char Data = 0;
3575
3576 public:
3577 ExtParameterInfo() = default;
3578
3579 /// Return the ABI treatment of this parameter.
3580 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3581 ExtParameterInfo withABI(ParameterABI kind) const {
3582 ExtParameterInfo copy = *this;
3583 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3584 return copy;
3585 }
3586
3587 /// Is this parameter considered "consumed" by Objective-C ARC?
3588 /// Consumed parameters must have retainable object type.
3589 bool isConsumed() const { return (Data & IsConsumed); }
3590 ExtParameterInfo withIsConsumed(bool consumed) const {
3591 ExtParameterInfo copy = *this;
3592 if (consumed)
3593 copy.Data |= IsConsumed;
3594 else
3595 copy.Data &= ~IsConsumed;
3596 return copy;
3597 }
3598
3599 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3600 ExtParameterInfo withHasPassObjectSize() const {
3601 ExtParameterInfo Copy = *this;
3602 Copy.Data |= HasPassObjSize;
3603 return Copy;
3604 }
3605
3606 bool isNoEscape() const { return Data & IsNoEscape; }
3607 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3608 ExtParameterInfo Copy = *this;
3609 if (NoEscape)
3610 Copy.Data |= IsNoEscape;
3611 else
3612 Copy.Data &= ~IsNoEscape;
3613 return Copy;
3614 }
3615
3616 unsigned char getOpaqueValue() const { return Data; }
3617 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3618 ExtParameterInfo result;
3619 result.Data = data;
3620 return result;
3621 }
3622
3623 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3624 return lhs.Data == rhs.Data;
3625 }
3626
3627 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3628 return lhs.Data != rhs.Data;
3629 }
3630 };
3631
3632 /// A class which abstracts out some details necessary for
3633 /// making a call.
3634 ///
3635 /// It is not actually used directly for storing this information in
3636 /// a FunctionType, although FunctionType does currently use the
3637 /// same bit-pattern.
3638 ///
3639 // If you add a field (say Foo), other than the obvious places (both,
3640 // constructors, compile failures), what you need to update is
3641 // * Operator==
3642 // * getFoo
3643 // * withFoo
3644 // * functionType. Add Foo, getFoo.
3645 // * ASTContext::getFooType
3646 // * ASTContext::mergeFunctionTypes
3647 // * FunctionNoProtoType::Profile
3648 // * FunctionProtoType::Profile
3649 // * TypePrinter::PrintFunctionProto
3650 // * AST read and write
3651 // * Codegen
3652 class ExtInfo {
3653 friend class FunctionType;
3654
3655 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3656 // adjust the Bits field below, and if you add bits, you'll need to adjust
3657 // Type::FunctionTypeBitfields::ExtInfo as well.
3658
3659 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3660 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3661 //
3662 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3663 enum { CallConvMask = 0x1F };
3664 enum { NoReturnMask = 0x20 };
3665 enum { ProducesResultMask = 0x40 };
3666 enum { NoCallerSavedRegsMask = 0x80 };
3667 enum {
3668 RegParmMask = 0x700,
3669 RegParmOffset = 8
3670 };
3671 enum { NoCfCheckMask = 0x800 };
3672 enum { CmseNSCallMask = 0x1000 };
3673 uint16_t Bits = CC_C;
3674
3675 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3676
3677 public:
3678 // Constructor with no defaults. Use this when you know that you
3679 // have all the elements (when reading an AST file for example).
3680 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3681 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3682 bool cmseNSCall) {
3683 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 3683, __PRETTY_FUNCTION__))
;
3684 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3685 (producesResult ? ProducesResultMask : 0) |
3686 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3687 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3688 (NoCfCheck ? NoCfCheckMask : 0) |
3689 (cmseNSCall ? CmseNSCallMask : 0);
3690 }
3691
3692 // Constructor with all defaults. Use when for example creating a
3693 // function known to use defaults.
3694 ExtInfo() = default;
3695
3696 // Constructor with just the calling convention, which is an important part
3697 // of the canonical type.
3698 ExtInfo(CallingConv CC) : Bits(CC) {}
3699
3700 bool getNoReturn() const { return Bits & NoReturnMask; }
3701 bool getProducesResult() const { return Bits & ProducesResultMask; }
3702 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3703 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3704 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3705 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3706
3707 unsigned getRegParm() const {
3708 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3709 if (RegParm > 0)
3710 --RegParm;
3711 return RegParm;
3712 }
3713
3714 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3715
3716 bool operator==(ExtInfo Other) const {
3717 return Bits == Other.Bits;
3718 }
3719 bool operator!=(ExtInfo Other) const {
3720 return Bits != Other.Bits;
3721 }
3722
3723 // Note that we don't have setters. That is by design, use
3724 // the following with methods instead of mutating these objects.
3725
3726 ExtInfo withNoReturn(bool noReturn) const {
3727 if (noReturn)
3728 return ExtInfo(Bits | NoReturnMask);
3729 else
3730 return ExtInfo(Bits & ~NoReturnMask);
3731 }
3732
3733 ExtInfo withProducesResult(bool producesResult) const {
3734 if (producesResult)
3735 return ExtInfo(Bits | ProducesResultMask);
3736 else
3737 return ExtInfo(Bits & ~ProducesResultMask);
3738 }
3739
3740 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3741 if (cmseNSCall)
3742 return ExtInfo(Bits | CmseNSCallMask);
3743 else
3744 return ExtInfo(Bits & ~CmseNSCallMask);
3745 }
3746
3747 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3748 if (noCallerSavedRegs)
3749 return ExtInfo(Bits | NoCallerSavedRegsMask);
3750 else
3751 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3752 }
3753
3754 ExtInfo withNoCfCheck(bool noCfCheck) const {
3755 if (noCfCheck)
3756 return ExtInfo(Bits | NoCfCheckMask);
3757 else
3758 return ExtInfo(Bits & ~NoCfCheckMask);
3759 }
3760
3761 ExtInfo withRegParm(unsigned RegParm) const {
3762 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 3762, __PRETTY_FUNCTION__))
;
3763 return ExtInfo((Bits & ~RegParmMask) |
3764 ((RegParm + 1) << RegParmOffset));
3765 }
3766
3767 ExtInfo withCallingConv(CallingConv cc) const {
3768 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3769 }
3770
3771 void Profile(llvm::FoldingSetNodeID &ID) const {
3772 ID.AddInteger(Bits);
3773 }
3774 };
3775
3776 /// A simple holder for a QualType representing a type in an
3777 /// exception specification. Unfortunately needed by FunctionProtoType
3778 /// because TrailingObjects cannot handle repeated types.
3779 struct ExceptionType { QualType Type; };
3780
3781 /// A simple holder for various uncommon bits which do not fit in
3782 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3783 /// alignment of subsequent objects in TrailingObjects. You must update
3784 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3785 struct alignas(void *) FunctionTypeExtraBitfields {
3786 /// The number of types in the exception specification.
3787 /// A whole unsigned is not needed here and according to
3788 /// [implimits] 8 bits would be enough here.
3789 unsigned NumExceptionType;
3790 };
3791
3792protected:
3793 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3794 TypeDependence Dependence, ExtInfo Info)
3795 : Type(tc, Canonical, Dependence), ResultType(res) {
3796 FunctionTypeBits.ExtInfo = Info.Bits;
3797 }
3798
3799 Qualifiers getFastTypeQuals() const {
3800 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3801 }
3802
3803public:
3804 QualType getReturnType() const { return ResultType; }
3805
3806 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3807 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3808
3809 /// Determine whether this function type includes the GNU noreturn
3810 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3811 /// type.
3812 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3813
3814 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3815 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3816 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3817
3818 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3819 "Const, volatile and restrict are assumed to be a subset of "
3820 "the fast qualifiers.");
3821
3822 bool isConst() const { return getFastTypeQuals().hasConst(); }
3823 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3824 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3825
3826 /// Determine the type of an expression that calls a function of
3827 /// this type.
3828 QualType getCallResultType(const ASTContext &Context) const {
3829 return getReturnType().getNonLValueExprType(Context);
3830 }
3831
3832 static StringRef getNameForCallConv(CallingConv CC);
3833
3834 static bool classof(const Type *T) {
3835 return T->getTypeClass() == FunctionNoProto ||
3836 T->getTypeClass() == FunctionProto;
3837 }
3838};
3839
3840/// Represents a K&R-style 'int foo()' function, which has
3841/// no information available about its arguments.
3842class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3843 friend class ASTContext; // ASTContext creates these.
3844
3845 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3846 : FunctionType(FunctionNoProto, Result, Canonical,
3847 Result->getDependence() &
3848 ~(TypeDependence::DependentInstantiation |
3849 TypeDependence::UnexpandedPack),
3850 Info) {}
3851
3852public:
3853 // No additional state past what FunctionType provides.
3854
3855 bool isSugared() const { return false; }
3856 QualType desugar() const { return QualType(this, 0); }
3857
3858 void Profile(llvm::FoldingSetNodeID &ID) {
3859 Profile(ID, getReturnType(), getExtInfo());
3860 }
3861
3862 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3863 ExtInfo Info) {
3864 Info.Profile(ID);
3865 ID.AddPointer(ResultType.getAsOpaquePtr());
3866 }
3867
3868 static bool classof(const Type *T) {
3869 return T->getTypeClass() == FunctionNoProto;
3870 }
3871};
3872
3873/// Represents a prototype with parameter type info, e.g.
3874/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3875/// parameters, not as having a single void parameter. Such a type can have
3876/// an exception specification, but this specification is not part of the
3877/// canonical type. FunctionProtoType has several trailing objects, some of
3878/// which optional. For more information about the trailing objects see
3879/// the first comment inside FunctionProtoType.
3880class FunctionProtoType final
3881 : public FunctionType,
3882 public llvm::FoldingSetNode,
3883 private llvm::TrailingObjects<
3884 FunctionProtoType, QualType, SourceLocation,
3885 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3886 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3887 friend class ASTContext; // ASTContext creates these.
3888 friend TrailingObjects;
3889
3890 // FunctionProtoType is followed by several trailing objects, some of
3891 // which optional. They are in order:
3892 //
3893 // * An array of getNumParams() QualType holding the parameter types.
3894 // Always present. Note that for the vast majority of FunctionProtoType,
3895 // these will be the only trailing objects.
3896 //
3897 // * Optionally if the function is variadic, the SourceLocation of the
3898 // ellipsis.
3899 //
3900 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3901 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3902 // a single FunctionTypeExtraBitfields. Present if and only if
3903 // hasExtraBitfields() is true.
3904 //
3905 // * Optionally exactly one of:
3906 // * an array of getNumExceptions() ExceptionType,
3907 // * a single Expr *,
3908 // * a pair of FunctionDecl *,
3909 // * a single FunctionDecl *
3910 // used to store information about the various types of exception
3911 // specification. See getExceptionSpecSize for the details.
3912 //
3913 // * Optionally an array of getNumParams() ExtParameterInfo holding
3914 // an ExtParameterInfo for each of the parameters. Present if and
3915 // only if hasExtParameterInfos() is true.
3916 //
3917 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3918 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3919 // if hasExtQualifiers() is true.
3920 //
3921 // The optional FunctionTypeExtraBitfields has to be before the data
3922 // related to the exception specification since it contains the number
3923 // of exception types.
3924 //
3925 // We put the ExtParameterInfos last. If all were equal, it would make
3926 // more sense to put these before the exception specification, because
3927 // it's much easier to skip past them compared to the elaborate switch
3928 // required to skip the exception specification. However, all is not
3929 // equal; ExtParameterInfos are used to model very uncommon features,
3930 // and it's better not to burden the more common paths.
3931
3932public:
3933 /// Holds information about the various types of exception specification.
3934 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3935 /// used to group together the various bits of information about the
3936 /// exception specification.
3937 struct ExceptionSpecInfo {
3938 /// The kind of exception specification this is.
3939 ExceptionSpecificationType Type = EST_None;
3940
3941 /// Explicitly-specified list of exception types.
3942 ArrayRef<QualType> Exceptions;
3943
3944 /// Noexcept expression, if this is a computed noexcept specification.
3945 Expr *NoexceptExpr = nullptr;
3946
3947 /// The function whose exception specification this is, for
3948 /// EST_Unevaluated and EST_Uninstantiated.
3949 FunctionDecl *SourceDecl = nullptr;
3950
3951 /// The function template whose exception specification this is instantiated
3952 /// from, for EST_Uninstantiated.
3953 FunctionDecl *SourceTemplate = nullptr;
3954
3955 ExceptionSpecInfo() = default;
3956
3957 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3958 };
3959
3960 /// Extra information about a function prototype. ExtProtoInfo is not
3961 /// stored as such in FunctionProtoType but is used to group together
3962 /// the various bits of extra information about a function prototype.
3963 struct ExtProtoInfo {
3964 FunctionType::ExtInfo ExtInfo;
3965 bool Variadic : 1;
3966 bool HasTrailingReturn : 1;
3967 Qualifiers TypeQuals;
3968 RefQualifierKind RefQualifier = RQ_None;
3969 ExceptionSpecInfo ExceptionSpec;
3970 const ExtParameterInfo *ExtParameterInfos = nullptr;
3971 SourceLocation EllipsisLoc;
3972
3973 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3974
3975 ExtProtoInfo(CallingConv CC)
3976 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3977
3978 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3979 ExtProtoInfo Result(*this);
3980 Result.ExceptionSpec = ESI;
3981 return Result;
3982 }
3983 };
3984
3985private:
3986 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3987 return getNumParams();
3988 }
3989
3990 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3991 return isVariadic();
3992 }
3993
3994 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3995 return hasExtraBitfields();
3996 }
3997
3998 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3999 return getExceptionSpecSize().NumExceptionType;
4000 }
4001
4002 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4003 return getExceptionSpecSize().NumExprPtr;
4004 }
4005
4006 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4007 return getExceptionSpecSize().NumFunctionDeclPtr;
4008 }
4009
4010 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4011 return hasExtParameterInfos() ? getNumParams() : 0;
4012 }
4013
4014 /// Determine whether there are any argument types that
4015 /// contain an unexpanded parameter pack.
4016 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4017 unsigned numArgs) {
4018 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4019 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4020 return true;
4021
4022 return false;
4023 }
4024
4025 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4026 QualType canonical, const ExtProtoInfo &epi);
4027
4028 /// This struct is returned by getExceptionSpecSize and is used to
4029 /// translate an ExceptionSpecificationType to the number and kind
4030 /// of trailing objects related to the exception specification.
4031 struct ExceptionSpecSizeHolder {
4032 unsigned NumExceptionType;
4033 unsigned NumExprPtr;
4034 unsigned NumFunctionDeclPtr;
4035 };
4036
4037 /// Return the number and kind of trailing objects
4038 /// related to the exception specification.
4039 static ExceptionSpecSizeHolder
4040 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4041 switch (EST) {
4042 case EST_None:
4043 case EST_DynamicNone:
4044 case EST_MSAny:
4045 case EST_BasicNoexcept:
4046 case EST_Unparsed:
4047 case EST_NoThrow:
4048 return {0, 0, 0};
4049
4050 case EST_Dynamic:
4051 return {NumExceptions, 0, 0};
4052
4053 case EST_DependentNoexcept:
4054 case EST_NoexceptFalse:
4055 case EST_NoexceptTrue:
4056 return {0, 1, 0};
4057
4058 case EST_Uninstantiated:
4059 return {0, 0, 2};
4060
4061 case EST_Unevaluated:
4062 return {0, 0, 1};
4063 }
4064 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4064)
;
4065 }
4066
4067 /// Return the number and kind of trailing objects
4068 /// related to the exception specification.
4069 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4070 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4071 }
4072
4073 /// Whether the trailing FunctionTypeExtraBitfields is present.
4074 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4075 // If the exception spec type is EST_Dynamic then we have > 0 exception
4076 // types and the exact number is stored in FunctionTypeExtraBitfields.
4077 return EST == EST_Dynamic;
4078 }
4079
4080 /// Whether the trailing FunctionTypeExtraBitfields is present.
4081 bool hasExtraBitfields() const {
4082 return hasExtraBitfields(getExceptionSpecType());
4083 }
4084
4085 bool hasExtQualifiers() const {
4086 return FunctionTypeBits.HasExtQuals;
4087 }
4088
4089public:
4090 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4091
4092 QualType getParamType(unsigned i) const {
4093 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4093, __PRETTY_FUNCTION__))
;
4094 return param_type_begin()[i];
4095 }
4096
4097 ArrayRef<QualType> getParamTypes() const {
4098 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4099 }
4100
4101 ExtProtoInfo getExtProtoInfo() const {
4102 ExtProtoInfo EPI;
4103 EPI.ExtInfo = getExtInfo();
4104 EPI.Variadic = isVariadic();
4105 EPI.EllipsisLoc = getEllipsisLoc();
4106 EPI.HasTrailingReturn = hasTrailingReturn();
4107 EPI.ExceptionSpec = getExceptionSpecInfo();
4108 EPI.TypeQuals = getMethodQuals();
4109 EPI.RefQualifier = getRefQualifier();
4110 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4111 return EPI;
4112 }
4113
4114 /// Get the kind of exception specification on this function.
4115 ExceptionSpecificationType getExceptionSpecType() const {
4116 return static_cast<ExceptionSpecificationType>(
4117 FunctionTypeBits.ExceptionSpecType);
4118 }
4119
4120 /// Return whether this function has any kind of exception spec.
4121 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4122
4123 /// Return whether this function has a dynamic (throw) exception spec.
4124 bool hasDynamicExceptionSpec() const {
4125 return isDynamicExceptionSpec(getExceptionSpecType());
4126 }
4127
4128 /// Return whether this function has a noexcept exception spec.
4129 bool hasNoexceptExceptionSpec() const {
4130 return isNoexceptExceptionSpec(getExceptionSpecType());
4131 }
4132
4133 /// Return whether this function has a dependent exception spec.
4134 bool hasDependentExceptionSpec() const;
4135
4136 /// Return whether this function has an instantiation-dependent exception
4137 /// spec.
4138 bool hasInstantiationDependentExceptionSpec() const;
4139
4140 /// Return all the available information about this type's exception spec.
4141 ExceptionSpecInfo getExceptionSpecInfo() const {
4142 ExceptionSpecInfo Result;
4143 Result.Type = getExceptionSpecType();
4144 if (Result.Type == EST_Dynamic) {
4145 Result.Exceptions = exceptions();
4146 } else if (isComputedNoexcept(Result.Type)) {
4147 Result.NoexceptExpr = getNoexceptExpr();
4148 } else if (Result.Type == EST_Uninstantiated) {
4149 Result.SourceDecl = getExceptionSpecDecl();
4150 Result.SourceTemplate = getExceptionSpecTemplate();
4151 } else if (Result.Type == EST_Unevaluated) {
4152 Result.SourceDecl = getExceptionSpecDecl();
4153 }
4154 return Result;
4155 }
4156
4157 /// Return the number of types in the exception specification.
4158 unsigned getNumExceptions() const {
4159 return getExceptionSpecType() == EST_Dynamic
4160 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4161 ->NumExceptionType
4162 : 0;
4163 }
4164
4165 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4166 QualType getExceptionType(unsigned i) const {
4167 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4167, __PRETTY_FUNCTION__))
;
4168 return exception_begin()[i];
4169 }
4170
4171 /// Return the expression inside noexcept(expression), or a null pointer
4172 /// if there is none (because the exception spec is not of this form).
4173 Expr *getNoexceptExpr() const {
4174 if (!isComputedNoexcept(getExceptionSpecType()))
4175 return nullptr;
4176 return *getTrailingObjects<Expr *>();
4177 }
4178
4179 /// If this function type has an exception specification which hasn't
4180 /// been determined yet (either because it has not been evaluated or because
4181 /// it has not been instantiated), this is the function whose exception
4182 /// specification is represented by this type.
4183 FunctionDecl *getExceptionSpecDecl() const {
4184 if (getExceptionSpecType() != EST_Uninstantiated &&
4185 getExceptionSpecType() != EST_Unevaluated)
4186 return nullptr;
4187 return getTrailingObjects<FunctionDecl *>()[0];
4188 }
4189
4190 /// If this function type has an uninstantiated exception
4191 /// specification, this is the function whose exception specification
4192 /// should be instantiated to find the exception specification for
4193 /// this type.
4194 FunctionDecl *getExceptionSpecTemplate() const {
4195 if (getExceptionSpecType() != EST_Uninstantiated)
4196 return nullptr;
4197 return getTrailingObjects<FunctionDecl *>()[1];
4198 }
4199
4200 /// Determine whether this function type has a non-throwing exception
4201 /// specification.
4202 CanThrowResult canThrow() const;
4203
4204 /// Determine whether this function type has a non-throwing exception
4205 /// specification. If this depends on template arguments, returns
4206 /// \c ResultIfDependent.
4207 bool isNothrow(bool ResultIfDependent = false) const {
4208 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4209 }
4210
4211 /// Whether this function prototype is variadic.
4212 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4213
4214 SourceLocation getEllipsisLoc() const {
4215 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4216 : SourceLocation();
4217 }
4218
4219 /// Determines whether this function prototype contains a
4220 /// parameter pack at the end.
4221 ///
4222 /// A function template whose last parameter is a parameter pack can be
4223 /// called with an arbitrary number of arguments, much like a variadic
4224 /// function.
4225 bool isTemplateVariadic() const;
4226
4227 /// Whether this function prototype has a trailing return type.
4228 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4229
4230 Qualifiers getMethodQuals() const {
4231 if (hasExtQualifiers())
4232 return *getTrailingObjects<Qualifiers>();
4233 else
4234 return getFastTypeQuals();
4235 }
4236
4237 /// Retrieve the ref-qualifier associated with this function type.
4238 RefQualifierKind getRefQualifier() const {
4239 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4240 }
4241
4242 using param_type_iterator = const QualType *;
4243 using param_type_range = llvm::iterator_range<param_type_iterator>;
4244
4245 param_type_range param_types() const {
4246 return param_type_range(param_type_begin(), param_type_end());
4247 }
4248
4249 param_type_iterator param_type_begin() const {
4250 return getTrailingObjects<QualType>();
4251 }
4252
4253 param_type_iterator param_type_end() const {
4254 return param_type_begin() + getNumParams();
4255 }
4256
4257 using exception_iterator = const QualType *;
4258
4259 ArrayRef<QualType> exceptions() const {
4260 return llvm::makeArrayRef(exception_begin(), exception_end());
4261 }
4262
4263 exception_iterator exception_begin() const {
4264 return reinterpret_cast<exception_iterator>(
4265 getTrailingObjects<ExceptionType>());
4266 }
4267
4268 exception_iterator exception_end() const {
4269 return exception_begin() + getNumExceptions();
4270 }
4271
4272 /// Is there any interesting extra information for any of the parameters
4273 /// of this function type?
4274 bool hasExtParameterInfos() const {
4275 return FunctionTypeBits.HasExtParameterInfos;
4276 }
4277
4278 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4279 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4279, __PRETTY_FUNCTION__))
;
4280 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4281 getNumParams());
4282 }
4283
4284 /// Return a pointer to the beginning of the array of extra parameter
4285 /// information, if present, or else null if none of the parameters
4286 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4287 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4288 if (!hasExtParameterInfos())
4289 return nullptr;
4290 return getTrailingObjects<ExtParameterInfo>();
4291 }
4292
4293 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4294 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4294, __PRETTY_FUNCTION__))
;
4295 if (hasExtParameterInfos())
4296 return getTrailingObjects<ExtParameterInfo>()[I];
4297 return ExtParameterInfo();
4298 }
4299
4300 ParameterABI getParameterABI(unsigned I) const {
4301 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4301, __PRETTY_FUNCTION__))
;
4302 if (hasExtParameterInfos())
4303 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4304 return ParameterABI::Ordinary;
4305 }
4306
4307 bool isParamConsumed(unsigned I) const {
4308 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4308, __PRETTY_FUNCTION__))
;
4309 if (hasExtParameterInfos())
4310 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4311 return false;
4312 }
4313
4314 bool isSugared() const { return false; }
4315 QualType desugar() const { return QualType(this, 0); }
4316
4317 void printExceptionSpecification(raw_ostream &OS,
4318 const PrintingPolicy &Policy) const;
4319
4320 static bool classof(const Type *T) {
4321 return T->getTypeClass() == FunctionProto;
4322 }
4323
4324 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4325 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4326 param_type_iterator ArgTys, unsigned NumArgs,
4327 const ExtProtoInfo &EPI, const ASTContext &Context,
4328 bool Canonical);
4329};
4330
4331/// Represents the dependent type named by a dependently-scoped
4332/// typename using declaration, e.g.
4333/// using typename Base<T>::foo;
4334///
4335/// Template instantiation turns these into the underlying type.
4336class UnresolvedUsingType : public Type {
4337 friend class ASTContext; // ASTContext creates these.
4338
4339 UnresolvedUsingTypenameDecl *Decl;
4340
4341 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4342 : Type(UnresolvedUsing, QualType(),
4343 TypeDependence::DependentInstantiation),
4344 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4345
4346public:
4347 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4348
4349 bool isSugared() const { return false; }
4350 QualType desugar() const { return QualType(this, 0); }
4351
4352 static bool classof(const Type *T) {
4353 return T->getTypeClass() == UnresolvedUsing;
4354 }
4355
4356 void Profile(llvm::FoldingSetNodeID &ID) {
4357 return Profile(ID, Decl);
4358 }
4359
4360 static void Profile(llvm::FoldingSetNodeID &ID,
4361 UnresolvedUsingTypenameDecl *D) {
4362 ID.AddPointer(D);
4363 }
4364};
4365
4366class TypedefType : public Type {
4367 TypedefNameDecl *Decl;
4368
4369private:
4370 friend class ASTContext; // ASTContext creates these.
4371
4372 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4373 QualType can);
4374
4375public:
4376 TypedefNameDecl *getDecl() const { return Decl; }
4377
4378 bool isSugared() const { return true; }
4379 QualType desugar() const;
4380
4381 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4382};
4383
4384/// Sugar type that represents a type that was qualified by a qualifier written
4385/// as a macro invocation.
4386class MacroQualifiedType : public Type {
4387 friend class ASTContext; // ASTContext creates these.
4388
4389 QualType UnderlyingTy;
4390 const IdentifierInfo *MacroII;
4391
4392 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4393 const IdentifierInfo *MacroII)
4394 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4395 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4396 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4397, __PRETTY_FUNCTION__))
4397 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4397, __PRETTY_FUNCTION__))
;
4398 }
4399
4400public:
4401 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4402 QualType getUnderlyingType() const { return UnderlyingTy; }
4403
4404 /// Return this attributed type's modified type with no qualifiers attached to
4405 /// it.
4406 QualType getModifiedType() const;
4407
4408 bool isSugared() const { return true; }
4409 QualType desugar() const;
4410
4411 static bool classof(const Type *T) {
4412 return T->getTypeClass() == MacroQualified;
4413 }
4414};
4415
4416/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4417class TypeOfExprType : public Type {
4418 Expr *TOExpr;
4419
4420protected:
4421 friend class ASTContext; // ASTContext creates these.
4422
4423 TypeOfExprType(Expr *E, QualType can = QualType());
4424
4425public:
4426 Expr *getUnderlyingExpr() const { return TOExpr; }
4427
4428 /// Remove a single level of sugar.
4429 QualType desugar() const;
4430
4431 /// Returns whether this type directly provides sugar.
4432 bool isSugared() const;
4433
4434 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4435};
4436
4437/// Internal representation of canonical, dependent
4438/// `typeof(expr)` types.
4439///
4440/// This class is used internally by the ASTContext to manage
4441/// canonical, dependent types, only. Clients will only see instances
4442/// of this class via TypeOfExprType nodes.
4443class DependentTypeOfExprType
4444 : public TypeOfExprType, public llvm::FoldingSetNode {
4445 const ASTContext &Context;
4446
4447public:
4448 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4449 : TypeOfExprType(E), Context(Context) {}
4450
4451 void Profile(llvm::FoldingSetNodeID &ID) {
4452 Profile(ID, Context, getUnderlyingExpr());
4453 }
4454
4455 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4456 Expr *E);
4457};
4458
4459/// Represents `typeof(type)`, a GCC extension.
4460class TypeOfType : public Type {
4461 friend class ASTContext; // ASTContext creates these.
4462
4463 QualType TOType;
4464
4465 TypeOfType(QualType T, QualType can)
4466 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4467 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4467, __PRETTY_FUNCTION__))
;
4468 }
4469
4470public:
4471 QualType getUnderlyingType() const { return TOType; }
4472
4473 /// Remove a single level of sugar.
4474 QualType desugar() const { return getUnderlyingType(); }
4475
4476 /// Returns whether this type directly provides sugar.
4477 bool isSugared() const { return true; }
4478
4479 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4480};
4481
4482/// Represents the type `decltype(expr)` (C++11).
4483class DecltypeType : public Type {
4484 Expr *E;
4485 QualType UnderlyingType;
4486
4487protected:
4488 friend class ASTContext; // ASTContext creates these.
4489
4490 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4491
4492public:
4493 Expr *getUnderlyingExpr() const { return E; }
4494 QualType getUnderlyingType() const { return UnderlyingType; }
4495
4496 /// Remove a single level of sugar.
4497 QualType desugar() const;
4498
4499 /// Returns whether this type directly provides sugar.
4500 bool isSugared() const;
4501
4502 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4503};
4504
4505/// Internal representation of canonical, dependent
4506/// decltype(expr) types.
4507///
4508/// This class is used internally by the ASTContext to manage
4509/// canonical, dependent types, only. Clients will only see instances
4510/// of this class via DecltypeType nodes.
4511class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4512 const ASTContext &Context;
4513
4514public:
4515 DependentDecltypeType(const ASTContext &Context, Expr *E);
4516
4517 void Profile(llvm::FoldingSetNodeID &ID) {
4518 Profile(ID, Context, getUnderlyingExpr());
4519 }
4520
4521 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4522 Expr *E);
4523};
4524
4525/// A unary type transform, which is a type constructed from another.
4526class UnaryTransformType : public Type {
4527public:
4528 enum UTTKind {
4529 EnumUnderlyingType
4530 };
4531
4532private:
4533 /// The untransformed type.
4534 QualType BaseType;
4535
4536 /// The transformed type if not dependent, otherwise the same as BaseType.
4537 QualType UnderlyingType;
4538
4539 UTTKind UKind;
4540
4541protected:
4542 friend class ASTContext;
4543
4544 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4545 QualType CanonicalTy);
4546
4547public:
4548 bool isSugared() const { return !isDependentType(); }
4549 QualType desugar() const { return UnderlyingType; }
4550
4551 QualType getUnderlyingType() const { return UnderlyingType; }
4552 QualType getBaseType() const { return BaseType; }
4553
4554 UTTKind getUTTKind() const { return UKind; }
4555
4556 static bool classof(const Type *T) {
4557 return T->getTypeClass() == UnaryTransform;
4558 }
4559};
4560
4561/// Internal representation of canonical, dependent
4562/// __underlying_type(type) types.
4563///
4564/// This class is used internally by the ASTContext to manage
4565/// canonical, dependent types, only. Clients will only see instances
4566/// of this class via UnaryTransformType nodes.
4567class DependentUnaryTransformType : public UnaryTransformType,
4568 public llvm::FoldingSetNode {
4569public:
4570 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4571 UTTKind UKind);
4572
4573 void Profile(llvm::FoldingSetNodeID &ID) {
4574 Profile(ID, getBaseType(), getUTTKind());
4575 }
4576
4577 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4578 UTTKind UKind) {
4579 ID.AddPointer(BaseType.getAsOpaquePtr());
4580 ID.AddInteger((unsigned)UKind);
4581 }
4582};
4583
4584class TagType : public Type {
4585 friend class ASTReader;
4586 template <class T> friend class serialization::AbstractTypeReader;
4587
4588 /// Stores the TagDecl associated with this type. The decl may point to any
4589 /// TagDecl that declares the entity.
4590 TagDecl *decl;
4591
4592protected:
4593 TagType(TypeClass TC, const TagDecl *D, QualType can);
4594
4595public:
4596 TagDecl *getDecl() const;
4597
4598 /// Determines whether this type is in the process of being defined.
4599 bool isBeingDefined() const;
4600
4601 static bool classof(const Type *T) {
4602 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4603 }
4604};
4605
4606/// A helper class that allows the use of isa/cast/dyncast
4607/// to detect TagType objects of structs/unions/classes.
4608class RecordType : public TagType {
4609protected:
4610 friend class ASTContext; // ASTContext creates these.
4611
4612 explicit RecordType(const RecordDecl *D)
4613 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4614 explicit RecordType(TypeClass TC, RecordDecl *D)
4615 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4616
4617public:
4618 RecordDecl *getDecl() const {
4619 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4620 }
4621
4622 /// Recursively check all fields in the record for const-ness. If any field
4623 /// is declared const, return true. Otherwise, return false.
4624 bool hasConstFields() const;
4625
4626 bool isSugared() const { return false; }
4627 QualType desugar() const { return QualType(this, 0); }
4628
4629 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4630};
4631
4632/// A helper class that allows the use of isa/cast/dyncast
4633/// to detect TagType objects of enums.
4634class EnumType : public TagType {
4635 friend class ASTContext; // ASTContext creates these.
4636
4637 explicit EnumType(const EnumDecl *D)
4638 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4639
4640public:
4641 EnumDecl *getDecl() const {
4642 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4643 }
4644
4645 bool isSugared() const { return false; }
4646 QualType desugar() const { return QualType(this, 0); }
4647
4648 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4649};
4650
4651/// An attributed type is a type to which a type attribute has been applied.
4652///
4653/// The "modified type" is the fully-sugared type to which the attributed
4654/// type was applied; generally it is not canonically equivalent to the
4655/// attributed type. The "equivalent type" is the minimally-desugared type
4656/// which the type is canonically equivalent to.
4657///
4658/// For example, in the following attributed type:
4659/// int32_t __attribute__((vector_size(16)))
4660/// - the modified type is the TypedefType for int32_t
4661/// - the equivalent type is VectorType(16, int32_t)
4662/// - the canonical type is VectorType(16, int)
4663class AttributedType : public Type, public llvm::FoldingSetNode {
4664public:
4665 using Kind = attr::Kind;
4666
4667private:
4668 friend class ASTContext; // ASTContext creates these
4669
4670 QualType ModifiedType;
4671 QualType EquivalentType;
4672
4673 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4674 QualType equivalent)
4675 : Type(Attributed, canon, equivalent->getDependence()),
4676 ModifiedType(modified), EquivalentType(equivalent) {
4677 AttributedTypeBits.AttrKind = attrKind;
4678 }
4679
4680public:
4681 Kind getAttrKind() const {
4682 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4683 }
4684
4685 QualType getModifiedType() const { return ModifiedType; }
4686 QualType getEquivalentType() const { return EquivalentType; }
4687
4688 bool isSugared() const { return true; }
4689 QualType desugar() const { return getEquivalentType(); }
4690
4691 /// Does this attribute behave like a type qualifier?
4692 ///
4693 /// A type qualifier adjusts a type to provide specialized rules for
4694 /// a specific object, like the standard const and volatile qualifiers.
4695 /// This includes attributes controlling things like nullability,
4696 /// address spaces, and ARC ownership. The value of the object is still
4697 /// largely described by the modified type.
4698 ///
4699 /// In contrast, many type attributes "rewrite" their modified type to
4700 /// produce a fundamentally different type, not necessarily related in any
4701 /// formalizable way to the original type. For example, calling convention
4702 /// and vector attributes are not simple type qualifiers.
4703 ///
4704 /// Type qualifiers are often, but not always, reflected in the canonical
4705 /// type.
4706 bool isQualifier() const;
4707
4708 bool isMSTypeSpec() const;
4709
4710 bool isCallingConv() const;
4711
4712 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4713
4714 /// Retrieve the attribute kind corresponding to the given
4715 /// nullability kind.
4716 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4717 switch (kind) {
4718 case NullabilityKind::NonNull:
4719 return attr::TypeNonNull;
4720
4721 case NullabilityKind::Nullable:
4722 return attr::TypeNullable;
4723
4724 case NullabilityKind::NullableResult:
4725 return attr::TypeNullableResult;
4726
4727 case NullabilityKind::Unspecified:
4728 return attr::TypeNullUnspecified;
4729 }
4730 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4730)
;
4731 }
4732
4733 /// Strip off the top-level nullability annotation on the given
4734 /// type, if it's there.
4735 ///
4736 /// \param T The type to strip. If the type is exactly an
4737 /// AttributedType specifying nullability (without looking through
4738 /// type sugar), the nullability is returned and this type changed
4739 /// to the underlying modified type.
4740 ///
4741 /// \returns the top-level nullability, if present.
4742 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4743
4744 void Profile(llvm::FoldingSetNodeID &ID) {
4745 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4746 }
4747
4748 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4749 QualType modified, QualType equivalent) {
4750 ID.AddInteger(attrKind);
4751 ID.AddPointer(modified.getAsOpaquePtr());
4752 ID.AddPointer(equivalent.getAsOpaquePtr());
4753 }
4754
4755 static bool classof(const Type *T) {
4756 return T->getTypeClass() == Attributed;
4757 }
4758};
4759
4760class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4761 friend class ASTContext; // ASTContext creates these
4762
4763 // Helper data collector for canonical types.
4764 struct CanonicalTTPTInfo {
4765 unsigned Depth : 15;
4766 unsigned ParameterPack : 1;
4767 unsigned Index : 16;
4768 };
4769
4770 union {
4771 // Info for the canonical type.
4772 CanonicalTTPTInfo CanTTPTInfo;
4773
4774 // Info for the non-canonical type.
4775 TemplateTypeParmDecl *TTPDecl;
4776 };
4777
4778 /// Build a non-canonical type.
4779 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4780 : Type(TemplateTypeParm, Canon,
4781 TypeDependence::DependentInstantiation |
4782 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4783 TTPDecl(TTPDecl) {}
4784
4785 /// Build the canonical type.
4786 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4787 : Type(TemplateTypeParm, QualType(this, 0),
4788 TypeDependence::DependentInstantiation |
4789 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4790 CanTTPTInfo.Depth = D;
4791 CanTTPTInfo.Index = I;
4792 CanTTPTInfo.ParameterPack = PP;
4793 }
4794
4795 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4796 QualType Can = getCanonicalTypeInternal();
4797 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4798 }
4799
4800public:
4801 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4802 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4803 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4804
4805 TemplateTypeParmDecl *getDecl() const {
4806 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4807 }
4808
4809 IdentifierInfo *getIdentifier() const;
4810
4811 bool isSugared() const { return false; }
4812 QualType desugar() const { return QualType(this, 0); }
4813
4814 void Profile(llvm::FoldingSetNodeID &ID) {
4815 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4816 }
4817
4818 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4819 unsigned Index, bool ParameterPack,
4820 TemplateTypeParmDecl *TTPDecl) {
4821 ID.AddInteger(Depth);
4822 ID.AddInteger(Index);
4823 ID.AddBoolean(ParameterPack);
4824 ID.AddPointer(TTPDecl);
4825 }
4826
4827 static bool classof(const Type *T) {
4828 return T->getTypeClass() == TemplateTypeParm;
4829 }
4830};
4831
4832/// Represents the result of substituting a type for a template
4833/// type parameter.
4834///
4835/// Within an instantiated template, all template type parameters have
4836/// been replaced with these. They are used solely to record that a
4837/// type was originally written as a template type parameter;
4838/// therefore they are never canonical.
4839class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4840 friend class ASTContext;
4841
4842 // The original type parameter.
4843 const TemplateTypeParmType *Replaced;
4844
4845 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4846 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4847 Replaced(Param) {}
4848
4849public:
4850 /// Gets the template parameter that was substituted for.
4851 const TemplateTypeParmType *getReplacedParameter() const {
4852 return Replaced;
4853 }
4854
4855 /// Gets the type that was substituted for the template
4856 /// parameter.
4857 QualType getReplacementType() const {
4858 return getCanonicalTypeInternal();
4859 }
4860
4861 bool isSugared() const { return true; }
4862 QualType desugar() const { return getReplacementType(); }
4863
4864 void Profile(llvm::FoldingSetNodeID &ID) {
4865 Profile(ID, getReplacedParameter(), getReplacementType());
4866 }
4867
4868 static void Profile(llvm::FoldingSetNodeID &ID,
4869 const TemplateTypeParmType *Replaced,
4870 QualType Replacement) {
4871 ID.AddPointer(Replaced);
4872 ID.AddPointer(Replacement.getAsOpaquePtr());
4873 }
4874
4875 static bool classof(const Type *T) {
4876 return T->getTypeClass() == SubstTemplateTypeParm;
4877 }
4878};
4879
4880/// Represents the result of substituting a set of types for a template
4881/// type parameter pack.
4882///
4883/// When a pack expansion in the source code contains multiple parameter packs
4884/// and those parameter packs correspond to different levels of template
4885/// parameter lists, this type node is used to represent a template type
4886/// parameter pack from an outer level, which has already had its argument pack
4887/// substituted but that still lives within a pack expansion that itself
4888/// could not be instantiated. When actually performing a substitution into
4889/// that pack expansion (e.g., when all template parameters have corresponding
4890/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4891/// at the current pack substitution index.
4892class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4893 friend class ASTContext;
4894
4895 /// The original type parameter.
4896 const TemplateTypeParmType *Replaced;
4897
4898 /// A pointer to the set of template arguments that this
4899 /// parameter pack is instantiated with.
4900 const TemplateArgument *Arguments;
4901
4902 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4903 QualType Canon,
4904 const TemplateArgument &ArgPack);
4905
4906public:
4907 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4908
4909 /// Gets the template parameter that was substituted for.
4910 const TemplateTypeParmType *getReplacedParameter() const {
4911 return Replaced;
4912 }
4913
4914 unsigned getNumArgs() const {
4915 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4916 }
4917
4918 bool isSugared() const { return false; }
4919 QualType desugar() const { return QualType(this, 0); }
4920
4921 TemplateArgument getArgumentPack() const;
4922
4923 void Profile(llvm::FoldingSetNodeID &ID);
4924 static void Profile(llvm::FoldingSetNodeID &ID,
4925 const TemplateTypeParmType *Replaced,
4926 const TemplateArgument &ArgPack);
4927
4928 static bool classof(const Type *T) {
4929 return T->getTypeClass() == SubstTemplateTypeParmPack;
4930 }
4931};
4932
4933/// Common base class for placeholders for types that get replaced by
4934/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4935/// class template types, and constrained type names.
4936///
4937/// These types are usually a placeholder for a deduced type. However, before
4938/// the initializer is attached, or (usually) if the initializer is
4939/// type-dependent, there is no deduced type and the type is canonical. In
4940/// the latter case, it is also a dependent type.
4941class DeducedType : public Type {
4942protected:
4943 DeducedType(TypeClass TC, QualType DeducedAsType,
4944 TypeDependence ExtraDependence)
4945 : Type(TC,
4946 // FIXME: Retain the sugared deduced type?
4947 DeducedAsType.isNull() ? QualType(this, 0)
4948 : DeducedAsType.getCanonicalType(),
4949 ExtraDependence | (DeducedAsType.isNull()
4950 ? TypeDependence::None
4951 : DeducedAsType->getDependence() &
4952 ~TypeDependence::VariablyModified)) {}
4953
4954public:
4955 bool isSugared() const { return !isCanonicalUnqualified(); }
4956 QualType desugar() const { return getCanonicalTypeInternal(); }
4957
4958 /// Get the type deduced for this placeholder type, or null if it's
4959 /// either not been deduced or was deduced to a dependent type.
4960 QualType getDeducedType() const {
4961 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4962 }
4963 bool isDeduced() const {
4964 return !isCanonicalUnqualified() || isDependentType();
4965 }
4966
4967 static bool classof(const Type *T) {
4968 return T->getTypeClass() == Auto ||
4969 T->getTypeClass() == DeducedTemplateSpecialization;
4970 }
4971};
4972
4973/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4974/// by a type-constraint.
4975class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4976 friend class ASTContext; // ASTContext creates these
4977
4978 ConceptDecl *TypeConstraintConcept;
4979
4980 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4981 TypeDependence ExtraDependence, ConceptDecl *CD,
4982 ArrayRef<TemplateArgument> TypeConstraintArgs);
4983
4984 const TemplateArgument *getArgBuffer() const {
4985 return reinterpret_cast<const TemplateArgument*>(this+1);
4986 }
4987
4988 TemplateArgument *getArgBuffer() {
4989 return reinterpret_cast<TemplateArgument*>(this+1);
4990 }
4991
4992public:
4993 /// Retrieve the template arguments.
4994 const TemplateArgument *getArgs() const {
4995 return getArgBuffer();
4996 }
4997
4998 /// Retrieve the number of template arguments.
4999 unsigned getNumArgs() const {
5000 return AutoTypeBits.NumArgs;
5001 }
5002
5003 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5004
5005 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
5006 return {getArgs(), getNumArgs()};
5007 }
5008
5009 ConceptDecl *getTypeConstraintConcept() const {
5010 return TypeConstraintConcept;
5011 }
5012
5013 bool isConstrained() const {
5014 return TypeConstraintConcept != nullptr;
5015 }
5016
5017 bool isDecltypeAuto() const {
5018 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5019 }
5020
5021 AutoTypeKeyword getKeyword() const {
5022 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5023 }
5024
5025 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5026 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5027 getTypeConstraintConcept(), getTypeConstraintArguments());
5028 }
5029
5030 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5031 QualType Deduced, AutoTypeKeyword Keyword,
5032 bool IsDependent, ConceptDecl *CD,
5033 ArrayRef<TemplateArgument> Arguments);
5034
5035 static bool classof(const Type *T) {
5036 return T->getTypeClass() == Auto;
5037 }
5038};
5039
5040/// Represents a C++17 deduced template specialization type.
5041class DeducedTemplateSpecializationType : public DeducedType,
5042 public llvm::FoldingSetNode {
5043 friend class ASTContext; // ASTContext creates these
5044
5045 /// The name of the template whose arguments will be deduced.
5046 TemplateName Template;
5047
5048 DeducedTemplateSpecializationType(TemplateName Template,
5049 QualType DeducedAsType,
5050 bool IsDeducedAsDependent)
5051 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5052 toTypeDependence(Template.getDependence()) |
5053 (IsDeducedAsDependent
5054 ? TypeDependence::DependentInstantiation
5055 : TypeDependence::None)),
5056 Template(Template) {}
5057
5058public:
5059 /// Retrieve the name of the template that we are deducing.
5060 TemplateName getTemplateName() const { return Template;}
5061
5062 void Profile(llvm::FoldingSetNodeID &ID) {
5063 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5064 }
5065
5066 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5067 QualType Deduced, bool IsDependent) {
5068 Template.Profile(ID);
5069 ID.AddPointer(Deduced.getAsOpaquePtr());
5070 ID.AddBoolean(IsDependent);
5071 }
5072
5073 static bool classof(const Type *T) {
5074 return T->getTypeClass() == DeducedTemplateSpecialization;
5075 }
5076};
5077
5078/// Represents a type template specialization; the template
5079/// must be a class template, a type alias template, or a template
5080/// template parameter. A template which cannot be resolved to one of
5081/// these, e.g. because it is written with a dependent scope
5082/// specifier, is instead represented as a
5083/// @c DependentTemplateSpecializationType.
5084///
5085/// A non-dependent template specialization type is always "sugar",
5086/// typically for a \c RecordType. For example, a class template
5087/// specialization type of \c vector<int> will refer to a tag type for
5088/// the instantiation \c std::vector<int, std::allocator<int>>
5089///
5090/// Template specializations are dependent if either the template or
5091/// any of the template arguments are dependent, in which case the
5092/// type may also be canonical.
5093///
5094/// Instances of this type are allocated with a trailing array of
5095/// TemplateArguments, followed by a QualType representing the
5096/// non-canonical aliased type when the template is a type alias
5097/// template.
5098class alignas(8) TemplateSpecializationType
5099 : public Type,
5100 public llvm::FoldingSetNode {
5101 friend class ASTContext; // ASTContext creates these
5102
5103 /// The name of the template being specialized. This is
5104 /// either a TemplateName::Template (in which case it is a
5105 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5106 /// TypeAliasTemplateDecl*), a
5107 /// TemplateName::SubstTemplateTemplateParmPack, or a
5108 /// TemplateName::SubstTemplateTemplateParm (in which case the
5109 /// replacement must, recursively, be one of these).
5110 TemplateName Template;
5111
5112 TemplateSpecializationType(TemplateName T,
5113 ArrayRef<TemplateArgument> Args,
5114 QualType Canon,
5115 QualType Aliased);
5116
5117public:
5118 /// Determine whether any of the given template arguments are dependent.
5119 ///
5120 /// The converted arguments should be supplied when known; whether an
5121 /// argument is dependent can depend on the conversions performed on it
5122 /// (for example, a 'const int' passed as a template argument might be
5123 /// dependent if the parameter is a reference but non-dependent if the
5124 /// parameter is an int).
5125 ///
5126 /// Note that the \p Args parameter is unused: this is intentional, to remind
5127 /// the caller that they need to pass in the converted arguments, not the
5128 /// specified arguments.
5129 static bool
5130 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5131 ArrayRef<TemplateArgument> Converted);
5132 static bool
5133 anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5134 ArrayRef<TemplateArgument> Converted);
5135 static bool anyInstantiationDependentTemplateArguments(
5136 ArrayRef<TemplateArgumentLoc> Args);
5137
5138 /// True if this template specialization type matches a current
5139 /// instantiation in the context in which it is found.
5140 bool isCurrentInstantiation() const {
5141 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5142 }
5143
5144 /// Determine if this template specialization type is for a type alias
5145 /// template that has been substituted.
5146 ///
5147 /// Nearly every template specialization type whose template is an alias
5148 /// template will be substituted. However, this is not the case when
5149 /// the specialization contains a pack expansion but the template alias
5150 /// does not have a corresponding parameter pack, e.g.,
5151 ///
5152 /// \code
5153 /// template<typename T, typename U, typename V> struct S;
5154 /// template<typename T, typename U> using A = S<T, int, U>;
5155 /// template<typename... Ts> struct X {
5156 /// typedef A<Ts...> type; // not a type alias
5157 /// };
5158 /// \endcode
5159 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5160
5161 /// Get the aliased type, if this is a specialization of a type alias
5162 /// template.
5163 QualType getAliasedType() const {
5164 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5164, __PRETTY_FUNCTION__))
;
5165 return *reinterpret_cast<const QualType*>(end());
5166 }
5167
5168 using iterator = const TemplateArgument *;
5169
5170 iterator begin() const { return getArgs(); }
5171 iterator end() const; // defined inline in TemplateBase.h
5172
5173 /// Retrieve the name of the template that we are specializing.
5174 TemplateName getTemplateName() const { return Template; }
5175
5176 /// Retrieve the template arguments.
5177 const TemplateArgument *getArgs() const {
5178 return reinterpret_cast<const TemplateArgument *>(this + 1);
5179 }
5180
5181 /// Retrieve the number of template arguments.
5182 unsigned getNumArgs() const {
5183 return TemplateSpecializationTypeBits.NumArgs;
5184 }
5185
5186 /// Retrieve a specific template argument as a type.
5187 /// \pre \c isArgType(Arg)
5188 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5189
5190 ArrayRef<TemplateArgument> template_arguments() const {
5191 return {getArgs(), getNumArgs()};
5192 }
5193
5194 bool isSugared() const {
5195 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5196 }
5197
5198 QualType desugar() const {
5199 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5200 }
5201
5202 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5203 Profile(ID, Template, template_arguments(), Ctx);
5204 if (isTypeAlias())
5205 getAliasedType().Profile(ID);
5206 }
5207
5208 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5209 ArrayRef<TemplateArgument> Args,
5210 const ASTContext &Context);
5211
5212 static bool classof(const Type *T) {
5213 return T->getTypeClass() == TemplateSpecialization;
5214 }
5215};
5216
5217/// Print a template argument list, including the '<' and '>'
5218/// enclosing the template arguments.
5219void printTemplateArgumentList(raw_ostream &OS,
5220 ArrayRef<TemplateArgument> Args,
5221 const PrintingPolicy &Policy,
5222 const TemplateParameterList *TPL = nullptr);
5223
5224void printTemplateArgumentList(raw_ostream &OS,
5225 ArrayRef<TemplateArgumentLoc> Args,
5226 const PrintingPolicy &Policy,
5227 const TemplateParameterList *TPL = nullptr);
5228
5229void printTemplateArgumentList(raw_ostream &OS,
5230 const TemplateArgumentListInfo &Args,
5231 const PrintingPolicy &Policy,
5232 const TemplateParameterList *TPL = nullptr);
5233
5234/// The injected class name of a C++ class template or class
5235/// template partial specialization. Used to record that a type was
5236/// spelled with a bare identifier rather than as a template-id; the
5237/// equivalent for non-templated classes is just RecordType.
5238///
5239/// Injected class name types are always dependent. Template
5240/// instantiation turns these into RecordTypes.
5241///
5242/// Injected class name types are always canonical. This works
5243/// because it is impossible to compare an injected class name type
5244/// with the corresponding non-injected template type, for the same
5245/// reason that it is impossible to directly compare template
5246/// parameters from different dependent contexts: injected class name
5247/// types can only occur within the scope of a particular templated
5248/// declaration, and within that scope every template specialization
5249/// will canonicalize to the injected class name (when appropriate
5250/// according to the rules of the language).
5251class InjectedClassNameType : public Type {
5252 friend class ASTContext; // ASTContext creates these.
5253 friend class ASTNodeImporter;
5254 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5255 // currently suitable for AST reading, too much
5256 // interdependencies.
5257 template <class T> friend class serialization::AbstractTypeReader;
5258
5259 CXXRecordDecl *Decl;
5260
5261 /// The template specialization which this type represents.
5262 /// For example, in
5263 /// template <class T> class A { ... };
5264 /// this is A<T>, whereas in
5265 /// template <class X, class Y> class A<B<X,Y> > { ... };
5266 /// this is A<B<X,Y> >.
5267 ///
5268 /// It is always unqualified, always a template specialization type,
5269 /// and always dependent.
5270 QualType InjectedType;
5271
5272 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5273 : Type(InjectedClassName, QualType(),
5274 TypeDependence::DependentInstantiation),
5275 Decl(D), InjectedType(TST) {
5276 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5276, __PRETTY_FUNCTION__))
;
5277 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5277, __PRETTY_FUNCTION__))
;
5278 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5278, __PRETTY_FUNCTION__))
;
5279 }
5280
5281public:
5282 QualType getInjectedSpecializationType() const { return InjectedType; }
5283
5284 const TemplateSpecializationType *getInjectedTST() const {
5285 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5286 }
5287
5288 TemplateName getTemplateName() const {
5289 return getInjectedTST()->getTemplateName();
5290 }
5291
5292 CXXRecordDecl *getDecl() const;
5293
5294 bool isSugared() const { return false; }
5295 QualType desugar() const { return QualType(this, 0); }
5296
5297 static bool classof(const Type *T) {
5298 return T->getTypeClass() == InjectedClassName;
5299 }
5300};
5301
5302/// The kind of a tag type.
5303enum TagTypeKind {
5304 /// The "struct" keyword.
5305 TTK_Struct,
5306
5307 /// The "__interface" keyword.
5308 TTK_Interface,
5309
5310 /// The "union" keyword.
5311 TTK_Union,
5312
5313 /// The "class" keyword.
5314 TTK_Class,
5315
5316 /// The "enum" keyword.
5317 TTK_Enum
5318};
5319
5320/// The elaboration keyword that precedes a qualified type name or
5321/// introduces an elaborated-type-specifier.
5322enum ElaboratedTypeKeyword {
5323 /// The "struct" keyword introduces the elaborated-type-specifier.
5324 ETK_Struct,
5325
5326 /// The "__interface" keyword introduces the elaborated-type-specifier.
5327 ETK_Interface,
5328
5329 /// The "union" keyword introduces the elaborated-type-specifier.
5330 ETK_Union,
5331
5332 /// The "class" keyword introduces the elaborated-type-specifier.
5333 ETK_Class,
5334
5335 /// The "enum" keyword introduces the elaborated-type-specifier.
5336 ETK_Enum,
5337
5338 /// The "typename" keyword precedes the qualified type name, e.g.,
5339 /// \c typename T::type.
5340 ETK_Typename,
5341
5342 /// No keyword precedes the qualified type name.
5343 ETK_None
5344};
5345
5346/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5347/// The keyword in stored in the free bits of the base class.
5348/// Also provides a few static helpers for converting and printing
5349/// elaborated type keyword and tag type kind enumerations.
5350class TypeWithKeyword : public Type {
5351protected:
5352 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5353 QualType Canonical, TypeDependence Dependence)
5354 : Type(tc, Canonical, Dependence) {
5355 TypeWithKeywordBits.Keyword = Keyword;
5356 }
5357
5358public:
5359 ElaboratedTypeKeyword getKeyword() const {
5360 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5361 }
5362
5363 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5364 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5365
5366 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5367 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5368 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5369
5370 /// Converts a TagTypeKind into an elaborated type keyword.
5371 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5372
5373 /// Converts an elaborated type keyword into a TagTypeKind.
5374 /// It is an error to provide an elaborated type keyword
5375 /// which *isn't* a tag kind here.
5376 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5377
5378 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5379
5380 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5381
5382 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5383 return getKeywordName(getKeywordForTagTypeKind(Kind));
5384 }
5385
5386 class CannotCastToThisType {};
5387 static CannotCastToThisType classof(const Type *);
5388};
5389
5390/// Represents a type that was referred to using an elaborated type
5391/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5392/// or both.
5393///
5394/// This type is used to keep track of a type name as written in the
5395/// source code, including tag keywords and any nested-name-specifiers.
5396/// The type itself is always "sugar", used to express what was written
5397/// in the source code but containing no additional semantic information.
5398class ElaboratedType final
5399 : public TypeWithKeyword,
5400 public llvm::FoldingSetNode,
5401 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5402 friend class ASTContext; // ASTContext creates these
5403 friend TrailingObjects;
5404
5405 /// The nested name specifier containing the qualifier.
5406 NestedNameSpecifier *NNS;
5407
5408 /// The type that this qualified name refers to.
5409 QualType NamedType;
5410
5411 /// The (re)declaration of this tag type owned by this occurrence is stored
5412 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5413 /// it, or obtain a null pointer if there is none.
5414
5415 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5416 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5417 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5418 // Any semantic dependence on the qualifier will have
5419 // been incorporated into NamedType. We still need to
5420 // track syntactic (instantiation / error / pack)
5421 // dependence on the qualifier.
5422 NamedType->getDependence() |
5423 (NNS ? toSyntacticDependence(
5424 toTypeDependence(NNS->getDependence()))
5425 : TypeDependence::None)),
5426 NNS(NNS), NamedType(NamedType) {
5427 ElaboratedTypeBits.HasOwnedTagDecl = false;
5428 if (OwnedTagDecl) {
5429 ElaboratedTypeBits.HasOwnedTagDecl = true;
5430 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5431 }
5432 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5434, __PRETTY_FUNCTION__))
5433 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5434, __PRETTY_FUNCTION__))
5434 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5434, __PRETTY_FUNCTION__))
;
5435 }
5436
5437public:
5438 /// Retrieve the qualification on this type.
5439 NestedNameSpecifier *getQualifier() const { return NNS; }
5440
5441 /// Retrieve the type named by the qualified-id.
5442 QualType getNamedType() const { return NamedType; }
5443
5444 /// Remove a single level of sugar.
5445 QualType desugar() const { return getNamedType(); }
5446
5447 /// Returns whether this type directly provides sugar.
5448 bool isSugared() const { return true; }
5449
5450 /// Return the (re)declaration of this type owned by this occurrence of this
5451 /// type, or nullptr if there is none.
5452 TagDecl *getOwnedTagDecl() const {
5453 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5454 : nullptr;
5455 }
5456
5457 void Profile(llvm::FoldingSetNodeID &ID) {
5458 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5459 }
5460
5461 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5462 NestedNameSpecifier *NNS, QualType NamedType,
5463 TagDecl *OwnedTagDecl) {
5464 ID.AddInteger(Keyword);
5465 ID.AddPointer(NNS);
5466 NamedType.Profile(ID);
5467 ID.AddPointer(OwnedTagDecl);
5468 }
5469
5470 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5471};
5472
5473/// Represents a qualified type name for which the type name is
5474/// dependent.
5475///
5476/// DependentNameType represents a class of dependent types that involve a
5477/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5478/// name of a type. The DependentNameType may start with a "typename" (for a
5479/// typename-specifier), "class", "struct", "union", or "enum" (for a
5480/// dependent elaborated-type-specifier), or nothing (in contexts where we
5481/// know that we must be referring to a type, e.g., in a base class specifier).
5482/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5483/// mode, this type is used with non-dependent names to delay name lookup until
5484/// instantiation.
5485class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5486 friend class ASTContext; // ASTContext creates these
5487
5488 /// The nested name specifier containing the qualifier.
5489 NestedNameSpecifier *NNS;
5490
5491 /// The type that this typename specifier refers to.
5492 const IdentifierInfo *Name;
5493
5494 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5495 const IdentifierInfo *Name, QualType CanonType)
5496 : TypeWithKeyword(Keyword, DependentName, CanonType,
5497 TypeDependence::DependentInstantiation |
5498 toTypeDependence(NNS->getDependence())),
5499 NNS(NNS), Name(Name) {}
5500
5501public:
5502 /// Retrieve the qualification on this type.
5503 NestedNameSpecifier *getQualifier() const { return NNS; }
5504
5505 /// Retrieve the type named by the typename specifier as an identifier.
5506 ///
5507 /// This routine will return a non-NULL identifier pointer when the
5508 /// form of the original typename was terminated by an identifier,
5509 /// e.g., "typename T::type".
5510 const IdentifierInfo *getIdentifier() const {
5511 return Name;
5512 }
5513
5514 bool isSugared() const { return false; }
5515 QualType desugar() const { return QualType(this, 0); }
5516
5517 void Profile(llvm::FoldingSetNodeID &ID) {
5518 Profile(ID, getKeyword(), NNS, Name);
5519 }
5520
5521 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5522 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5523 ID.AddInteger(Keyword);
5524 ID.AddPointer(NNS);
5525 ID.AddPointer(Name);
5526 }
5527
5528 static bool classof(const Type *T) {
5529 return T->getTypeClass() == DependentName;
5530 }
5531};
5532
5533/// Represents a template specialization type whose template cannot be
5534/// resolved, e.g.
5535/// A<T>::template B<T>
5536class alignas(8) DependentTemplateSpecializationType
5537 : public TypeWithKeyword,
5538 public llvm::FoldingSetNode {
5539 friend class ASTContext; // ASTContext creates these
5540
5541 /// The nested name specifier containing the qualifier.
5542 NestedNameSpecifier *NNS;
5543
5544 /// The identifier of the template.
5545 const IdentifierInfo *Name;
5546
5547 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5548 NestedNameSpecifier *NNS,
5549 const IdentifierInfo *Name,
5550 ArrayRef<TemplateArgument> Args,
5551 QualType Canon);
5552
5553 const TemplateArgument *getArgBuffer() const {
5554 return reinterpret_cast<const TemplateArgument*>(this+1);
5555 }
5556
5557 TemplateArgument *getArgBuffer() {
5558 return reinterpret_cast<TemplateArgument*>(this+1);
5559 }
5560
5561public:
5562 NestedNameSpecifier *getQualifier() const { return NNS; }
5563 const IdentifierInfo *getIdentifier() const { return Name; }
5564
5565 /// Retrieve the template arguments.
5566 const TemplateArgument *getArgs() const {
5567 return getArgBuffer();
5568 }
5569
5570 /// Retrieve the number of template arguments.
5571 unsigned getNumArgs() const {
5572 return DependentTemplateSpecializationTypeBits.NumArgs;
5573 }
5574
5575 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5576
5577 ArrayRef<TemplateArgument> template_arguments() const {
5578 return {getArgs(), getNumArgs()};
5579 }
5580
5581 using iterator = const TemplateArgument *;
5582
5583 iterator begin() const { return getArgs(); }
5584 iterator end() const; // inline in TemplateBase.h
5585
5586 bool isSugared() const { return false; }
5587 QualType desugar() const { return QualType(this, 0); }
5588
5589 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5590 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5591 }
5592
5593 static void Profile(llvm::FoldingSetNodeID &ID,
5594 const ASTContext &Context,
5595 ElaboratedTypeKeyword Keyword,
5596 NestedNameSpecifier *Qualifier,
5597 const IdentifierInfo *Name,
5598 ArrayRef<TemplateArgument> Args);
5599
5600 static bool classof(const Type *T) {
5601 return T->getTypeClass() == DependentTemplateSpecialization;
5602 }
5603};
5604
5605/// Represents a pack expansion of types.
5606///
5607/// Pack expansions are part of C++11 variadic templates. A pack
5608/// expansion contains a pattern, which itself contains one or more
5609/// "unexpanded" parameter packs. When instantiated, a pack expansion
5610/// produces a series of types, each instantiated from the pattern of
5611/// the expansion, where the Ith instantiation of the pattern uses the
5612/// Ith arguments bound to each of the unexpanded parameter packs. The
5613/// pack expansion is considered to "expand" these unexpanded
5614/// parameter packs.
5615///
5616/// \code
5617/// template<typename ...Types> struct tuple;
5618///
5619/// template<typename ...Types>
5620/// struct tuple_of_references {
5621/// typedef tuple<Types&...> type;
5622/// };
5623/// \endcode
5624///
5625/// Here, the pack expansion \c Types&... is represented via a
5626/// PackExpansionType whose pattern is Types&.
5627class PackExpansionType : public Type, public llvm::FoldingSetNode {
5628 friend class ASTContext; // ASTContext creates these
5629
5630 /// The pattern of the pack expansion.
5631 QualType Pattern;
5632
5633 PackExpansionType(QualType Pattern, QualType Canon,
5634 Optional<unsigned> NumExpansions)
5635 : Type(PackExpansion, Canon,
5636 (Pattern->getDependence() | TypeDependence::Dependent |
5637 TypeDependence::Instantiation) &
5638 ~TypeDependence::UnexpandedPack),
5639 Pattern(Pattern) {
5640 PackExpansionTypeBits.NumExpansions =
5641 NumExpansions ? *NumExpansions + 1 : 0;
5642 }
5643
5644public:
5645 /// Retrieve the pattern of this pack expansion, which is the
5646 /// type that will be repeatedly instantiated when instantiating the
5647 /// pack expansion itself.
5648 QualType getPattern() const { return Pattern; }
5649
5650 /// Retrieve the number of expansions that this pack expansion will
5651 /// generate, if known.
5652 Optional<unsigned> getNumExpansions() const {
5653 if (PackExpansionTypeBits.NumExpansions)
5654 return PackExpansionTypeBits.NumExpansions - 1;
5655 return None;
5656 }
5657
5658 bool isSugared() const { return false; }
5659 QualType desugar() const { return QualType(this, 0); }
5660
5661 void Profile(llvm::FoldingSetNodeID &ID) {
5662 Profile(ID, getPattern(), getNumExpansions());
5663 }
5664
5665 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5666 Optional<unsigned> NumExpansions) {
5667 ID.AddPointer(Pattern.getAsOpaquePtr());
5668 ID.AddBoolean(NumExpansions.hasValue());
5669 if (NumExpansions)
5670 ID.AddInteger(*NumExpansions);
5671 }
5672
5673 static bool classof(const Type *T) {
5674 return T->getTypeClass() == PackExpansion;
5675 }
5676};
5677
5678/// This class wraps the list of protocol qualifiers. For types that can
5679/// take ObjC protocol qualifers, they can subclass this class.
5680template <class T>
5681class ObjCProtocolQualifiers {
5682protected:
5683 ObjCProtocolQualifiers() = default;
5684
5685 ObjCProtocolDecl * const *getProtocolStorage() const {
5686 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5687 }
5688
5689 ObjCProtocolDecl **getProtocolStorage() {
5690 return static_cast<T*>(this)->getProtocolStorageImpl();
5691 }
5692
5693 void setNumProtocols(unsigned N) {
5694 static_cast<T*>(this)->setNumProtocolsImpl(N);
5695 }
5696
5697 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5698 setNumProtocols(protocols.size());
5699 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5700, __PRETTY_FUNCTION__))
5700 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5700, __PRETTY_FUNCTION__))
;
5701 if (!protocols.empty())
5702 memcpy(getProtocolStorage(), protocols.data(),
5703 protocols.size() * sizeof(ObjCProtocolDecl*));
5704 }
5705
5706public:
5707 using qual_iterator = ObjCProtocolDecl * const *;
5708 using qual_range = llvm::iterator_range<qual_iterator>;
5709
5710 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5711 qual_iterator qual_begin() const { return getProtocolStorage(); }
5712 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5713
5714 bool qual_empty() const { return getNumProtocols() == 0; }
5715
5716 /// Return the number of qualifying protocols in this type, or 0 if
5717 /// there are none.
5718 unsigned getNumProtocols() const {
5719 return static_cast<const T*>(this)->getNumProtocolsImpl();
5720 }
5721
5722 /// Fetch a protocol by index.
5723 ObjCProtocolDecl *getProtocol(unsigned I) const {
5724 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5724, __PRETTY_FUNCTION__))
;
5725 return qual_begin()[I];
5726 }
5727
5728 /// Retrieve all of the protocol qualifiers.
5729 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5730 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5731 }
5732};
5733
5734/// Represents a type parameter type in Objective C. It can take
5735/// a list of protocols.
5736class ObjCTypeParamType : public Type,
5737 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5738 public llvm::FoldingSetNode {
5739 friend class ASTContext;
5740 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5741
5742 /// The number of protocols stored on this type.
5743 unsigned NumProtocols : 6;
5744
5745 ObjCTypeParamDecl *OTPDecl;
5746
5747 /// The protocols are stored after the ObjCTypeParamType node. In the
5748 /// canonical type, the list of protocols are sorted alphabetically
5749 /// and uniqued.
5750 ObjCProtocolDecl **getProtocolStorageImpl();
5751
5752 /// Return the number of qualifying protocols in this interface type,
5753 /// or 0 if there are none.
5754 unsigned getNumProtocolsImpl() const {
5755 return NumProtocols;
5756 }
5757
5758 void setNumProtocolsImpl(unsigned N) {
5759 NumProtocols = N;
5760 }
5761
5762 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5763 QualType can,
5764 ArrayRef<ObjCProtocolDecl *> protocols);
5765
5766public:
5767 bool isSugared() const { return true; }
5768 QualType desugar() const { return getCanonicalTypeInternal(); }
5769
5770 static bool classof(const Type *T) {
5771 return T->getTypeClass() == ObjCTypeParam;
5772 }
5773
5774 void Profile(llvm::FoldingSetNodeID &ID);
5775 static void Profile(llvm::FoldingSetNodeID &ID,
5776 const ObjCTypeParamDecl *OTPDecl,
5777 QualType CanonicalType,
5778 ArrayRef<ObjCProtocolDecl *> protocols);
5779
5780 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5781};
5782
5783/// Represents a class type in Objective C.
5784///
5785/// Every Objective C type is a combination of a base type, a set of
5786/// type arguments (optional, for parameterized classes) and a list of
5787/// protocols.
5788///
5789/// Given the following declarations:
5790/// \code
5791/// \@class C<T>;
5792/// \@protocol P;
5793/// \endcode
5794///
5795/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5796/// with base C and no protocols.
5797///
5798/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5799/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5800/// protocol list.
5801/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5802/// and protocol list [P].
5803///
5804/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5805/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5806/// and no protocols.
5807///
5808/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5809/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5810/// this should get its own sugar class to better represent the source.
5811class ObjCObjectType : public Type,
5812 public ObjCProtocolQualifiers<ObjCObjectType> {
5813 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5814
5815 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5816 // after the ObjCObjectPointerType node.
5817 // ObjCObjectType.NumProtocols - the number of protocols stored
5818 // after the type arguments of ObjCObjectPointerType node.
5819 //
5820 // These protocols are those written directly on the type. If
5821 // protocol qualifiers ever become additive, the iterators will need
5822 // to get kindof complicated.
5823 //
5824 // In the canonical object type, these are sorted alphabetically
5825 // and uniqued.
5826
5827 /// Either a BuiltinType or an InterfaceType or sugar for either.
5828 QualType BaseType;
5829
5830 /// Cached superclass type.
5831 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5832 CachedSuperClassType;
5833
5834 QualType *getTypeArgStorage();
5835 const QualType *getTypeArgStorage() const {
5836 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5837 }
5838
5839 ObjCProtocolDecl **getProtocolStorageImpl();
5840 /// Return the number of qualifying protocols in this interface type,
5841 /// or 0 if there are none.
5842 unsigned getNumProtocolsImpl() const {
5843 return ObjCObjectTypeBits.NumProtocols;
5844 }
5845 void setNumProtocolsImpl(unsigned N) {
5846 ObjCObjectTypeBits.NumProtocols = N;
5847 }
5848
5849protected:
5850 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5851
5852 ObjCObjectType(QualType Canonical, QualType Base,
5853 ArrayRef<QualType> typeArgs,
5854 ArrayRef<ObjCProtocolDecl *> protocols,
5855 bool isKindOf);
5856
5857 ObjCObjectType(enum Nonce_ObjCInterface)
5858 : Type(ObjCInterface, QualType(), TypeDependence::None),
5859 BaseType(QualType(this_(), 0)) {
5860 ObjCObjectTypeBits.NumProtocols = 0;
5861 ObjCObjectTypeBits.NumTypeArgs = 0;
5862 ObjCObjectTypeBits.IsKindOf = 0;
5863 }
5864
5865 void computeSuperClassTypeSlow() const;
5866
5867public:
5868 /// Gets the base type of this object type. This is always (possibly
5869 /// sugar for) one of:
5870 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5871 /// user, which is a typedef for an ObjCObjectPointerType)
5872 /// - the 'Class' builtin type (same caveat)
5873 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5874 QualType getBaseType() const { return BaseType; }
5875
5876 bool isObjCId() const {
5877 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5878 }
5879
5880 bool isObjCClass() const {
5881 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5882 }
5883
5884 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5885 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5886 bool isObjCUnqualifiedIdOrClass() const {
5887 if (!qual_empty()) return false;
5888 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5889 return T->getKind() == BuiltinType::ObjCId ||
5890 T->getKind() == BuiltinType::ObjCClass;
5891 return false;
5892 }
5893 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5894 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5895
5896 /// Gets the interface declaration for this object type, if the base type
5897 /// really is an interface.
5898 ObjCInterfaceDecl *getInterface() const;
5899
5900 /// Determine whether this object type is "specialized", meaning
5901 /// that it has type arguments.
5902 bool isSpecialized() const;
5903
5904 /// Determine whether this object type was written with type arguments.
5905 bool isSpecializedAsWritten() const {
5906 return ObjCObjectTypeBits.NumTypeArgs > 0;
5907 }
5908
5909 /// Determine whether this object type is "unspecialized", meaning
5910 /// that it has no type arguments.
5911 bool isUnspecialized() const { return !isSpecialized(); }
5912
5913 /// Determine whether this object type is "unspecialized" as
5914 /// written, meaning that it has no type arguments.
5915 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5916
5917 /// Retrieve the type arguments of this object type (semantically).
5918 ArrayRef<QualType> getTypeArgs() const;
5919
5920 /// Retrieve the type arguments of this object type as they were
5921 /// written.
5922 ArrayRef<QualType> getTypeArgsAsWritten() const {
5923 return llvm::makeArrayRef(getTypeArgStorage(),
5924 ObjCObjectTypeBits.NumTypeArgs);
5925 }
5926
5927 /// Whether this is a "__kindof" type as written.
5928 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5929
5930 /// Whether this ia a "__kindof" type (semantically).
5931 bool isKindOfType() const;
5932
5933 /// Retrieve the type of the superclass of this object type.
5934 ///
5935 /// This operation substitutes any type arguments into the
5936 /// superclass of the current class type, potentially producing a
5937 /// specialization of the superclass type. Produces a null type if
5938 /// there is no superclass.
5939 QualType getSuperClassType() const {
5940 if (!CachedSuperClassType.getInt())
5941 computeSuperClassTypeSlow();
5942
5943 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5943, __PRETTY_FUNCTION__))
;
5944 return QualType(CachedSuperClassType.getPointer(), 0);
5945 }
5946
5947 /// Strip off the Objective-C "kindof" type and (with it) any
5948 /// protocol qualifiers.
5949 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5950
5951 bool isSugared() const { return false; }
5952 QualType desugar() const { return QualType(this, 0); }
5953
5954 static bool classof(const Type *T) {
5955 return T->getTypeClass() == ObjCObject ||
5956 T->getTypeClass() == ObjCInterface;
5957 }
5958};
5959
5960/// A class providing a concrete implementation
5961/// of ObjCObjectType, so as to not increase the footprint of
5962/// ObjCInterfaceType. Code outside of ASTContext and the core type
5963/// system should not reference this type.
5964class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5965 friend class ASTContext;
5966
5967 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5968 // will need to be modified.
5969
5970 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5971 ArrayRef<QualType> typeArgs,
5972 ArrayRef<ObjCProtocolDecl *> protocols,
5973 bool isKindOf)
5974 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5975
5976public:
5977 void Profile(llvm::FoldingSetNodeID &ID);
5978 static void Profile(llvm::FoldingSetNodeID &ID,
5979 QualType Base,
5980 ArrayRef<QualType> typeArgs,
5981 ArrayRef<ObjCProtocolDecl *> protocols,
5982 bool isKindOf);
5983};
5984
5985inline QualType *ObjCObjectType::getTypeArgStorage() {
5986 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5987}
5988
5989inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5990 return reinterpret_cast<ObjCProtocolDecl**>(
5991 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5992}
5993
5994inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5995 return reinterpret_cast<ObjCProtocolDecl**>(
5996 static_cast<ObjCTypeParamType*>(this)+1);
5997}
5998
5999/// Interfaces are the core concept in Objective-C for object oriented design.
6000/// They basically correspond to C++ classes. There are two kinds of interface
6001/// types: normal interfaces like `NSString`, and qualified interfaces, which
6002/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
6003///
6004/// ObjCInterfaceType guarantees the following properties when considered
6005/// as a subtype of its superclass, ObjCObjectType:
6006/// - There are no protocol qualifiers. To reinforce this, code which
6007/// tries to invoke the protocol methods via an ObjCInterfaceType will
6008/// fail to compile.
6009/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
6010/// T->getBaseType() == QualType(T, 0).
6011class ObjCInterfaceType : public ObjCObjectType {
6012 friend class ASTContext; // ASTContext creates these.
6013 friend class ASTReader;
6014 friend class ObjCInterfaceDecl;
6015 template <class T> friend class serialization::AbstractTypeReader;
6016
6017 mutable ObjCInterfaceDecl *Decl;
6018
6019 ObjCInterfaceType(const ObjCInterfaceDecl *D)
6020 : ObjCObjectType(Nonce_ObjCInterface),
6021 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
6022
6023public:
6024 /// Get the declaration of this interface.
6025 ObjCInterfaceDecl *getDecl() const { return Decl; }
6026
6027 bool isSugared() const { return false; }
6028 QualType desugar() const { return QualType(this, 0); }
6029
6030 static bool classof(const Type *T) {
6031 return T->getTypeClass() == ObjCInterface;
6032 }
6033
6034 // Nonsense to "hide" certain members of ObjCObjectType within this
6035 // class. People asking for protocols on an ObjCInterfaceType are
6036 // not going to get what they want: ObjCInterfaceTypes are
6037 // guaranteed to have no protocols.
6038 enum {
6039 qual_iterator,
6040 qual_begin,
6041 qual_end,
6042 getNumProtocols,
6043 getProtocol
6044 };
6045};
6046
6047inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6048 QualType baseType = getBaseType();
6049 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6050 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6051 return T->getDecl();
6052
6053 baseType = ObjT->getBaseType();
6054 }
6055
6056 return nullptr;
6057}
6058
6059/// Represents a pointer to an Objective C object.
6060///
6061/// These are constructed from pointer declarators when the pointee type is
6062/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6063/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6064/// and 'Class<P>' are translated into these.
6065///
6066/// Pointers to pointers to Objective C objects are still PointerTypes;
6067/// only the first level of pointer gets it own type implementation.
6068class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6069 friend class ASTContext; // ASTContext creates these.
6070
6071 QualType PointeeType;
6072
6073 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6074 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6075 PointeeType(Pointee) {}
6076
6077public:
6078 /// Gets the type pointed to by this ObjC pointer.
6079 /// The result will always be an ObjCObjectType or sugar thereof.
6080 QualType getPointeeType() const { return PointeeType; }
6081
6082 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6083 ///
6084 /// This method is equivalent to getPointeeType() except that
6085 /// it discards any typedefs (or other sugar) between this
6086 /// type and the "outermost" object type. So for:
6087 /// \code
6088 /// \@class A; \@protocol P; \@protocol Q;
6089 /// typedef A<P> AP;
6090 /// typedef A A1;
6091 /// typedef A1<P> A1P;
6092 /// typedef A1P<Q> A1PQ;
6093 /// \endcode
6094 /// For 'A*', getObjectType() will return 'A'.
6095 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6096 /// For 'AP*', getObjectType() will return 'A<P>'.
6097 /// For 'A1*', getObjectType() will return 'A'.
6098 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6099 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6100 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6101 /// adding protocols to a protocol-qualified base discards the
6102 /// old qualifiers (for now). But if it didn't, getObjectType()
6103 /// would return 'A1P<Q>' (and we'd have to make iterating over
6104 /// qualifiers more complicated).
6105 const ObjCObjectType *getObjectType() const {
6106 return PointeeType->castAs<ObjCObjectType>();
6107 }
6108
6109 /// If this pointer points to an Objective C
6110 /// \@interface type, gets the type for that interface. Any protocol
6111 /// qualifiers on the interface are ignored.
6112 ///
6113 /// \return null if the base type for this pointer is 'id' or 'Class'
6114 const ObjCInterfaceType *getInterfaceType() const;
6115
6116 /// If this pointer points to an Objective \@interface
6117 /// type, gets the declaration for that interface.
6118 ///
6119 /// \return null if the base type for this pointer is 'id' or 'Class'
6120 ObjCInterfaceDecl *getInterfaceDecl() const {
6121 return getObjectType()->getInterface();
6122 }
6123
6124 /// True if this is equivalent to the 'id' type, i.e. if
6125 /// its object type is the primitive 'id' type with no protocols.
6126 bool isObjCIdType() const {
6127 return getObjectType()->isObjCUnqualifiedId();
6128 }
6129
6130 /// True if this is equivalent to the 'Class' type,
6131 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6132 bool isObjCClassType() const {
6133 return getObjectType()->isObjCUnqualifiedClass();
6134 }
6135
6136 /// True if this is equivalent to the 'id' or 'Class' type,
6137 bool isObjCIdOrClassType() const {
6138 return getObjectType()->isObjCUnqualifiedIdOrClass();
6139 }
6140
6141 /// True if this is equivalent to 'id<P>' for some non-empty set of
6142 /// protocols.
6143 bool isObjCQualifiedIdType() const {
6144 return getObjectType()->isObjCQualifiedId();
6145 }
6146
6147 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6148 /// protocols.
6149 bool isObjCQualifiedClassType() const {
6150 return getObjectType()->isObjCQualifiedClass();
6151 }
6152
6153 /// Whether this is a "__kindof" type.
6154 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6155
6156 /// Whether this type is specialized, meaning that it has type arguments.
6157 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6158
6159 /// Whether this type is specialized, meaning that it has type arguments.
6160 bool isSpecializedAsWritten() const {
6161 return getObjectType()->isSpecializedAsWritten();
6162 }
6163
6164 /// Whether this type is unspecialized, meaning that is has no type arguments.
6165 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6166
6167 /// Determine whether this object type is "unspecialized" as
6168 /// written, meaning that it has no type arguments.
6169 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6170
6171 /// Retrieve the type arguments for this type.
6172 ArrayRef<QualType> getTypeArgs() const {
6173 return getObjectType()->getTypeArgs();
6174 }
6175
6176 /// Retrieve the type arguments for this type.
6177 ArrayRef<QualType> getTypeArgsAsWritten() const {
6178 return getObjectType()->getTypeArgsAsWritten();
6179 }
6180
6181 /// An iterator over the qualifiers on the object type. Provided
6182 /// for convenience. This will always iterate over the full set of
6183 /// protocols on a type, not just those provided directly.
6184 using qual_iterator = ObjCObjectType::qual_iterator;
6185 using qual_range = llvm::iterator_range<qual_iterator>;
6186
6187 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6188
6189 qual_iterator qual_begin() const {
6190 return getObjectType()->qual_begin();
6191 }
6192
6193 qual_iterator qual_end() const {
6194 return getObjectType()->qual_end();
6195 }
6196
6197 bool qual_empty() const { return getObjectType()->qual_empty(); }
6198
6199 /// Return the number of qualifying protocols on the object type.
6200 unsigned getNumProtocols() const {
6201 return getObjectType()->getNumProtocols();
6202 }
6203
6204 /// Retrieve a qualifying protocol by index on the object type.
6205 ObjCProtocolDecl *getProtocol(unsigned I) const {
6206 return getObjectType()->getProtocol(I);
6207 }
6208
6209 bool isSugared() const { return false; }
6210 QualType desugar() const { return QualType(this, 0); }
6211
6212 /// Retrieve the type of the superclass of this object pointer type.
6213 ///
6214 /// This operation substitutes any type arguments into the
6215 /// superclass of the current class type, potentially producing a
6216 /// pointer to a specialization of the superclass type. Produces a
6217 /// null type if there is no superclass.
6218 QualType getSuperClassType() const;
6219
6220 /// Strip off the Objective-C "kindof" type and (with it) any
6221 /// protocol qualifiers.
6222 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6223 const ASTContext &ctx) const;
6224
6225 void Profile(llvm::FoldingSetNodeID &ID) {
6226 Profile(ID, getPointeeType());
6227 }
6228
6229 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6230 ID.AddPointer(T.getAsOpaquePtr());
6231 }
6232
6233 static bool classof(const Type *T) {
6234 return T->getTypeClass() == ObjCObjectPointer;
6235 }
6236};
6237
6238class AtomicType : public Type, public llvm::FoldingSetNode {
6239 friend class ASTContext; // ASTContext creates these.
6240
6241 QualType ValueType;
6242
6243 AtomicType(QualType ValTy, QualType Canonical)
6244 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6245
6246public:
6247 /// Gets the type contained by this atomic type, i.e.
6248 /// the type returned by performing an atomic load of this atomic type.
6249 QualType getValueType() const { return ValueType; }
6250
6251 bool isSugared() const { return false; }
6252 QualType desugar() const { return QualType(this, 0); }
6253
6254 void Profile(llvm::FoldingSetNodeID &ID) {
6255 Profile(ID, getValueType());
6256 }
6257
6258 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6259 ID.AddPointer(T.getAsOpaquePtr());
6260 }
6261
6262 static bool classof(const Type *T) {
6263 return T->getTypeClass() == Atomic;
6264 }
6265};
6266
6267/// PipeType - OpenCL20.
6268class PipeType : public Type, public llvm::FoldingSetNode {
6269 friend class ASTContext; // ASTContext creates these.
6270
6271 QualType ElementType;
6272 bool isRead;
6273
6274 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6275 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6276 ElementType(elemType), isRead(isRead) {}
6277
6278public:
6279 QualType getElementType() const { return ElementType; }
6280
6281 bool isSugared() const { return false; }
6282
6283 QualType desugar() const { return QualType(this, 0); }
6284
6285 void Profile(llvm::FoldingSetNodeID &ID) {
6286 Profile(ID, getElementType(), isReadOnly());
6287 }
6288
6289 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6290 ID.AddPointer(T.getAsOpaquePtr());
6291 ID.AddBoolean(isRead);
6292 }
6293
6294 static bool classof(const Type *T) {
6295 return T->getTypeClass() == Pipe;
6296 }
6297
6298 bool isReadOnly() const { return isRead; }
6299};
6300
6301/// A fixed int type of a specified bitwidth.
6302class ExtIntType final : public Type, public llvm::FoldingSetNode {
6303 friend class ASTContext;
6304 unsigned IsUnsigned : 1;
6305 unsigned NumBits : 24;
6306
6307protected:
6308 ExtIntType(bool isUnsigned, unsigned NumBits);
6309
6310public:
6311 bool isUnsigned() const { return IsUnsigned; }
6312 bool isSigned() const { return !IsUnsigned; }
6313 unsigned getNumBits() const { return NumBits; }
6314
6315 bool isSugared() const { return false; }
6316 QualType desugar() const { return QualType(this, 0); }
6317
6318 void Profile(llvm::FoldingSetNodeID &ID) {
6319 Profile(ID, isUnsigned(), getNumBits());
6320 }
6321
6322 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6323 unsigned NumBits) {
6324 ID.AddBoolean(IsUnsigned);
6325 ID.AddInteger(NumBits);
6326 }
6327
6328 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; }
6329};
6330
6331class DependentExtIntType final : public Type, public llvm::FoldingSetNode {
6332 friend class ASTContext;
6333 const ASTContext &Context;
6334 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6335
6336protected:
6337 DependentExtIntType(const ASTContext &Context, bool IsUnsigned,
6338 Expr *NumBits);
6339
6340public:
6341 bool isUnsigned() const;
6342 bool isSigned() const { return !isUnsigned(); }
6343 Expr *getNumBitsExpr() const;
6344
6345 bool isSugared() const { return false; }
6346 QualType desugar() const { return QualType(this, 0); }
6347
6348 void Profile(llvm::FoldingSetNodeID &ID) {
6349 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6350 }
6351 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6352 bool IsUnsigned, Expr *NumBitsExpr);
6353
6354 static bool classof(const Type *T) {
6355 return T->getTypeClass() == DependentExtInt;
6356 }
6357};
6358
6359/// A qualifier set is used to build a set of qualifiers.
6360class QualifierCollector : public Qualifiers {
6361public:
6362 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6363
6364 /// Collect any qualifiers on the given type and return an
6365 /// unqualified type. The qualifiers are assumed to be consistent
6366 /// with those already in the type.
6367 const Type *strip(QualType type) {
6368 addFastQualifiers(type.getLocalFastQualifiers());
6369 if (!type.hasLocalNonFastQualifiers())
6370 return type.getTypePtrUnsafe();
6371
6372 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6373 addConsistentQualifiers(extQuals->getQualifiers());
6374 return extQuals->getBaseType();
6375 }
6376
6377 /// Apply the collected qualifiers to the given type.
6378 QualType apply(const ASTContext &Context, QualType QT) const;
6379
6380 /// Apply the collected qualifiers to the given type.
6381 QualType apply(const ASTContext &Context, const Type* T) const;
6382};
6383
6384/// A container of type source information.
6385///
6386/// A client can read the relevant info using TypeLoc wrappers, e.g:
6387/// @code
6388/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6389/// TL.getBeginLoc().print(OS, SrcMgr);
6390/// @endcode
6391class alignas(8) TypeSourceInfo {
6392 // Contains a memory block after the class, used for type source information,
6393 // allocated by ASTContext.
6394 friend class ASTContext;
6395
6396 QualType Ty;
6397
6398 TypeSourceInfo(QualType ty) : Ty(ty) {}
6399
6400public:
6401 /// Return the type wrapped by this type source info.
6402 QualType getType() const { return Ty; }
6403
6404 /// Return the TypeLoc wrapper for the type source info.
6405 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6406
6407 /// Override the type stored in this TypeSourceInfo. Use with caution!
6408 void overrideType(QualType T) { Ty = T; }
6409};
6410
6411// Inline function definitions.
6412
6413inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6414 SplitQualType desugar =
6415 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6416 desugar.Quals.addConsistentQualifiers(Quals);
6417 return desugar;
6418}
6419
6420inline const Type *QualType::getTypePtr() const {
6421 return getCommonPtr()->BaseType;
6422}
6423
6424inline const Type *QualType::getTypePtrOrNull() const {
6425 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6426}
6427
6428inline SplitQualType QualType::split() const {
6429 if (!hasLocalNonFastQualifiers())
6430 return SplitQualType(getTypePtrUnsafe(),
6431 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6432
6433 const ExtQuals *eq = getExtQualsUnsafe();
6434 Qualifiers qs = eq->getQualifiers();
6435 qs.addFastQualifiers(getLocalFastQualifiers());
6436 return SplitQualType(eq->getBaseType(), qs);
6437}
6438
6439inline Qualifiers QualType::getLocalQualifiers() const {
6440 Qualifiers Quals;
6441 if (hasLocalNonFastQualifiers())
6442 Quals = getExtQualsUnsafe()->getQualifiers();
6443 Quals.addFastQualifiers(getLocalFastQualifiers());
6444 return Quals;
6445}
6446
6447inline Qualifiers QualType::getQualifiers() const {
6448 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6449 quals.addFastQualifiers(getLocalFastQualifiers());
6450 return quals;
6451}
6452
6453inline unsigned QualType::getCVRQualifiers() const {
6454 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6455 cvr |= getLocalCVRQualifiers();
6456 return cvr;
6457}
6458
6459inline QualType QualType::getCanonicalType() const {
6460 QualType canon = getCommonPtr()->CanonicalType;
6461 return canon.withFastQualifiers(getLocalFastQualifiers());
6462}
6463
6464inline bool QualType::isCanonical() const {
6465 return getTypePtr()->isCanonicalUnqualified();
6466}
6467
6468inline bool QualType::isCanonicalAsParam() const {
6469 if (!isCanonical()) return false;
6470 if (hasLocalQualifiers()) return false;
6471
6472 const Type *T = getTypePtr();
6473 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6474 return false;
6475
6476 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6477}
6478
6479inline bool QualType::isConstQualified() const {
6480 return isLocalConstQualified() ||
6481 getCommonPtr()->CanonicalType.isLocalConstQualified();
6482}
6483
6484inline bool QualType::isRestrictQualified() const {
6485 return isLocalRestrictQualified() ||
6486 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6487}
6488
6489
6490inline bool QualType::isVolatileQualified() const {
6491 return isLocalVolatileQualified() ||
6492 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6493}
6494
6495inline bool QualType::hasQualifiers() const {
6496 return hasLocalQualifiers() ||
6497 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6498}
6499
6500inline QualType QualType::getUnqualifiedType() const {
6501 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6502 return QualType(getTypePtr(), 0);
6503
6504 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6505}
6506
6507inline SplitQualType QualType::getSplitUnqualifiedType() const {
6508 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6509 return split();
6510
6511 return getSplitUnqualifiedTypeImpl(*this);
6512}
6513
6514inline void QualType::removeLocalConst() {
6515 removeLocalFastQualifiers(Qualifiers::Const);
6516}
6517
6518inline void QualType::removeLocalRestrict() {
6519 removeLocalFastQualifiers(Qualifiers::Restrict);
6520}
6521
6522inline void QualType::removeLocalVolatile() {
6523 removeLocalFastQualifiers(Qualifiers::Volatile);
6524}
6525
6526inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6527 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 6527, __PRETTY_FUNCTION__))
;
6528 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6529 "Fast bits differ from CVR bits!");
6530
6531 // Fast path: we don't need to touch the slow qualifiers.
6532 removeLocalFastQualifiers(Mask);
6533}
6534
6535/// Check if this type has any address space qualifier.
6536inline bool QualType::hasAddressSpace() const {
6537 return getQualifiers().hasAddressSpace();
6538}
6539
6540/// Return the address space of this type.
6541inline LangAS QualType::getAddressSpace() const {
6542 return getQualifiers().getAddressSpace();
6543}
6544
6545/// Return the gc attribute of this type.
6546inline Qualifiers::GC QualType::getObjCGCAttr() const {
6547 return getQualifiers().getObjCGCAttr();
6548}
6549
6550inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6551 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6552 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6553 return false;
6554}
6555
6556inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6557 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6558 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6559 return false;
6560}
6561
6562inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6563 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6564 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6565 return false;
6566}
6567
6568inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6569 if (const auto *PT = t.getAs<PointerType>()) {
6570 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6571 return FT->getExtInfo();
6572 } else if (const auto *FT = t.getAs<FunctionType>())
6573 return FT->getExtInfo();
6574
6575 return FunctionType::ExtInfo();
6576}
6577
6578inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6579 return getFunctionExtInfo(*t);
6580}
6581
6582/// Determine whether this type is more
6583/// qualified than the Other type. For example, "const volatile int"
6584/// is more qualified than "const int", "volatile int", and
6585/// "int". However, it is not more qualified than "const volatile
6586/// int".
6587inline bool QualType::isMoreQualifiedThan(QualType other) const {
6588 Qualifiers MyQuals = getQualifiers();
6589 Qualifiers OtherQuals = other.getQualifiers();
6590 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6591}
6592
6593/// Determine whether this type is at last
6594/// as qualified as the Other type. For example, "const volatile
6595/// int" is at least as qualified as "const int", "volatile int",
6596/// "int", and "const volatile int".
6597inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6598 Qualifiers OtherQuals = other.getQualifiers();
6599
6600 // Ignore __unaligned qualifier if this type is a void.
6601 if (getUnqualifiedType()->isVoidType())
6602 OtherQuals.removeUnaligned();
6603
6604 return getQualifiers().compatiblyIncludes(OtherQuals);
6605}
6606
6607/// If Type is a reference type (e.g., const
6608/// int&), returns the type that the reference refers to ("const
6609/// int"). Otherwise, returns the type itself. This routine is used
6610/// throughout Sema to implement C++ 5p6:
6611///
6612/// If an expression initially has the type "reference to T" (8.3.2,
6613/// 8.5.3), the type is adjusted to "T" prior to any further
6614/// analysis, the expression designates the object or function
6615/// denoted by the reference, and the expression is an lvalue.
6616inline QualType QualType::getNonReferenceType() const {
6617 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6618 return RefType->getPointeeType();
6619 else
6620 return *this;
6621}
6622
6623inline bool QualType::isCForbiddenLValueType() const {
6624 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6625 getTypePtr()->isFunctionType());
6626}
6627
6628/// Tests whether the type is categorized as a fundamental type.
6629///
6630/// \returns True for types specified in C++0x [basic.fundamental].
6631inline bool Type::isFundamentalType() const {
6632 return isVoidType() ||
6633 isNullPtrType() ||
6634 // FIXME: It's really annoying that we don't have an
6635 // 'isArithmeticType()' which agrees with the standard definition.
6636 (isArithmeticType() && !isEnumeralType());
6637}
6638
6639/// Tests whether the type is categorized as a compound type.
6640///
6641/// \returns True for types specified in C++0x [basic.compound].
6642inline bool Type::isCompoundType() const {
6643 // C++0x [basic.compound]p1:
6644 // Compound types can be constructed in the following ways:
6645 // -- arrays of objects of a given type [...];
6646 return isArrayType() ||
6647 // -- functions, which have parameters of given types [...];
6648 isFunctionType() ||
6649 // -- pointers to void or objects or functions [...];
6650 isPointerType() ||
6651 // -- references to objects or functions of a given type. [...]
6652 isReferenceType() ||
6653 // -- classes containing a sequence of objects of various types, [...];
6654 isRecordType() ||
6655 // -- unions, which are classes capable of containing objects of different
6656 // types at different times;
6657 isUnionType() ||
6658 // -- enumerations, which comprise a set of named constant values. [...];
6659 isEnumeralType() ||
6660 // -- pointers to non-static class members, [...].
6661 isMemberPointerType();
6662}
6663
6664inline bool Type::isFunctionType() const {
6665 return isa<FunctionType>(CanonicalType);
6666}
6667
6668inline bool Type::isPointerType() const {
6669 return isa<PointerType>(CanonicalType);
6670}
6671
6672inline bool Type::isAnyPointerType() const {
6673 return isPointerType() || isObjCObjectPointerType();
6674}
6675
6676inline bool Type::isBlockPointerType() const {
6677 return isa<BlockPointerType>(CanonicalType);
6678}
6679
6680inline bool Type::isReferenceType() const {
6681 return isa<ReferenceType>(CanonicalType);
6682}
6683
6684inline bool Type::isLValueReferenceType() const {
6685 return isa<LValueReferenceType>(CanonicalType);
6686}
6687
6688inline bool Type::isRValueReferenceType() const {
6689 return isa<RValueReferenceType>(CanonicalType);
6690}
6691
6692inline bool Type::isObjectPointerType() const {
6693 // Note: an "object pointer type" is not the same thing as a pointer to an
6694 // object type; rather, it is a pointer to an object type or a pointer to cv
6695 // void.
6696 if (const auto *T = getAs<PointerType>())
6697 return !T->getPointeeType()->isFunctionType();
6698 else
6699 return false;
6700}
6701
6702inline bool Type::isFunctionPointerType() const {
6703 if (const auto *T = getAs<PointerType>())
6704 return T->getPointeeType()->isFunctionType();
6705 else
6706 return false;
6707}
6708
6709inline bool Type::isFunctionReferenceType() const {
6710 if (const auto *T = getAs<ReferenceType>())
6711 return T->getPointeeType()->isFunctionType();
6712 else
6713 return false;
6714}
6715
6716inline bool Type::isMemberPointerType() const {
6717 return isa<MemberPointerType>(CanonicalType);
6718}
6719
6720inline bool Type::isMemberFunctionPointerType() const {
6721 if (const auto *T = getAs<MemberPointerType>())
6722 return T->isMemberFunctionPointer();
6723 else
6724 return false;
6725}
6726
6727inline bool Type::isMemberDataPointerType() const {
6728 if (const auto *T = getAs<MemberPointerType>())
6729 return T->isMemberDataPointer();
6730 else
6731 return false;
6732}
6733
6734inline bool Type::isArrayType() const {
6735 return isa<ArrayType>(CanonicalType);
6736}
6737
6738inline bool Type::isConstantArrayType() const {
6739 return isa<ConstantArrayType>(CanonicalType);
6740}
6741
6742inline bool Type::isIncompleteArrayType() const {
6743 return isa<IncompleteArrayType>(CanonicalType);
6744}
6745
6746inline bool Type::isVariableArrayType() const {
6747 return isa<VariableArrayType>(CanonicalType);
6748}
6749
6750inline bool Type::isDependentSizedArrayType() const {
6751 return isa<DependentSizedArrayType>(CanonicalType);
6752}
6753
6754inline bool Type::isBuiltinType() const {
6755 return isa<BuiltinType>(CanonicalType);
6756}
6757
6758inline bool Type::isRecordType() const {
6759 return isa<RecordType>(CanonicalType);
6760}
6761
6762inline bool Type::isEnumeralType() const {
6763 return isa<EnumType>(CanonicalType);
31
Assuming field 'CanonicalType' is a 'EnumType'
32
Returning the value 1, which participates in a condition later
6764}
6765
6766inline bool Type::isAnyComplexType() const {
6767 return isa<ComplexType>(CanonicalType);
6768}
6769
6770inline bool Type::isVectorType() const {
6771 return isa<VectorType>(CanonicalType);
6772}
6773
6774inline bool Type::isExtVectorType() const {
6775 return isa<ExtVectorType>(CanonicalType);
6776}
6777
6778inline bool Type::isMatrixType() const {
6779 return isa<MatrixType>(CanonicalType);
6780}
6781
6782inline bool Type::isConstantMatrixType() const {
6783 return isa<ConstantMatrixType>(CanonicalType);
6784}
6785
6786inline bool Type::isDependentAddressSpaceType() const {
6787 return isa<DependentAddressSpaceType>(CanonicalType);
6788}
6789
6790inline bool Type::isObjCObjectPointerType() const {
6791 return isa<ObjCObjectPointerType>(CanonicalType);
6792}
6793
6794inline bool Type::isObjCObjectType() const {
6795 return isa<ObjCObjectType>(CanonicalType);
6796}
6797
6798inline bool Type::isObjCObjectOrInterfaceType() const {
6799 return isa<ObjCInterfaceType>(CanonicalType) ||
6800 isa<ObjCObjectType>(CanonicalType);
6801}
6802
6803inline bool Type::isAtomicType() const {
6804 return isa<AtomicType>(CanonicalType);
6805}
6806
6807inline bool Type::isUndeducedAutoType() const {
6808 return isa<AutoType>(CanonicalType);
6809}
6810
6811inline bool Type::isObjCQualifiedIdType() const {
6812 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6813 return OPT->isObjCQualifiedIdType();
6814 return false;
6815}
6816
6817inline bool Type::isObjCQualifiedClassType() const {
6818 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6819 return OPT->isObjCQualifiedClassType();
6820 return false;
6821}
6822
6823inline bool Type::isObjCIdType() const {
6824 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6825 return OPT->isObjCIdType();
6826 return false;
6827}
6828
6829inline bool Type::isObjCClassType() const {
6830 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6831 return OPT->isObjCClassType();
6832 return false;
6833}
6834
6835inline bool Type::isObjCSelType() const {
6836 if (const auto *OPT = getAs<PointerType>())
6837 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6838 return false;
6839}
6840
6841inline bool Type::isObjCBuiltinType() const {
6842 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6843}
6844
6845inline bool Type::isDecltypeType() const {
6846 return isa<DecltypeType>(this);
6847}
6848
6849#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6850 inline bool Type::is##Id##Type() const { \
6851 return isSpecificBuiltinType(BuiltinType::Id); \
6852 }
6853#include "clang/Basic/OpenCLImageTypes.def"
6854
6855inline bool Type::isSamplerT() const {
6856 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6857}
6858
6859inline bool Type::isEventT() const {
6860 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6861}
6862
6863inline bool Type::isClkEventT() const {
6864 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6865}
6866
6867inline bool Type::isQueueT() const {
6868 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6869}
6870
6871inline bool Type::isReserveIDT() const {
6872 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6873}
6874
6875inline bool Type::isImageType() const {
6876#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6877 return
6878#include "clang/Basic/OpenCLImageTypes.def"
6879 false; // end boolean or operation
6880}
6881
6882inline bool Type::isPipeType() const {
6883 return isa<PipeType>(CanonicalType);
6884}
6885
6886inline bool Type::isExtIntType() const {
6887 return isa<ExtIntType>(CanonicalType);
6888}
6889
6890#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6891 inline bool Type::is##Id##Type() const { \
6892 return isSpecificBuiltinType(BuiltinType::Id); \
6893 }
6894#include "clang/Basic/OpenCLExtensionTypes.def"
6895
6896inline bool Type::isOCLIntelSubgroupAVCType() const {
6897#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6898 isOCLIntelSubgroupAVC##Id##Type() ||
6899 return
6900#include "clang/Basic/OpenCLExtensionTypes.def"
6901 false; // end of boolean or operation
6902}
6903
6904inline bool Type::isOCLExtOpaqueType() const {
6905#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6906 return
6907#include "clang/Basic/OpenCLExtensionTypes.def"
6908 false; // end of boolean or operation
6909}
6910
6911inline bool Type::isOpenCLSpecificType() const {
6912 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6913 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6914}
6915
6916inline bool Type::isTemplateTypeParmType() const {
6917 return isa<TemplateTypeParmType>(CanonicalType);
6918}
6919
6920inline bool Type::isSpecificBuiltinType(unsigned K) const {
6921 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6922 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6923 }
6924 return false;
6925}
6926
6927inline bool Type::isPlaceholderType() const {
6928 if (const auto *BT = dyn_cast<BuiltinType>(this))
6929 return BT->isPlaceholderType();
6930 return false;
6931}
6932
6933inline const BuiltinType *Type::getAsPlaceholderType() const {
6934 if (const auto *BT = dyn_cast<BuiltinType>(this))
6935 if (BT->isPlaceholderType())
6936 return BT;
6937 return nullptr;
6938}
6939
6940inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6941 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 6941, __PRETTY_FUNCTION__))
;
6942 return isSpecificBuiltinType(K);
6943}
6944
6945inline bool Type::isNonOverloadPlaceholderType() const {
6946 if (const auto *BT = dyn_cast<BuiltinType>(this))
6947 return BT->isNonOverloadPlaceholderType();
6948 return false;
6949}
6950
6951inline bool Type::isVoidType() const {
6952 return isSpecificBuiltinType(BuiltinType::Void);
6953}
6954
6955inline bool Type::isHalfType() const {
6956 // FIXME: Should we allow complex __fp16? Probably not.
6957 return isSpecificBuiltinType(BuiltinType::Half);
6958}
6959
6960inline bool Type::isFloat16Type() const {
6961 return isSpecificBuiltinType(BuiltinType::Float16);
6962}
6963
6964inline bool Type::isBFloat16Type() const {
6965 return isSpecificBuiltinType(BuiltinType::BFloat16);
6966}
6967
6968inline bool Type::isFloat128Type() const {
6969 return isSpecificBuiltinType(BuiltinType::Float128);
6970}
6971
6972inline bool Type::isNullPtrType() const {
6973 return isSpecificBuiltinType(BuiltinType::NullPtr);
6974}
6975
6976bool IsEnumDeclComplete(EnumDecl *);
6977bool IsEnumDeclScoped(EnumDecl *);
6978
6979inline bool Type::isIntegerType() const {
6980 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6981 return BT->getKind() >= BuiltinType::Bool &&
6982 BT->getKind() <= BuiltinType::Int128;
6983 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6984 // Incomplete enum types are not treated as integer types.
6985 // FIXME: In C++, enum types are never integer types.
6986 return IsEnumDeclComplete(ET->getDecl()) &&
6987 !IsEnumDeclScoped(ET->getDecl());
6988 }
6989 return isExtIntType();
6990}
6991
6992inline bool Type::isFixedPointType() const {
6993 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6994 return BT->getKind() >= BuiltinType::ShortAccum &&
6995 BT->getKind() <= BuiltinType::SatULongFract;
6996 }
6997 return false;
6998}
6999
7000inline bool Type::isFixedPointOrIntegerType() const {
7001 return isFixedPointType() || isIntegerType();
7002}
7003
7004inline bool Type::isSaturatedFixedPointType() const {
7005 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7006 return BT->getKind() >= BuiltinType::SatShortAccum &&
7007 BT->getKind() <= BuiltinType::SatULongFract;
7008 }
7009 return false;
7010}
7011
7012inline bool Type::isUnsaturatedFixedPointType() const {
7013 return isFixedPointType() && !isSaturatedFixedPointType();
7014}
7015
7016inline bool Type::isSignedFixedPointType() const {
7017 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7018 return ((BT->getKind() >= BuiltinType::ShortAccum &&
7019 BT->getKind() <= BuiltinType::LongAccum) ||
7020 (BT->getKind() >= BuiltinType::ShortFract &&
7021 BT->getKind() <= BuiltinType::LongFract) ||
7022 (BT->getKind() >= BuiltinType::SatShortAccum &&
7023 BT->getKind() <= BuiltinType::SatLongAccum) ||
7024 (BT->getKind() >= BuiltinType::SatShortFract &&
7025 BT->getKind() <= BuiltinType::SatLongFract));
7026 }
7027 return false;
7028}
7029
7030inline bool Type::isUnsignedFixedPointType() const {
7031 return isFixedPointType() && !isSignedFixedPointType();
7032}
7033
7034inline bool Type::isScalarType() const {
7035 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7036 return BT->getKind() > BuiltinType::Void &&
7037 BT->getKind() <= BuiltinType::NullPtr;
7038 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7039 // Enums are scalar types, but only if they are defined. Incomplete enums
7040 // are not treated as scalar types.
7041 return IsEnumDeclComplete(ET->getDecl());
7042 return isa<PointerType>(CanonicalType) ||
7043 isa<BlockPointerType>(CanonicalType) ||
7044 isa<MemberPointerType>(CanonicalType) ||
7045 isa<ComplexType>(CanonicalType) ||
7046 isa<ObjCObjectPointerType>(CanonicalType) ||
7047 isExtIntType();
7048}
7049
7050inline bool Type::isIntegralOrEnumerationType() const {
7051 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7052 return BT->getKind() >= BuiltinType::Bool &&
7053 BT->getKind() <= BuiltinType::Int128;
7054
7055 // Check for a complete enum type; incomplete enum types are not properly an
7056 // enumeration type in the sense required here.
7057 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7058 return IsEnumDeclComplete(ET->getDecl());
7059
7060 return isExtIntType();
7061}
7062
7063inline bool Type::isBooleanType() const {
7064 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7065 return BT->getKind() == BuiltinType::Bool;
7066 return false;
7067}
7068
7069inline bool Type::isUndeducedType() const {
7070 auto *DT = getContainedDeducedType();
7071 return DT && !DT->isDeduced();
7072}
7073
7074/// Determines whether this is a type for which one can define
7075/// an overloaded operator.
7076inline bool Type::isOverloadableType() const {
7077 return isDependentType() || isRecordType() || isEnumeralType();
7078}
7079
7080/// Determines whether this type is written as a typedef-name.
7081inline bool Type::isTypedefNameType() const {
7082 if (getAs<TypedefType>())
7083 return true;
7084 if (auto *TST = getAs<TemplateSpecializationType>())
7085 return TST->isTypeAlias();
7086 return false;
7087}
7088
7089/// Determines whether this type can decay to a pointer type.
7090inline bool Type::canDecayToPointerType() const {
7091 return isFunctionType() || isArrayType();
7092}
7093
7094inline bool Type::hasPointerRepresentation() const {
7095 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7096 isObjCObjectPointerType() || isNullPtrType());
7097}
7098
7099inline bool Type::hasObjCPointerRepresentation() const {
7100 return isObjCObjectPointerType();
7101}
7102
7103inline const Type *Type::getBaseElementTypeUnsafe() const {
7104 const Type *type = this;
7105 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7106 type = arrayType->getElementType().getTypePtr();
7107 return type;
7108}
7109
7110inline const Type *Type::getPointeeOrArrayElementType() const {
7111 const Type *type = this;
7112 if (type->isAnyPointerType())
7113 return type->getPointeeType().getTypePtr();
7114 else if (type->isArrayType())
7115 return type->getBaseElementTypeUnsafe();
7116 return type;
7117}
7118/// Insertion operator for partial diagnostics. This allows sending adress
7119/// spaces into a diagnostic with <<.
7120inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7121 LangAS AS) {
7122 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7123 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7124 return PD;
7125}
7126
7127/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7128/// into a diagnostic with <<.
7129inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7130 Qualifiers Q) {
7131 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7132 DiagnosticsEngine::ArgumentKind::ak_qual);
7133 return PD;
7134}
7135
7136/// Insertion operator for partial diagnostics. This allows sending QualType's
7137/// into a diagnostic with <<.
7138inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7139 QualType T) {
7140 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7141 DiagnosticsEngine::ak_qualtype);
7142 return PD;
7143}
7144
7145// Helper class template that is used by Type::getAs to ensure that one does
7146// not try to look through a qualified type to get to an array type.
7147template <typename T>
7148using TypeIsArrayType =
7149 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7150 std::is_base_of<ArrayType, T>::value>;
7151
7152// Member-template getAs<specific type>'.
7153template <typename T> const T *Type::getAs() const {
7154 static_assert(!TypeIsArrayType<T>::value,
7155 "ArrayType cannot be used with getAs!");
7156
7157 // If this is directly a T type, return it.
7158 if (const auto *Ty = dyn_cast<T>(this))
7159 return Ty;
7160
7161 // If the canonical form of this type isn't the right kind, reject it.
7162 if (!isa<T>(CanonicalType))
7163 return nullptr;
7164
7165 // If this is a typedef for the type, strip the typedef off without
7166 // losing all typedef information.
7167 return cast<T>(getUnqualifiedDesugaredType());
7168}
7169
7170template <typename T> const T *Type::getAsAdjusted() const {
7171 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7172
7173 // If this is directly a T type, return it.
7174 if (const auto *Ty = dyn_cast<T>(this))
7175 return Ty;
7176
7177 // If the canonical form of this type isn't the right kind, reject it.
7178 if (!isa<T>(CanonicalType))
7179 return nullptr;
7180
7181 // Strip off type adjustments that do not modify the underlying nature of the
7182 // type.
7183 const Type *Ty = this;
7184 while (Ty) {
7185 if (const auto *A = dyn_cast<AttributedType>(Ty))
7186 Ty = A->getModifiedType().getTypePtr();
7187 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7188 Ty = E->desugar().getTypePtr();
7189 else if (const auto *P = dyn_cast<ParenType>(Ty))
7190 Ty = P->desugar().getTypePtr();
7191 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7192 Ty = A->desugar().getTypePtr();
7193 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7194 Ty = M->desugar().getTypePtr();
7195 else
7196 break;
7197 }
7198
7199 // Just because the canonical type is correct does not mean we can use cast<>,
7200 // since we may not have stripped off all the sugar down to the base type.
7201 return dyn_cast<T>(Ty);
7202}
7203
7204inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7205 // If this is directly an array type, return it.
7206 if (const auto *arr = dyn_cast<ArrayType>(this))
7207 return arr;
7208
7209 // If the canonical form of this type isn't the right kind, reject it.
7210 if (!isa<ArrayType>(CanonicalType))
7211 return nullptr;
7212
7213 // If this is a typedef for the type, strip the typedef off without
7214 // losing all typedef information.
7215 return cast<ArrayType>(getUnqualifiedDesugaredType());
7216}
7217
7218template <typename T> const T *Type::castAs() const {
7219 static_assert(!TypeIsArrayType<T>::value,
7220 "ArrayType cannot be used with castAs!");
7221
7222 if (const auto *ty = dyn_cast<T>(this)) return ty;
7223 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 7223, __PRETTY_FUNCTION__))
;
7224 return cast<T>(getUnqualifiedDesugaredType());
7225}
7226
7227inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7228 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 7228, __PRETTY_FUNCTION__))
;
7229 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7230 return cast<ArrayType>(getUnqualifiedDesugaredType());
7231}
7232
7233DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7234 QualType CanonicalPtr)
7235 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7236#ifndef NDEBUG
7237 QualType Adjusted = getAdjustedType();
7238 (void)AttributedType::stripOuterNullability(Adjusted);
7239 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 7239, __PRETTY_FUNCTION__))
;
7240#endif
7241}
7242
7243QualType DecayedType::getPointeeType() const {
7244 QualType Decayed = getDecayedType();
7245 (void)AttributedType::stripOuterNullability(Decayed);
7246 return cast<PointerType>(Decayed)->getPointeeType();
7247}
7248
7249// Get the decimal string representation of a fixed point type, represented
7250// as a scaled integer.
7251// TODO: At some point, we should change the arguments to instead just accept an
7252// APFixedPoint instead of APSInt and scale.
7253void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7254 unsigned Scale);
7255
7256} // namespace clang
7257
7258#endif // LLVM_CLANG_AST_TYPE_H