blob: a97968dc7b20967d8779ede200bc7788675ceb74 [file] [log] [blame]
Yi Kong878f9942023-12-13 12:55:04 +09001//===- Overload.h - C++ Overloading -----------------------------*- 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// This file defines the data structures and types used in C++
10// overload resolution.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_OVERLOAD_H
15#define LLVM_CLANG_SEMA_OVERLOAD_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/LLVM.h"
25#include "clang/Basic/SourceLocation.h"
26#include "clang/Sema/SemaFixItUtils.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/AlignOf.h"
34#include "llvm/Support/Allocator.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/ErrorHandling.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <utility>
41
42namespace clang {
43
44class APValue;
45class ASTContext;
46class Sema;
47
48 /// OverloadingResult - Capture the result of performing overload
49 /// resolution.
50 enum OverloadingResult {
51 /// Overload resolution succeeded.
52 OR_Success,
53
54 /// No viable function found.
55 OR_No_Viable_Function,
56
57 /// Ambiguous candidates found.
58 OR_Ambiguous,
59
60 /// Succeeded, but refers to a deleted function.
61 OR_Deleted
62 };
63
64 enum OverloadCandidateDisplayKind {
65 /// Requests that all candidates be shown. Viable candidates will
66 /// be printed first.
67 OCD_AllCandidates,
68
69 /// Requests that only viable candidates be shown.
70 OCD_ViableCandidates,
71
72 /// Requests that only tied-for-best candidates be shown.
73 OCD_AmbiguousCandidates
74 };
75
76 /// The parameter ordering that will be used for the candidate. This is
77 /// used to represent C++20 binary operator rewrites that reverse the order
78 /// of the arguments. If the parameter ordering is Reversed, the Args list is
79 /// reversed (but obviously the ParamDecls for the function are not).
80 ///
81 /// After forming an OverloadCandidate with reversed parameters, the list
82 /// of conversions will (as always) be indexed by argument, so will be
83 /// in reverse parameter order.
84 enum class OverloadCandidateParamOrder : char { Normal, Reversed };
85
86 /// The kinds of rewrite we perform on overload candidates. Note that the
87 /// values here are chosen to serve as both bitflags and as a rank (lower
88 /// values are preferred by overload resolution).
89 enum OverloadCandidateRewriteKind : unsigned {
90 /// Candidate is not a rewritten candidate.
91 CRK_None = 0x0,
92
93 /// Candidate is a rewritten candidate with a different operator name.
94 CRK_DifferentOperator = 0x1,
95
96 /// Candidate is a rewritten candidate with a reversed order of parameters.
97 CRK_Reversed = 0x2,
98 };
99
100 /// ImplicitConversionKind - The kind of implicit conversion used to
101 /// convert an argument to a parameter's type. The enumerator values
102 /// match with the table titled 'Conversions' in [over.ics.scs] and are listed
103 /// such that better conversion kinds have smaller values.
104 enum ImplicitConversionKind {
105 /// Identity conversion (no conversion)
106 ICK_Identity = 0,
107
108 /// Lvalue-to-rvalue conversion (C++ [conv.lval])
109 ICK_Lvalue_To_Rvalue,
110
111 /// Array-to-pointer conversion (C++ [conv.array])
112 ICK_Array_To_Pointer,
113
114 /// Function-to-pointer (C++ [conv.array])
115 ICK_Function_To_Pointer,
116
117 /// Function pointer conversion (C++17 [conv.fctptr])
118 ICK_Function_Conversion,
119
120 /// Qualification conversions (C++ [conv.qual])
121 ICK_Qualification,
122
123 /// Integral promotions (C++ [conv.prom])
124 ICK_Integral_Promotion,
125
126 /// Floating point promotions (C++ [conv.fpprom])
127 ICK_Floating_Promotion,
128
129 /// Complex promotions (Clang extension)
130 ICK_Complex_Promotion,
131
132 /// Integral conversions (C++ [conv.integral])
133 ICK_Integral_Conversion,
134
135 /// Floating point conversions (C++ [conv.double]
136 ICK_Floating_Conversion,
137
138 /// Complex conversions (C99 6.3.1.6)
139 ICK_Complex_Conversion,
140
141 /// Floating-integral conversions (C++ [conv.fpint])
142 ICK_Floating_Integral,
143
144 /// Pointer conversions (C++ [conv.ptr])
145 ICK_Pointer_Conversion,
146
147 /// Pointer-to-member conversions (C++ [conv.mem])
148 ICK_Pointer_Member,
149
150 /// Boolean conversions (C++ [conv.bool])
151 ICK_Boolean_Conversion,
152
153 /// Conversions between compatible types in C99
154 ICK_Compatible_Conversion,
155
156 /// Derived-to-base (C++ [over.best.ics])
157 ICK_Derived_To_Base,
158
159 /// Vector conversions
160 ICK_Vector_Conversion,
161
162 /// Arm SVE Vector conversions
163 ICK_SVE_Vector_Conversion,
164
165 /// RISC-V RVV Vector conversions
166 ICK_RVV_Vector_Conversion,
167
168 /// A vector splat from an arithmetic type
169 ICK_Vector_Splat,
170
171 /// Complex-real conversions (C99 6.3.1.7)
172 ICK_Complex_Real,
173
174 /// Block Pointer conversions
175 ICK_Block_Pointer_Conversion,
176
177 /// Transparent Union Conversions
178 ICK_TransparentUnionConversion,
179
180 /// Objective-C ARC writeback conversion
181 ICK_Writeback_Conversion,
182
183 /// Zero constant to event (OpenCL1.2 6.12.10)
184 ICK_Zero_Event_Conversion,
185
186 /// Zero constant to queue
187 ICK_Zero_Queue_Conversion,
188
189 /// Conversions allowed in C, but not C++
190 ICK_C_Only_Conversion,
191
192 /// C-only conversion between pointers with incompatible types
193 ICK_Incompatible_Pointer_Conversion,
194
195 /// The number of conversion kinds
196 ICK_Num_Conversion_Kinds,
197 };
198
199 /// ImplicitConversionRank - The rank of an implicit conversion
200 /// kind. The enumerator values match with Table 9 of (C++
201 /// 13.3.3.1.1) and are listed such that better conversion ranks
202 /// have smaller values.
203 enum ImplicitConversionRank {
204 /// Exact Match
205 ICR_Exact_Match = 0,
206
207 /// Promotion
208 ICR_Promotion,
209
210 /// Conversion
211 ICR_Conversion,
212
213 /// OpenCL Scalar Widening
214 ICR_OCL_Scalar_Widening,
215
216 /// Complex <-> Real conversion
217 ICR_Complex_Real_Conversion,
218
219 /// ObjC ARC writeback conversion
220 ICR_Writeback_Conversion,
221
222 /// Conversion only allowed in the C standard (e.g. void* to char*).
223 ICR_C_Conversion,
224
225 /// Conversion not allowed by the C standard, but that we accept as an
226 /// extension anyway.
227 ICR_C_Conversion_Extension
228 };
229
230 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
231
232 /// NarrowingKind - The kind of narrowing conversion being performed by a
233 /// standard conversion sequence according to C++11 [dcl.init.list]p7.
234 enum NarrowingKind {
235 /// Not a narrowing conversion.
236 NK_Not_Narrowing,
237
238 /// A narrowing conversion by virtue of the source and destination types.
239 NK_Type_Narrowing,
240
241 /// A narrowing conversion, because a constant expression got narrowed.
242 NK_Constant_Narrowing,
243
244 /// A narrowing conversion, because a non-constant-expression variable might
245 /// have got narrowed.
246 NK_Variable_Narrowing,
247
248 /// Cannot tell whether this is a narrowing conversion because the
249 /// expression is value-dependent.
250 NK_Dependent_Narrowing,
251 };
252
253 /// StandardConversionSequence - represents a standard conversion
254 /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
255 /// contains between zero and three conversions. If a particular
256 /// conversion is not needed, it will be set to the identity conversion
257 /// (ICK_Identity). Note that the three conversions are
258 /// specified as separate members (rather than in an array) so that
259 /// we can keep the size of a standard conversion sequence to a
260 /// single word.
261 class StandardConversionSequence {
262 public:
263 /// First -- The first conversion can be an lvalue-to-rvalue
264 /// conversion, array-to-pointer conversion, or
265 /// function-to-pointer conversion.
266 ImplicitConversionKind First : 8;
267
268 /// Second - The second conversion can be an integral promotion,
269 /// floating point promotion, integral conversion, floating point
270 /// conversion, floating-integral conversion, pointer conversion,
271 /// pointer-to-member conversion, or boolean conversion.
272 ImplicitConversionKind Second : 8;
273
274 /// Third - The third conversion can be a qualification conversion
275 /// or a function conversion.
276 ImplicitConversionKind Third : 8;
277
278 /// Whether this is the deprecated conversion of a
279 /// string literal to a pointer to non-const character data
280 /// (C++ 4.2p2).
281 unsigned DeprecatedStringLiteralToCharPtr : 1;
282
283 /// Whether the qualification conversion involves a change in the
284 /// Objective-C lifetime (for automatic reference counting).
285 unsigned QualificationIncludesObjCLifetime : 1;
286
287 /// IncompatibleObjC - Whether this is an Objective-C conversion
288 /// that we should warn about (if we actually use it).
289 unsigned IncompatibleObjC : 1;
290
291 /// ReferenceBinding - True when this is a reference binding
292 /// (C++ [over.ics.ref]).
293 unsigned ReferenceBinding : 1;
294
295 /// DirectBinding - True when this is a reference binding that is a
296 /// direct binding (C++ [dcl.init.ref]).
297 unsigned DirectBinding : 1;
298
299 /// Whether this is an lvalue reference binding (otherwise, it's
300 /// an rvalue reference binding).
301 unsigned IsLvalueReference : 1;
302
303 /// Whether we're binding to a function lvalue.
304 unsigned BindsToFunctionLvalue : 1;
305
306 /// Whether we're binding to an rvalue.
307 unsigned BindsToRvalue : 1;
308
309 /// Whether this binds an implicit object argument to a
310 /// non-static member function without a ref-qualifier.
311 unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
312
313 /// Whether this binds a reference to an object with a different
314 /// Objective-C lifetime qualifier.
315 unsigned ObjCLifetimeConversionBinding : 1;
316
317 /// FromType - The type that this conversion is converting
318 /// from. This is an opaque pointer that can be translated into a
319 /// QualType.
320 void *FromTypePtr;
321
322 /// ToType - The types that this conversion is converting to in
323 /// each step. This is an opaque pointer that can be translated
324 /// into a QualType.
325 void *ToTypePtrs[3];
326
327 /// CopyConstructor - The copy constructor that is used to perform
328 /// this conversion, when the conversion is actually just the
329 /// initialization of an object via copy constructor. Such
330 /// conversions are either identity conversions or derived-to-base
331 /// conversions.
332 CXXConstructorDecl *CopyConstructor;
333 DeclAccessPair FoundCopyConstructor;
334
335 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
336
337 void setToType(unsigned Idx, QualType T) {
338 assert(Idx < 3 && "To type index is out of range");
339 ToTypePtrs[Idx] = T.getAsOpaquePtr();
340 }
341
342 void setAllToTypes(QualType T) {
343 ToTypePtrs[0] = T.getAsOpaquePtr();
344 ToTypePtrs[1] = ToTypePtrs[0];
345 ToTypePtrs[2] = ToTypePtrs[0];
346 }
347
348 QualType getFromType() const {
349 return QualType::getFromOpaquePtr(FromTypePtr);
350 }
351
352 QualType getToType(unsigned Idx) const {
353 assert(Idx < 3 && "To type index is out of range");
354 return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
355 }
356
357 void setAsIdentityConversion();
358
359 bool isIdentityConversion() const {
360 return Second == ICK_Identity && Third == ICK_Identity;
361 }
362
363 ImplicitConversionRank getRank() const;
364 NarrowingKind
365 getNarrowingKind(ASTContext &Context, const Expr *Converted,
366 APValue &ConstantValue, QualType &ConstantType,
367 bool IgnoreFloatToIntegralConversion = false) const;
368 bool isPointerConversionToBool() const;
369 bool isPointerConversionToVoidPointer(ASTContext& Context) const;
370 void dump() const;
371 };
372
373 /// UserDefinedConversionSequence - Represents a user-defined
374 /// conversion sequence (C++ 13.3.3.1.2).
375 struct UserDefinedConversionSequence {
376 /// Represents the standard conversion that occurs before
377 /// the actual user-defined conversion.
378 ///
379 /// C++11 13.3.3.1.2p1:
380 /// If the user-defined conversion is specified by a constructor
381 /// (12.3.1), the initial standard conversion sequence converts
382 /// the source type to the type required by the argument of the
383 /// constructor. If the user-defined conversion is specified by
384 /// a conversion function (12.3.2), the initial standard
385 /// conversion sequence converts the source type to the implicit
386 /// object parameter of the conversion function.
387 StandardConversionSequence Before;
388
389 /// EllipsisConversion - When this is true, it means user-defined
390 /// conversion sequence starts with a ... (ellipsis) conversion, instead of
391 /// a standard conversion. In this case, 'Before' field must be ignored.
392 // FIXME. I much rather put this as the first field. But there seems to be
393 // a gcc code gen. bug which causes a crash in a test. Putting it here seems
394 // to work around the crash.
395 bool EllipsisConversion : 1;
396
397 /// HadMultipleCandidates - When this is true, it means that the
398 /// conversion function was resolved from an overloaded set having
399 /// size greater than 1.
400 bool HadMultipleCandidates : 1;
401
402 /// After - Represents the standard conversion that occurs after
403 /// the actual user-defined conversion.
404 StandardConversionSequence After;
405
406 /// ConversionFunction - The function that will perform the
407 /// user-defined conversion. Null if the conversion is an
408 /// aggregate initialization from an initializer list.
409 FunctionDecl* ConversionFunction;
410
411 /// The declaration that we found via name lookup, which might be
412 /// the same as \c ConversionFunction or it might be a using declaration
413 /// that refers to \c ConversionFunction.
414 DeclAccessPair FoundConversionFunction;
415
416 void dump() const;
417 };
418
419 /// Represents an ambiguous user-defined conversion sequence.
420 struct AmbiguousConversionSequence {
421 using ConversionSet =
422 SmallVector<std::pair<NamedDecl *, FunctionDecl *>, 4>;
423
424 void *FromTypePtr;
425 void *ToTypePtr;
426 char Buffer[sizeof(ConversionSet)];
427
428 QualType getFromType() const {
429 return QualType::getFromOpaquePtr(FromTypePtr);
430 }
431
432 QualType getToType() const {
433 return QualType::getFromOpaquePtr(ToTypePtr);
434 }
435
436 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
437 void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
438
439 ConversionSet &conversions() {
440 return *reinterpret_cast<ConversionSet*>(Buffer);
441 }
442
443 const ConversionSet &conversions() const {
444 return *reinterpret_cast<const ConversionSet*>(Buffer);
445 }
446
447 void addConversion(NamedDecl *Found, FunctionDecl *D) {
448 conversions().push_back(std::make_pair(Found, D));
449 }
450
451 using iterator = ConversionSet::iterator;
452
453 iterator begin() { return conversions().begin(); }
454 iterator end() { return conversions().end(); }
455
456 using const_iterator = ConversionSet::const_iterator;
457
458 const_iterator begin() const { return conversions().begin(); }
459 const_iterator end() const { return conversions().end(); }
460
461 void construct();
462 void destruct();
463 void copyFrom(const AmbiguousConversionSequence &);
464 };
465
466 /// BadConversionSequence - Records information about an invalid
467 /// conversion sequence.
468 struct BadConversionSequence {
469 enum FailureKind {
470 no_conversion,
471 unrelated_class,
472 bad_qualifiers,
473 lvalue_ref_to_rvalue,
474 rvalue_ref_to_lvalue,
475 too_few_initializers,
476 too_many_initializers,
477 };
478
479 // This can be null, e.g. for implicit object arguments.
480 Expr *FromExpr;
481
482 FailureKind Kind;
483
484 private:
485 // The type we're converting from (an opaque QualType).
486 void *FromTy;
487
488 // The type we're converting to (an opaque QualType).
489 void *ToTy;
490
491 public:
492 void init(FailureKind K, Expr *From, QualType To) {
493 init(K, From->getType(), To);
494 FromExpr = From;
495 }
496
497 void init(FailureKind K, QualType From, QualType To) {
498 Kind = K;
499 FromExpr = nullptr;
500 setFromType(From);
501 setToType(To);
502 }
503
504 QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
505 QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
506
507 void setFromExpr(Expr *E) {
508 FromExpr = E;
509 setFromType(E->getType());
510 }
511
512 void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
513 void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
514 };
515
516 /// ImplicitConversionSequence - Represents an implicit conversion
517 /// sequence, which may be a standard conversion sequence
518 /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
519 /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
520 class ImplicitConversionSequence {
521 public:
522 /// Kind - The kind of implicit conversion sequence. BadConversion
523 /// specifies that there is no conversion from the source type to
524 /// the target type. AmbiguousConversion represents the unique
525 /// ambiguous conversion (C++0x [over.best.ics]p10).
526 /// StaticObjectArgumentConversion represents the conversion rules for
527 /// the synthesized first argument of calls to static member functions
528 /// ([over.best.ics.general]p8).
529 enum Kind {
530 StandardConversion = 0,
531 StaticObjectArgumentConversion,
532 UserDefinedConversion,
533 AmbiguousConversion,
534 EllipsisConversion,
535 BadConversion
536 };
537
538 private:
539 enum {
540 Uninitialized = BadConversion + 1
541 };
542
543 /// ConversionKind - The kind of implicit conversion sequence.
544 unsigned ConversionKind : 31;
545
546 // Whether the initializer list was of an incomplete array.
547 unsigned InitializerListOfIncompleteArray : 1;
548
549 /// When initializing an array or std::initializer_list from an
550 /// initializer-list, this is the array or std::initializer_list type being
551 /// initialized. The remainder of the conversion sequence, including ToType,
552 /// describe the worst conversion of an initializer to an element of the
553 /// array or std::initializer_list. (Note, 'worst' is not well defined.)
554 QualType InitializerListContainerType;
555
556 void setKind(Kind K) {
557 destruct();
558 ConversionKind = K;
559 }
560
561 void destruct() {
562 if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
563 }
564
565 public:
566 union {
567 /// When ConversionKind == StandardConversion, provides the
568 /// details of the standard conversion sequence.
569 StandardConversionSequence Standard;
570
571 /// When ConversionKind == UserDefinedConversion, provides the
572 /// details of the user-defined conversion sequence.
573 UserDefinedConversionSequence UserDefined;
574
575 /// When ConversionKind == AmbiguousConversion, provides the
576 /// details of the ambiguous conversion.
577 AmbiguousConversionSequence Ambiguous;
578
579 /// When ConversionKind == BadConversion, provides the details
580 /// of the bad conversion.
581 BadConversionSequence Bad;
582 };
583
584 ImplicitConversionSequence()
585 : ConversionKind(Uninitialized),
586 InitializerListOfIncompleteArray(false) {
587 Standard.setAsIdentityConversion();
588 }
589
590 ImplicitConversionSequence(const ImplicitConversionSequence &Other)
591 : ConversionKind(Other.ConversionKind),
592 InitializerListOfIncompleteArray(
593 Other.InitializerListOfIncompleteArray),
594 InitializerListContainerType(Other.InitializerListContainerType) {
595 switch (ConversionKind) {
596 case Uninitialized: break;
597 case StandardConversion: Standard = Other.Standard; break;
598 case StaticObjectArgumentConversion:
599 break;
600 case UserDefinedConversion: UserDefined = Other.UserDefined; break;
601 case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
602 case EllipsisConversion: break;
603 case BadConversion: Bad = Other.Bad; break;
604 }
605 }
606
607 ImplicitConversionSequence &
608 operator=(const ImplicitConversionSequence &Other) {
609 destruct();
610 new (this) ImplicitConversionSequence(Other);
611 return *this;
612 }
613
614 ~ImplicitConversionSequence() {
615 destruct();
616 }
617
618 Kind getKind() const {
619 assert(isInitialized() && "querying uninitialized conversion");
620 return Kind(ConversionKind);
621 }
622
623 /// Return a ranking of the implicit conversion sequence
624 /// kind, where smaller ranks represent better conversion
625 /// sequences.
626 ///
627 /// In particular, this routine gives user-defined conversion
628 /// sequences and ambiguous conversion sequences the same rank,
629 /// per C++ [over.best.ics]p10.
630 unsigned getKindRank() const {
631 switch (getKind()) {
632 case StandardConversion:
633 case StaticObjectArgumentConversion:
634 return 0;
635
636 case UserDefinedConversion:
637 case AmbiguousConversion:
638 return 1;
639
640 case EllipsisConversion:
641 return 2;
642
643 case BadConversion:
644 return 3;
645 }
646
647 llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
648 }
649
650 bool isBad() const { return getKind() == BadConversion; }
651 bool isStandard() const { return getKind() == StandardConversion; }
652 bool isStaticObjectArgument() const {
653 return getKind() == StaticObjectArgumentConversion;
654 }
655 bool isEllipsis() const { return getKind() == EllipsisConversion; }
656 bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
657 bool isUserDefined() const { return getKind() == UserDefinedConversion; }
658 bool isFailure() const { return isBad() || isAmbiguous(); }
659
660 /// Determines whether this conversion sequence has been
661 /// initialized. Most operations should never need to query
662 /// uninitialized conversions and should assert as above.
663 bool isInitialized() const { return ConversionKind != Uninitialized; }
664
665 /// Sets this sequence as a bad conversion for an explicit argument.
666 void setBad(BadConversionSequence::FailureKind Failure,
667 Expr *FromExpr, QualType ToType) {
668 setKind(BadConversion);
669 Bad.init(Failure, FromExpr, ToType);
670 }
671
672 /// Sets this sequence as a bad conversion for an implicit argument.
673 void setBad(BadConversionSequence::FailureKind Failure,
674 QualType FromType, QualType ToType) {
675 setKind(BadConversion);
676 Bad.init(Failure, FromType, ToType);
677 }
678
679 void setStandard() { setKind(StandardConversion); }
680 void setStaticObjectArgument() { setKind(StaticObjectArgumentConversion); }
681 void setEllipsis() { setKind(EllipsisConversion); }
682 void setUserDefined() { setKind(UserDefinedConversion); }
683
684 void setAmbiguous() {
685 if (ConversionKind == AmbiguousConversion) return;
686 ConversionKind = AmbiguousConversion;
687 Ambiguous.construct();
688 }
689
690 void setAsIdentityConversion(QualType T) {
691 setStandard();
692 Standard.setAsIdentityConversion();
693 Standard.setFromType(T);
694 Standard.setAllToTypes(T);
695 }
696
697 // True iff this is a conversion sequence from an initializer list to an
698 // array or std::initializer.
699 bool hasInitializerListContainerType() const {
700 return !InitializerListContainerType.isNull();
701 }
702 void setInitializerListContainerType(QualType T, bool IA) {
703 InitializerListContainerType = T;
704 InitializerListOfIncompleteArray = IA;
705 }
706 bool isInitializerListOfIncompleteArray() const {
707 return InitializerListOfIncompleteArray;
708 }
709 QualType getInitializerListContainerType() const {
710 assert(hasInitializerListContainerType() &&
711 "not initializer list container");
712 return InitializerListContainerType;
713 }
714
715 /// Form an "implicit" conversion sequence from nullptr_t to bool, for a
716 /// direct-initialization of a bool object from nullptr_t.
717 static ImplicitConversionSequence getNullptrToBool(QualType SourceType,
718 QualType DestType,
719 bool NeedLValToRVal) {
720 ImplicitConversionSequence ICS;
721 ICS.setStandard();
722 ICS.Standard.setAsIdentityConversion();
723 ICS.Standard.setFromType(SourceType);
724 if (NeedLValToRVal)
725 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
726 ICS.Standard.setToType(0, SourceType);
727 ICS.Standard.Second = ICK_Boolean_Conversion;
728 ICS.Standard.setToType(1, DestType);
729 ICS.Standard.setToType(2, DestType);
730 return ICS;
731 }
732
733 // The result of a comparison between implicit conversion
734 // sequences. Use Sema::CompareImplicitConversionSequences to
735 // actually perform the comparison.
736 enum CompareKind {
737 Better = -1,
738 Indistinguishable = 0,
739 Worse = 1
740 };
741
742 void DiagnoseAmbiguousConversion(Sema &S,
743 SourceLocation CaretLoc,
744 const PartialDiagnostic &PDiag) const;
745
746 void dump() const;
747 };
748
749 enum OverloadFailureKind {
750 ovl_fail_too_many_arguments,
751 ovl_fail_too_few_arguments,
752 ovl_fail_bad_conversion,
753 ovl_fail_bad_deduction,
754
755 /// This conversion candidate was not considered because it
756 /// duplicates the work of a trivial or derived-to-base
757 /// conversion.
758 ovl_fail_trivial_conversion,
759
760 /// This conversion candidate was not considered because it is
761 /// an illegal instantiation of a constructor temploid: it is
762 /// callable with one argument, we only have one argument, and
763 /// its first parameter type is exactly the type of the class.
764 ///
765 /// Defining such a constructor directly is illegal, and
766 /// template-argument deduction is supposed to ignore such
767 /// instantiations, but we can still get one with the right
768 /// kind of implicit instantiation.
769 ovl_fail_illegal_constructor,
770
771 /// This conversion candidate is not viable because its result
772 /// type is not implicitly convertible to the desired type.
773 ovl_fail_bad_final_conversion,
774
775 /// This conversion function template specialization candidate is not
776 /// viable because the final conversion was not an exact match.
777 ovl_fail_final_conversion_not_exact,
778
779 /// (CUDA) This candidate was not viable because the callee
780 /// was not accessible from the caller's target (i.e. host->device,
781 /// global->host, device->host).
782 ovl_fail_bad_target,
783
784 /// This candidate function was not viable because an enable_if
785 /// attribute disabled it.
786 ovl_fail_enable_if,
787
788 /// This candidate constructor or conversion function is explicit but
789 /// the context doesn't permit explicit functions.
790 ovl_fail_explicit,
791
792 /// This candidate was not viable because its address could not be taken.
793 ovl_fail_addr_not_available,
794
795 /// This inherited constructor is not viable because it would slice the
796 /// argument.
797 ovl_fail_inhctor_slice,
798
799 /// This candidate was not viable because it is a non-default multiversioned
800 /// function.
801 ovl_non_default_multiversion_function,
802
803 /// This constructor/conversion candidate fail due to an address space
804 /// mismatch between the object being constructed and the overload
805 /// candidate.
806 ovl_fail_object_addrspace_mismatch,
807
808 /// This candidate was not viable because its associated constraints were
809 /// not satisfied.
810 ovl_fail_constraints_not_satisfied,
811
812 /// This candidate was not viable because it has internal linkage and is
813 /// from a different module unit than the use.
814 ovl_fail_module_mismatched,
815 };
816
817 /// A list of implicit conversion sequences for the arguments of an
818 /// OverloadCandidate.
819 using ConversionSequenceList =
820 llvm::MutableArrayRef<ImplicitConversionSequence>;
821
822 /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
823 struct OverloadCandidate {
824 /// Function - The actual function that this candidate
825 /// represents. When NULL, this is a built-in candidate
826 /// (C++ [over.oper]) or a surrogate for a conversion to a
827 /// function pointer or reference (C++ [over.call.object]).
828 FunctionDecl *Function;
829
830 /// FoundDecl - The original declaration that was looked up /
831 /// invented / otherwise found, together with its access.
832 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
833 DeclAccessPair FoundDecl;
834
835 /// BuiltinParamTypes - Provides the parameter types of a built-in overload
836 /// candidate. Only valid when Function is NULL.
837 QualType BuiltinParamTypes[3];
838
839 /// Surrogate - The conversion function for which this candidate
840 /// is a surrogate, but only if IsSurrogate is true.
841 CXXConversionDecl *Surrogate;
842
843 /// The conversion sequences used to convert the function arguments
844 /// to the function parameters. Note that these are indexed by argument,
845 /// so may not match the parameter order of Function.
846 ConversionSequenceList Conversions;
847
848 /// The FixIt hints which can be used to fix the Bad candidate.
849 ConversionFixItGenerator Fix;
850
851 /// Viable - True to indicate that this overload candidate is viable.
852 bool Viable : 1;
853
854 /// Whether this candidate is the best viable function, or tied for being
855 /// the best viable function.
856 ///
857 /// For an ambiguous overload resolution, indicates whether this candidate
858 /// was part of the ambiguity kernel: the minimal non-empty set of viable
859 /// candidates such that all elements of the ambiguity kernel are better
860 /// than all viable candidates not in the ambiguity kernel.
861 bool Best : 1;
862
863 /// IsSurrogate - True to indicate that this candidate is a
864 /// surrogate for a conversion to a function pointer or reference
865 /// (C++ [over.call.object]).
866 bool IsSurrogate : 1;
867
868 /// IgnoreObjectArgument - True to indicate that the first
869 /// argument's conversion, which for this function represents the
870 /// implicit object argument, should be ignored. This will be true
871 /// when the candidate is a static member function (where the
872 /// implicit object argument is just a placeholder) or a
873 /// non-static member function when the call doesn't have an
874 /// object argument.
875 bool IgnoreObjectArgument : 1;
876
877 /// True if the candidate was found using ADL.
878 CallExpr::ADLCallKind IsADLCandidate : 1;
879
880 /// Whether this is a rewritten candidate, and if so, of what kind?
881 unsigned RewriteKind : 2;
882
883 /// FailureKind - The reason why this candidate is not viable.
884 /// Actually an OverloadFailureKind.
885 unsigned char FailureKind;
886
887 /// The number of call arguments that were explicitly provided,
888 /// to be used while performing partial ordering of function templates.
889 unsigned ExplicitCallArguments;
890
891 union {
892 DeductionFailureInfo DeductionFailure;
893
894 /// FinalConversion - For a conversion function (where Function is
895 /// a CXXConversionDecl), the standard conversion that occurs
896 /// after the call to the overload candidate to convert the result
897 /// of calling the conversion function to the required type.
898 StandardConversionSequence FinalConversion;
899 };
900
901 /// Get RewriteKind value in OverloadCandidateRewriteKind type (This
902 /// function is to workaround the spurious GCC bitfield enum warning)
903 OverloadCandidateRewriteKind getRewriteKind() const {
904 return static_cast<OverloadCandidateRewriteKind>(RewriteKind);
905 }
906
907 bool isReversed() const { return getRewriteKind() & CRK_Reversed; }
908
909 /// hasAmbiguousConversion - Returns whether this overload
910 /// candidate requires an ambiguous conversion or not.
911 bool hasAmbiguousConversion() const {
912 for (auto &C : Conversions) {
913 if (!C.isInitialized()) return false;
914 if (C.isAmbiguous()) return true;
915 }
916 return false;
917 }
918
919 bool TryToFixBadConversion(unsigned Idx, Sema &S) {
920 bool CanFix = Fix.tryToFixConversion(
921 Conversions[Idx].Bad.FromExpr,
922 Conversions[Idx].Bad.getFromType(),
923 Conversions[Idx].Bad.getToType(), S);
924
925 // If at least one conversion fails, the candidate cannot be fixed.
926 if (!CanFix)
927 Fix.clear();
928
929 return CanFix;
930 }
931
932 unsigned getNumParams() const {
933 if (IsSurrogate) {
934 QualType STy = Surrogate->getConversionType();
935 while (STy->isPointerType() || STy->isReferenceType())
936 STy = STy->getPointeeType();
937 return STy->castAs<FunctionProtoType>()->getNumParams();
938 }
939 if (Function)
940 return Function->getNumParams();
941 return ExplicitCallArguments;
942 }
943
944 bool NotValidBecauseConstraintExprHasError() const;
945
946 private:
947 friend class OverloadCandidateSet;
948 OverloadCandidate()
949 : IsSurrogate(false), IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
950 };
951
952 /// OverloadCandidateSet - A set of overload candidates, used in C++
953 /// overload resolution (C++ 13.3).
954 class OverloadCandidateSet {
955 public:
956 enum CandidateSetKind {
957 /// Normal lookup.
958 CSK_Normal,
959
960 /// C++ [over.match.oper]:
961 /// Lookup of operator function candidates in a call using operator
962 /// syntax. Candidates that have no parameters of class type will be
963 /// skipped unless there is a parameter of (reference to) enum type and
964 /// the corresponding argument is of the same enum type.
965 CSK_Operator,
966
967 /// C++ [over.match.copy]:
968 /// Copy-initialization of an object of class type by user-defined
969 /// conversion.
970 CSK_InitByUserDefinedConversion,
971
972 /// C++ [over.match.ctor], [over.match.list]
973 /// Initialization of an object of class type by constructor,
974 /// using either a parenthesized or braced list of arguments.
975 CSK_InitByConstructor,
976 };
977
978 /// Information about operator rewrites to consider when adding operator
979 /// functions to a candidate set.
980 struct OperatorRewriteInfo {
981 OperatorRewriteInfo()
982 : OriginalOperator(OO_None), OpLoc(), AllowRewrittenCandidates(false) {}
983 OperatorRewriteInfo(OverloadedOperatorKind Op, SourceLocation OpLoc,
984 bool AllowRewritten)
985 : OriginalOperator(Op), OpLoc(OpLoc),
986 AllowRewrittenCandidates(AllowRewritten) {}
987
988 /// The original operator as written in the source.
989 OverloadedOperatorKind OriginalOperator;
990 /// The source location of the operator.
991 SourceLocation OpLoc;
992 /// Whether we should include rewritten candidates in the overload set.
993 bool AllowRewrittenCandidates;
994
995 /// Would use of this function result in a rewrite using a different
996 /// operator?
997 bool isRewrittenOperator(const FunctionDecl *FD) {
998 return OriginalOperator &&
999 FD->getDeclName().getCXXOverloadedOperator() != OriginalOperator;
1000 }
1001
1002 bool isAcceptableCandidate(const FunctionDecl *FD) {
1003 if (!OriginalOperator)
1004 return true;
1005
1006 // For an overloaded operator, we can have candidates with a different
1007 // name in our unqualified lookup set. Make sure we only consider the
1008 // ones we're supposed to.
1009 OverloadedOperatorKind OO =
1010 FD->getDeclName().getCXXOverloadedOperator();
1011 return OO && (OO == OriginalOperator ||
1012 (AllowRewrittenCandidates &&
1013 OO == getRewrittenOverloadedOperator(OriginalOperator)));
1014 }
1015
1016 /// Determine the kind of rewrite that should be performed for this
1017 /// candidate.
1018 OverloadCandidateRewriteKind
1019 getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO) {
1020 OverloadCandidateRewriteKind CRK = CRK_None;
1021 if (isRewrittenOperator(FD))
1022 CRK = OverloadCandidateRewriteKind(CRK | CRK_DifferentOperator);
1023 if (PO == OverloadCandidateParamOrder::Reversed)
1024 CRK = OverloadCandidateRewriteKind(CRK | CRK_Reversed);
1025 return CRK;
1026 }
1027 /// Determines whether this operator could be implemented by a function
1028 /// with reversed parameter order.
1029 bool isReversible() {
1030 return AllowRewrittenCandidates && OriginalOperator &&
1031 (getRewrittenOverloadedOperator(OriginalOperator) != OO_None ||
1032 allowsReversed(OriginalOperator));
1033 }
1034
1035 /// Determine whether reversing parameter order is allowed for operator
1036 /// Op.
1037 bool allowsReversed(OverloadedOperatorKind Op);
1038
1039 /// Determine whether we should add a rewritten candidate for \p FD with
1040 /// reversed parameter order.
1041 /// \param OriginalArgs are the original non reversed arguments.
1042 bool shouldAddReversed(Sema &S, ArrayRef<Expr *> OriginalArgs,
1043 FunctionDecl *FD);
1044 };
1045
1046 private:
1047 SmallVector<OverloadCandidate, 16> Candidates;
1048 llvm::SmallPtrSet<uintptr_t, 16> Functions;
1049
1050 // Allocator for ConversionSequenceLists. We store the first few of these
1051 // inline to avoid allocation for small sets.
1052 llvm::BumpPtrAllocator SlabAllocator;
1053
1054 SourceLocation Loc;
1055 CandidateSetKind Kind;
1056 OperatorRewriteInfo RewriteInfo;
1057
1058 constexpr static unsigned NumInlineBytes =
1059 24 * sizeof(ImplicitConversionSequence);
1060 unsigned NumInlineBytesUsed = 0;
1061 alignas(void *) char InlineSpace[NumInlineBytes];
1062
1063 // Address space of the object being constructed.
1064 LangAS DestAS = LangAS::Default;
1065
1066 /// If we have space, allocates from inline storage. Otherwise, allocates
1067 /// from the slab allocator.
1068 /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
1069 /// instead.
1070 /// FIXME: Now that this only allocates ImplicitConversionSequences, do we
1071 /// want to un-generalize this?
1072 template <typename T>
1073 T *slabAllocate(unsigned N) {
1074 // It's simpler if this doesn't need to consider alignment.
1075 static_assert(alignof(T) == alignof(void *),
1076 "Only works for pointer-aligned types.");
1077 static_assert(std::is_trivial<T>::value ||
1078 std::is_same<ImplicitConversionSequence, T>::value,
1079 "Add destruction logic to OverloadCandidateSet::clear().");
1080
1081 unsigned NBytes = sizeof(T) * N;
1082 if (NBytes > NumInlineBytes - NumInlineBytesUsed)
1083 return SlabAllocator.Allocate<T>(N);
1084 char *FreeSpaceStart = InlineSpace + NumInlineBytesUsed;
1085 assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
1086 "Misaligned storage!");
1087
1088 NumInlineBytesUsed += NBytes;
1089 return reinterpret_cast<T *>(FreeSpaceStart);
1090 }
1091
1092 void destroyCandidates();
1093
1094 public:
1095 OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK,
1096 OperatorRewriteInfo RewriteInfo = {})
1097 : Loc(Loc), Kind(CSK), RewriteInfo(RewriteInfo) {}
1098 OverloadCandidateSet(const OverloadCandidateSet &) = delete;
1099 OverloadCandidateSet &operator=(const OverloadCandidateSet &) = delete;
1100 ~OverloadCandidateSet() { destroyCandidates(); }
1101
1102 SourceLocation getLocation() const { return Loc; }
1103 CandidateSetKind getKind() const { return Kind; }
1104 OperatorRewriteInfo getRewriteInfo() const { return RewriteInfo; }
1105
1106 /// Whether diagnostics should be deferred.
1107 bool shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, SourceLocation OpLoc);
1108
1109 /// Determine when this overload candidate will be new to the
1110 /// overload set.
1111 bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO =
1112 OverloadCandidateParamOrder::Normal) {
1113 uintptr_t Key = reinterpret_cast<uintptr_t>(F->getCanonicalDecl());
1114 Key |= static_cast<uintptr_t>(PO);
1115 return Functions.insert(Key).second;
1116 }
1117
1118 /// Exclude a function from being considered by overload resolution.
1119 void exclude(Decl *F) {
1120 isNewCandidate(F, OverloadCandidateParamOrder::Normal);
1121 isNewCandidate(F, OverloadCandidateParamOrder::Reversed);
1122 }
1123
1124 /// Clear out all of the candidates.
1125 void clear(CandidateSetKind CSK);
1126
1127 using iterator = SmallVectorImpl<OverloadCandidate>::iterator;
1128
1129 iterator begin() { return Candidates.begin(); }
1130 iterator end() { return Candidates.end(); }
1131
1132 size_t size() const { return Candidates.size(); }
1133 bool empty() const { return Candidates.empty(); }
1134
1135 /// Allocate storage for conversion sequences for NumConversions
1136 /// conversions.
1137 ConversionSequenceList
1138 allocateConversionSequences(unsigned NumConversions) {
1139 ImplicitConversionSequence *Conversions =
1140 slabAllocate<ImplicitConversionSequence>(NumConversions);
1141
1142 // Construct the new objects.
1143 for (unsigned I = 0; I != NumConversions; ++I)
1144 new (&Conversions[I]) ImplicitConversionSequence();
1145
1146 return ConversionSequenceList(Conversions, NumConversions);
1147 }
1148
1149 /// Add a new candidate with NumConversions conversion sequence slots
1150 /// to the overload set.
1151 OverloadCandidate &
1152 addCandidate(unsigned NumConversions = 0,
1153 ConversionSequenceList Conversions = std::nullopt) {
1154 assert((Conversions.empty() || Conversions.size() == NumConversions) &&
1155 "preallocated conversion sequence has wrong length");
1156
1157 Candidates.push_back(OverloadCandidate());
1158 OverloadCandidate &C = Candidates.back();
1159 C.Conversions = Conversions.empty()
1160 ? allocateConversionSequences(NumConversions)
1161 : Conversions;
1162 return C;
1163 }
1164
1165 /// Find the best viable function on this overload set, if it exists.
1166 OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
1167 OverloadCandidateSet::iterator& Best);
1168
1169 SmallVector<OverloadCandidate *, 32> CompleteCandidates(
1170 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
1171 SourceLocation OpLoc = SourceLocation(),
1172 llvm::function_ref<bool(OverloadCandidate &)> Filter =
1173 [](OverloadCandidate &) { return true; });
1174
1175 void NoteCandidates(
1176 PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD,
1177 ArrayRef<Expr *> Args, StringRef Opc = "",
1178 SourceLocation Loc = SourceLocation(),
1179 llvm::function_ref<bool(OverloadCandidate &)> Filter =
1180 [](OverloadCandidate &) { return true; });
1181
1182 void NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
1183 ArrayRef<OverloadCandidate *> Cands,
1184 StringRef Opc = "",
1185 SourceLocation OpLoc = SourceLocation());
1186
1187 LangAS getDestAS() { return DestAS; }
1188
1189 void setDestAS(LangAS AS) {
1190 assert((Kind == CSK_InitByConstructor ||
1191 Kind == CSK_InitByUserDefinedConversion) &&
1192 "can't set the destination address space when not constructing an "
1193 "object");
1194 DestAS = AS;
1195 }
1196
1197 };
1198
1199 bool isBetterOverloadCandidate(Sema &S,
1200 const OverloadCandidate &Cand1,
1201 const OverloadCandidate &Cand2,
1202 SourceLocation Loc,
1203 OverloadCandidateSet::CandidateSetKind Kind);
1204
1205 struct ConstructorInfo {
1206 DeclAccessPair FoundDecl;
1207 CXXConstructorDecl *Constructor;
1208 FunctionTemplateDecl *ConstructorTmpl;
1209
1210 explicit operator bool() const { return Constructor; }
1211 };
1212
1213 // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
1214 // that takes one of these.
1215 inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
1216 if (isa<UsingDecl>(ND))
1217 return ConstructorInfo{};
1218
1219 // For constructors, the access check is performed against the underlying
1220 // declaration, not the found declaration.
1221 auto *D = ND->getUnderlyingDecl();
1222 ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr,
1223 nullptr};
1224 Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
1225 if (Info.ConstructorTmpl)
1226 D = Info.ConstructorTmpl->getTemplatedDecl();
1227 Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
1228 return Info;
1229 }
1230
1231 // Returns false if signature help is relevant despite number of arguments
1232 // exceeding parameters. Specifically, it returns false when
1233 // PartialOverloading is true and one of the following:
1234 // * Function is variadic
1235 // * Function is template variadic
1236 // * Function is an instantiation of template variadic function
1237 // The last case may seem strange. The idea is that if we added one more
1238 // argument, we'd end up with a function similar to Function. Since, in the
1239 // context of signature help and/or code completion, we do not know what the
1240 // type of the next argument (that the user is typing) will be, this is as
1241 // good candidate as we can get, despite the fact that it takes one less
1242 // parameter.
1243 bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function);
1244
1245} // namespace clang
1246
1247#endif // LLVM_CLANG_SEMA_OVERLOAD_H