1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Sema class, which performs semantic analysis and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Availability.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/LocInfoType.h"
26 #include "clang/AST/MangleNumberingContext.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/ExpressionTraits.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/Module.h"
33 #include "clang/Basic/OpenMPKinds.h"
34 #include "clang/Basic/PragmaKinds.h"
35 #include "clang/Basic/Specifiers.h"
36 #include "clang/Basic/TemplateKinds.h"
37 #include "clang/Basic/TypeTraits.h"
38 #include "clang/Sema/AnalysisBasedWarnings.h"
39 #include "clang/Sema/CleanupInfo.h"
40 #include "clang/Sema/DeclSpec.h"
41 #include "clang/Sema/ExternalSemaSource.h"
42 #include "clang/Sema/IdentifierResolver.h"
43 #include "clang/Sema/ObjCMethodList.h"
44 #include "clang/Sema/Ownership.h"
45 #include "clang/Sema/Scope.h"
46 #include "clang/Sema/ScopeInfo.h"
47 #include "clang/Sema/TypoCorrection.h"
48 #include "clang/Sema/Weak.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/SetVector.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/TinyPtrVector.h"
62 template <typename ValueT> struct DenseMapInfo;
63 template <typename ValueT, typename ValueInfoT> class DenseSet;
65 class InlineAsmIdentifierInfo;
72 class ASTMutationListener;
82 class CXXBindTemporaryExpr;
83 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
84 class CXXConstructorDecl;
85 class CXXConversionDecl;
87 class CXXDestructorDecl;
88 class CXXFieldCollector;
89 class CXXMemberCallExpr;
95 class ClassTemplateDecl;
96 class ClassTemplatePartialSpecializationDecl;
97 class ClassTemplateSpecializationDecl;
98 class VarTemplatePartialSpecializationDecl;
99 class CodeCompleteConsumer;
100 class CodeCompletionAllocator;
101 class CodeCompletionTUInfo;
102 class CodeCompletionResult;
104 class DeclAccessPair;
107 class DeclaratorDecl;
108 class DeducedTemplateArgument;
109 class DependentDiagnostic;
110 class DesignatedInitExpr;
113 class EnumConstantDecl;
119 class FunctionProtoType;
120 class FunctionTemplateDecl;
121 class ImplicitConversionSequence;
123 class InitializationKind;
124 class InitializationSequence;
125 class InitializedEntity;
126 class IntegerLiteral;
130 class LocalInstantiationScope;
133 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
135 class MultiLevelTemplateArgumentList;
137 class ObjCCategoryDecl;
138 class ObjCCategoryImplDecl;
139 class ObjCCompatibleAliasDecl;
140 class ObjCContainerDecl;
142 class ObjCImplementationDecl;
143 class ObjCInterfaceDecl;
145 template <class T> class ObjCList;
146 class ObjCMessageExpr;
147 class ObjCMethodDecl;
148 class ObjCPropertyDecl;
149 class ObjCProtocolDecl;
150 class OMPThreadPrivateDecl;
151 class OMPDeclareReductionDecl;
152 class OMPDeclareSimdDecl;
154 struct OverloadCandidate;
155 class OverloadCandidateSet;
160 class PseudoDestructorTypeStorage;
161 class PseudoObjectExpr;
163 class StandardConversionSequence;
167 class TemplateArgument;
168 class TemplateArgumentList;
169 class TemplateArgumentLoc;
171 class TemplateParameterList;
172 class TemplatePartialOrderingContext;
173 class TemplateTemplateParmDecl;
177 class TypedefNameDecl;
179 class TypoCorrectionConsumer;
181 class UnresolvedLookupExpr;
182 class UnresolvedMemberExpr;
183 class UnresolvedSetImpl;
184 class UnresolvedSetIterator;
186 class UsingShadowDecl;
189 class VarTemplateSpecializationDecl;
190 class VisibilityAttr;
191 class VisibleDeclConsumer;
192 class IndirectFieldDecl;
193 struct DeductionFailureInfo;
194 class TemplateSpecCandidateSet;
197 class AccessedEntity;
198 class BlockScopeInfo;
199 class CapturedRegionScopeInfo;
200 class CapturingScopeInfo;
201 class CompoundScopeInfo;
202 class DelayedDiagnostic;
203 class DelayedDiagnosticPool;
204 class FunctionScopeInfo;
205 class LambdaScopeInfo;
206 class PossiblyUnreachableDiag;
207 class TemplateDeductionInfo;
210 namespace threadSafety {
212 void threadSafetyCleanup(BeforeSet* Cache);
215 // FIXME: No way to easily map from TemplateTypeParmTypes to
216 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
217 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
218 SourceLocation> UnexpandedParameterPack;
220 /// Describes whether we've seen any nullability information for the given
222 struct FileNullability {
223 /// The first pointer declarator (of any pointer kind) in the file that does
224 /// not have a corresponding nullability annotation.
225 SourceLocation PointerLoc;
227 /// Which kind of pointer declarator we saw.
230 /// Whether we saw any type nullability annotations in the given file.
231 bool SawTypeNullability = false;
234 /// A mapping from file IDs to a record of whether we've seen nullability
235 /// information in that file.
236 class FileNullabilityMap {
237 /// A mapping from file IDs to the nullability information for each file ID.
238 llvm::DenseMap<FileID, FileNullability> Map;
240 /// A single-element cache based on the file ID.
243 FileNullability Nullability;
247 FileNullability &operator[](FileID file) {
248 // Check the single-element cache.
249 if (file == Cache.File)
250 return Cache.Nullability;
252 // It's not in the single-element cache; flush the cache if we have one.
253 if (!Cache.File.isInvalid()) {
254 Map[Cache.File] = Cache.Nullability;
257 // Pull this entry into the cache.
259 Cache.Nullability = Map[file];
260 return Cache.Nullability;
264 /// Sema - This implements semantic analysis and AST building for C.
266 Sema(const Sema &) = delete;
267 void operator=(const Sema &) = delete;
269 ///\brief Source of additional semantic information.
270 ExternalSemaSource *ExternalSource;
272 ///\brief Whether Sema has generated a multiplexer and has to delete it.
273 bool isMultiplexExternalSource;
275 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
277 bool isVisibleSlow(const NamedDecl *D);
279 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
280 const NamedDecl *New) {
281 // We are about to link these. It is now safe to compute the linkage of
282 // the new decl. If the new decl has external linkage, we will
283 // link it with the hidden decl (which also has external linkage) and
284 // it will keep having external linkage. If it has internal linkage, we
285 // will not link it. Since it has no previous decls, it will remain
286 // with internal linkage.
287 return isVisible(Old) || New->isExternallyVisible();
289 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
292 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
293 typedef OpaquePtr<TemplateName> TemplateTy;
294 typedef OpaquePtr<QualType> TypeTy;
296 OpenCLOptions OpenCLFeatures;
297 FPOptions FPFeatures;
299 const LangOptions &LangOpts;
302 ASTConsumer &Consumer;
303 DiagnosticsEngine &Diags;
304 SourceManager &SourceMgr;
306 /// \brief Flag indicating whether or not to collect detailed statistics.
309 /// \brief Code-completion consumer.
310 CodeCompleteConsumer *CodeCompleter;
312 /// CurContext - This is the current declaration context of parsing.
313 DeclContext *CurContext;
315 /// \brief Generally null except when we temporarily switch decl contexts,
316 /// like in \see ActOnObjCTemporaryExitContainerContext.
317 DeclContext *OriginalLexicalContext;
319 /// VAListTagName - The declaration name corresponding to __va_list_tag.
320 /// This is used as part of a hack to omit that class from ADL results.
321 DeclarationName VAListTagName;
323 bool MSStructPragmaOn; // True when \#pragma ms_struct on
325 /// \brief Controls member pointer representation format under the MS ABI.
326 LangOptions::PragmaMSPointersToMembersKind
327 MSPointerToMemberRepresentationMethod;
329 /// Stack of active SEH __finally scopes. Can be empty.
330 SmallVector<Scope*, 2> CurrentSEHFinally;
332 /// \brief Source location for newly created implicit MSInheritanceAttrs
333 SourceLocation ImplicitMSInheritanceAttrLoc;
335 enum PragmaMsStackAction {
336 PSK_Reset = 0x0, // #pragma ()
337 PSK_Set = 0x1, // #pragma (value)
338 PSK_Push = 0x2, // #pragma (push[, id])
339 PSK_Pop = 0x4, // #pragma (pop[, id])
340 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
341 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
342 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
345 template<typename ValueType>
348 llvm::StringRef StackSlotLabel;
350 SourceLocation PragmaLocation;
351 Slot(llvm::StringRef StackSlotLabel,
353 SourceLocation PragmaLocation)
354 : StackSlotLabel(StackSlotLabel), Value(Value),
355 PragmaLocation(PragmaLocation) {}
357 void Act(SourceLocation PragmaLocation,
358 PragmaMsStackAction Action,
359 llvm::StringRef StackSlotLabel,
362 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
363 // method body to restore the stacks on exit, so it works like this:
366 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
368 // #pragma <name>(pop, InternalPragmaSlot)
371 // It works even with #pragma vtordisp, although MSVC doesn't support
372 // #pragma vtordisp(push [, id], n)
375 // Push / pop a named sentinel slot.
376 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
377 assert((Action == PSK_Push || Action == PSK_Pop) &&
378 "Can only push / pop #pragma stack sentinels!");
379 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
383 explicit PragmaStack(const ValueType &Default)
384 : DefaultValue(Default), CurrentValue(Default) {}
386 SmallVector<Slot, 2> Stack;
387 ValueType DefaultValue; // Value used for PSK_Reset action.
388 ValueType CurrentValue;
389 SourceLocation CurrentPragmaLocation;
391 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
392 // we shouldn't do so if they're in a module).
394 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
395 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
397 /// 0: Suppress all vtordisps
398 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
400 /// 2: Always insert vtordisps to support RTTI on partially constructed
402 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
404 // Sentinel to represent when the stack is set to mac68k alignment.
405 static const unsigned kMac68kAlignmentSentinel = ~0U;
406 PragmaStack<unsigned> PackStack;
408 PragmaStack<StringLiteral *> DataSegStack;
409 PragmaStack<StringLiteral *> BSSSegStack;
410 PragmaStack<StringLiteral *> ConstSegStack;
411 PragmaStack<StringLiteral *> CodeSegStack;
413 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
414 // Actions should be performed only if we enter / exit a C++ method body.
415 class PragmaStackSentinelRAII {
417 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
418 ~PragmaStackSentinelRAII();
426 /// A mapping that describes the nullability we've seen in each header file.
427 FileNullabilityMap NullabilityMap;
429 /// Last section used with #pragma init_seg.
430 StringLiteral *CurInitSeg;
431 SourceLocation CurInitSegLoc;
433 /// VisContext - Manages the stack for \#pragma GCC visibility.
434 void *VisContext; // Really a "PragmaVisStack*"
436 /// \brief This represents the last location of a "#pragma clang optimize off"
437 /// directive if such a directive has not been closed by an "on" yet. If
438 /// optimizations are currently "on", this is set to an invalid location.
439 SourceLocation OptimizeOffPragmaLocation;
441 /// \brief Flag indicating if Sema is building a recovery call expression.
443 /// This flag is used to avoid building recovery call expressions
444 /// if Sema is already doing so, which would cause infinite recursions.
445 bool IsBuildingRecoveryCallExpr;
447 /// Used to control the generation of ExprWithCleanups.
450 /// ExprCleanupObjects - This is the stack of objects requiring
451 /// cleanup that are created by the current full expression. The
452 /// element type here is ExprWithCleanups::Object.
453 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
455 /// \brief Store a list of either DeclRefExprs or MemberExprs
456 /// that contain a reference to a variable (constant) that may or may not
457 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
458 /// and discarded value conversions have been applied to all subexpressions
459 /// of the enclosing full expression. This is cleared at the end of each
461 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
463 /// \brief Stack containing information about each of the nested
464 /// function, block, and method scopes that are currently active.
466 /// This array is never empty. Clients should ignore the first
467 /// element, which is used to cache a single FunctionScopeInfo
468 /// that's used to parse every top-level function.
469 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
471 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
472 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
475 /// ExtVectorDecls - This is a list all the extended vector types. This allows
476 /// us to associate a raw vector type with one of the ext_vector type names.
477 /// This is only necessary for issuing pretty diagnostics.
478 ExtVectorDeclsType ExtVectorDecls;
480 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
481 std::unique_ptr<CXXFieldCollector> FieldCollector;
483 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
485 /// \brief Set containing all declared private fields that are not used.
486 NamedDeclSetType UnusedPrivateFields;
488 /// \brief Set containing all typedefs that are likely unused.
489 llvm::SmallSetVector<const TypedefNameDecl *, 4>
490 UnusedLocalTypedefNameCandidates;
492 /// \brief Delete-expressions to be analyzed at the end of translation unit
494 /// This list contains class members, and locations of delete-expressions
495 /// that could not be proven as to whether they mismatch with new-expression
496 /// used in initializer of the field.
497 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
498 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
499 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
501 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
503 /// PureVirtualClassDiagSet - a set of class declarations which we have
504 /// emitted a list of pure virtual functions. Used to prevent emitting the
505 /// same list more than once.
506 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
508 /// ParsingInitForAutoVars - a set of declarations with auto types for which
509 /// we are currently parsing the initializer.
510 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
512 /// \brief Look for a locally scoped extern "C" declaration by the given name.
513 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
515 typedef LazyVector<VarDecl *, ExternalSemaSource,
516 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
517 TentativeDefinitionsType;
519 /// \brief All the tentative definitions encountered in the TU.
520 TentativeDefinitionsType TentativeDefinitions;
522 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
523 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
524 UnusedFileScopedDeclsType;
526 /// \brief The set of file scoped decls seen so far that have not been used
527 /// and must warn if not used. Only contains the first declaration.
528 UnusedFileScopedDeclsType UnusedFileScopedDecls;
530 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
531 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
532 DelegatingCtorDeclsType;
534 /// \brief All the delegating constructors seen so far in the file, used for
535 /// cycle detection at the end of the TU.
536 DelegatingCtorDeclsType DelegatingCtorDecls;
538 /// \brief All the overriding functions seen during a class definition
539 /// that had their exception spec checks delayed, plus the overridden
541 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
542 DelayedExceptionSpecChecks;
544 /// \brief All the members seen during a class definition which were both
545 /// explicitly defaulted and had explicitly-specified exception
546 /// specifications, along with the function type containing their
547 /// user-specified exception specification. Those exception specifications
548 /// were overridden with the default specifications, but we still need to
549 /// check whether they are compatible with the default specification, and
550 /// we can't do that until the nesting set of class definitions is complete.
551 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
552 DelayedDefaultedMemberExceptionSpecs;
554 typedef llvm::MapVector<const FunctionDecl *,
555 std::unique_ptr<LateParsedTemplate>>
556 LateParsedTemplateMapT;
557 LateParsedTemplateMapT LateParsedTemplateMap;
559 /// \brief Callback to the parser to parse templated functions when needed.
560 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
561 typedef void LateTemplateParserCleanupCB(void *P);
562 LateTemplateParserCB *LateTemplateParser;
563 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
566 void SetLateTemplateParser(LateTemplateParserCB *LTP,
567 LateTemplateParserCleanupCB *LTPCleanup,
569 LateTemplateParser = LTP;
570 LateTemplateParserCleanup = LTPCleanup;
574 class DelayedDiagnostics;
576 class DelayedDiagnosticsState {
577 sema::DelayedDiagnosticPool *SavedPool;
578 friend class Sema::DelayedDiagnostics;
580 typedef DelayedDiagnosticsState ParsingDeclState;
581 typedef DelayedDiagnosticsState ProcessingContextState;
583 /// A class which encapsulates the logic for delaying diagnostics
584 /// during parsing and other processing.
585 class DelayedDiagnostics {
586 /// \brief The current pool of diagnostics into which delayed
587 /// diagnostics should go.
588 sema::DelayedDiagnosticPool *CurPool;
591 DelayedDiagnostics() : CurPool(nullptr) {}
593 /// Adds a delayed diagnostic.
594 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
596 /// Determines whether diagnostics should be delayed.
597 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
599 /// Returns the current delayed-diagnostics pool.
600 sema::DelayedDiagnosticPool *getCurrentPool() const {
604 /// Enter a new scope. Access and deprecation diagnostics will be
605 /// collected in this pool.
606 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
607 DelayedDiagnosticsState state;
608 state.SavedPool = CurPool;
613 /// Leave a delayed-diagnostic state that was previously pushed.
614 /// Do not emit any of the diagnostics. This is performed as part
615 /// of the bookkeeping of popping a pool "properly".
616 void popWithoutEmitting(DelayedDiagnosticsState state) {
617 CurPool = state.SavedPool;
620 /// Enter a new scope where access and deprecation diagnostics are
622 DelayedDiagnosticsState pushUndelayed() {
623 DelayedDiagnosticsState state;
624 state.SavedPool = CurPool;
629 /// Undo a previous pushUndelayed().
630 void popUndelayed(DelayedDiagnosticsState state) {
631 assert(CurPool == nullptr);
632 CurPool = state.SavedPool;
634 } DelayedDiagnostics;
636 /// A RAII object to temporarily push a declaration context.
640 DeclContext *SavedContext;
641 ProcessingContextState SavedContextState;
642 QualType SavedCXXThisTypeOverride;
645 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
646 : S(S), SavedContext(S.CurContext),
647 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
648 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
650 assert(ContextToPush && "pushing null context");
651 S.CurContext = ContextToPush;
653 S.CXXThisTypeOverride = QualType();
657 if (!SavedContext) return;
658 S.CurContext = SavedContext;
659 S.DelayedDiagnostics.popUndelayed(SavedContextState);
660 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
661 SavedContext = nullptr;
669 /// \brief RAII object to handle the state changes required to synthesize
671 class SynthesizedFunctionScope {
673 Sema::ContextRAII SavedContext;
676 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
677 : S(S), SavedContext(S, DC)
679 S.PushFunctionScope();
680 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
683 ~SynthesizedFunctionScope() {
684 S.PopExpressionEvaluationContext();
685 S.PopFunctionScopeInfo();
689 /// WeakUndeclaredIdentifiers - Identifiers contained in
690 /// \#pragma weak before declared. rare. may alias another
691 /// identifier, declared or undeclared
692 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
694 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
695 /// \#pragma redefine_extname before declared. Used in Solaris system headers
696 /// to define functions that occur in multiple standards to call the version
697 /// in the currently selected standard.
698 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
701 /// \brief Load weak undeclared identifiers from the external source.
702 void LoadExternalWeakUndeclaredIdentifiers();
704 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
705 /// \#pragma weak during processing of other Decls.
706 /// I couldn't figure out a clean way to generate these in-line, so
707 /// we store them here and handle separately -- which is a hack.
708 /// It would be best to refactor this.
709 SmallVector<Decl*,2> WeakTopLevelDecl;
711 IdentifierResolver IdResolver;
713 /// Translation Unit Scope - useful to Objective-C actions that need
714 /// to lookup file scope declarations in the "ordinary" C decl namespace.
715 /// For example, user-defined classes, built-in "id" type, etc.
718 /// \brief The C++ "std" namespace, where the standard library resides.
719 LazyDeclPtr StdNamespace;
721 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
722 /// standard library.
723 LazyDeclPtr StdBadAlloc;
725 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
726 /// standard library.
727 LazyDeclPtr StdAlignValT;
729 /// \brief The C++ "std::experimental" namespace, where the experimental parts
730 /// of the standard library resides.
731 NamespaceDecl *StdExperimentalNamespaceCache;
733 /// \brief The C++ "std::initializer_list" template, which is defined in
734 /// \<initializer_list>.
735 ClassTemplateDecl *StdInitializerList;
737 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
738 RecordDecl *CXXTypeInfoDecl;
740 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
741 RecordDecl *MSVCGuidDecl;
743 /// \brief Caches identifiers/selectors for NSFoundation APIs.
744 std::unique_ptr<NSAPI> NSAPIObj;
746 /// \brief The declaration of the Objective-C NSNumber class.
747 ObjCInterfaceDecl *NSNumberDecl;
749 /// \brief The declaration of the Objective-C NSValue class.
750 ObjCInterfaceDecl *NSValueDecl;
752 /// \brief Pointer to NSNumber type (NSNumber *).
753 QualType NSNumberPointer;
755 /// \brief Pointer to NSValue type (NSValue *).
756 QualType NSValuePointer;
758 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
759 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
761 /// \brief The declaration of the Objective-C NSString class.
762 ObjCInterfaceDecl *NSStringDecl;
764 /// \brief Pointer to NSString type (NSString *).
765 QualType NSStringPointer;
767 /// \brief The declaration of the stringWithUTF8String: method.
768 ObjCMethodDecl *StringWithUTF8StringMethod;
770 /// \brief The declaration of the valueWithBytes:objCType: method.
771 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
773 /// \brief The declaration of the Objective-C NSArray class.
774 ObjCInterfaceDecl *NSArrayDecl;
776 /// \brief The declaration of the arrayWithObjects:count: method.
777 ObjCMethodDecl *ArrayWithObjectsMethod;
779 /// \brief The declaration of the Objective-C NSDictionary class.
780 ObjCInterfaceDecl *NSDictionaryDecl;
782 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
783 ObjCMethodDecl *DictionaryWithObjectsMethod;
785 /// \brief id<NSCopying> type.
786 QualType QIDNSCopying;
788 /// \brief will hold 'respondsToSelector:'
789 Selector RespondsToSelectorSel;
791 /// A flag to remember whether the implicit forms of operator new and delete
792 /// have been declared.
793 bool GlobalNewDeleteDeclared;
795 /// A flag to indicate that we're in a context that permits abstract
796 /// references to fields. This is really a
797 bool AllowAbstractFieldReference;
799 /// \brief Describes how the expressions currently being parsed are
800 /// evaluated at run-time, if at all.
801 enum ExpressionEvaluationContext {
802 /// \brief The current expression and its subexpressions occur within an
803 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
804 /// \c sizeof, where the type of the expression may be significant but
805 /// no code will be generated to evaluate the value of the expression at
809 /// \brief The current expression occurs within a discarded statement.
810 /// This behaves largely similarly to an unevaluated operand in preventing
811 /// definitions from being required, but not in other ways.
814 /// \brief The current expression occurs within an unevaluated
815 /// operand that unconditionally permits abstract references to
816 /// fields, such as a SIZE operator in MS-style inline assembly.
819 /// \brief The current context is "potentially evaluated" in C++11 terms,
820 /// but the expression is evaluated at compile-time (like the values of
821 /// cases in a switch statement).
824 /// \brief The current expression is potentially evaluated at run time,
825 /// which means that code may be generated to evaluate the value of the
826 /// expression at run time.
827 PotentiallyEvaluated,
829 /// \brief The current expression is potentially evaluated, but any
830 /// declarations referenced inside that expression are only used if
831 /// in fact the current expression is used.
833 /// This value is used when parsing default function arguments, for which
834 /// we would like to provide diagnostics (e.g., passing non-POD arguments
835 /// through varargs) but do not want to mark declarations as "referenced"
836 /// until the default argument is used.
837 PotentiallyEvaluatedIfUsed
840 /// \brief Data structure used to record current or nested
841 /// expression evaluation contexts.
842 struct ExpressionEvaluationContextRecord {
843 /// \brief The expression evaluation context.
844 ExpressionEvaluationContext Context;
846 /// \brief Whether the enclosing context needed a cleanup.
847 CleanupInfo ParentCleanup;
849 /// \brief Whether we are in a decltype expression.
852 /// \brief The number of active cleanup objects when we entered
853 /// this expression evaluation context.
854 unsigned NumCleanupObjects;
856 /// \brief The number of typos encountered during this expression evaluation
857 /// context (i.e. the number of TypoExprs created).
860 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
862 /// \brief The lambdas that are present within this context, if it
863 /// is indeed an unevaluated context.
864 SmallVector<LambdaExpr *, 2> Lambdas;
866 /// \brief The declaration that provides context for lambda expressions
867 /// and block literals if the normal declaration context does not
868 /// suffice, e.g., in a default function argument.
869 Decl *ManglingContextDecl;
871 /// \brief The context information used to mangle lambda expressions
872 /// and block literals within this context.
874 /// This mangling information is allocated lazily, since most contexts
875 /// do not have lambda expressions or block literals.
876 std::unique_ptr<MangleNumberingContext> MangleNumbering;
878 /// \brief If we are processing a decltype type, a set of call expressions
879 /// for which we have deferred checking the completeness of the return type.
880 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
882 /// \brief If we are processing a decltype type, a set of temporary binding
883 /// expressions for which we have deferred checking the destructor.
884 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
886 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
887 unsigned NumCleanupObjects,
888 CleanupInfo ParentCleanup,
889 Decl *ManglingContextDecl,
891 : Context(Context), ParentCleanup(ParentCleanup),
892 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
894 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
896 /// \brief Retrieve the mangling numbering context, used to consistently
897 /// number constructs like lambdas for mangling.
898 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
900 bool isUnevaluated() const {
901 return Context == Unevaluated || Context == UnevaluatedAbstract;
905 /// A stack of expression evaluation contexts.
906 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
908 /// \brief Compute the mangling number context for a lambda expression or
911 /// \param DC - The DeclContext containing the lambda expression or
913 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
914 /// associated with the context, if relevant.
915 MangleNumberingContext *getCurrentMangleNumberContext(
916 const DeclContext *DC,
917 Decl *&ManglingContextDecl);
920 /// SpecialMemberOverloadResult - The overloading result for a special member
923 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
924 /// integer are used to determine whether overload resolution succeeded.
925 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
934 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
937 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
938 : FastFoldingSetNode(ID)
941 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
942 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
944 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
945 void setKind(Kind K) { Pair.setInt(K); }
948 /// \brief A cache of special member function overload resolution results
950 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
952 /// \brief A cache of the flags available in enumerations with the flag_bits
954 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
956 /// \brief The kind of translation unit we are processing.
958 /// When we're processing a complete translation unit, Sema will perform
959 /// end-of-translation-unit semantic tasks (such as creating
960 /// initializers for tentative definitions in C) once parsing has
961 /// completed. Modules and precompiled headers perform different kinds of
963 TranslationUnitKind TUKind;
965 llvm::BumpPtrAllocator BumpAlloc;
967 /// \brief The number of SFINAE diagnostics that have been trapped.
968 unsigned NumSFINAEErrors;
970 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
971 UnparsedDefaultArgInstantiationsMap;
973 /// \brief A mapping from parameters with unparsed default arguments to the
974 /// set of instantiations of each parameter.
976 /// This mapping is a temporary data structure used when parsing
977 /// nested class templates or nested classes of class templates,
978 /// where we might end up instantiating an inner class before the
979 /// default arguments of its methods have been parsed.
980 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
982 // Contains the locations of the beginning of unparsed default
983 // argument locations.
984 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
986 /// UndefinedInternals - all the used, undefined objects which require a
987 /// definition in this translation unit.
988 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
990 /// Obtain a sorted list of functions that are undefined but ODR-used.
991 void getUndefinedButUsed(
992 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
994 /// Retrieves list of suspicious delete-expressions that will be checked at
995 /// the end of translation unit.
996 const llvm::MapVector<FieldDecl *, DeleteLocs> &
997 getMismatchingDeleteExpressions() const;
999 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1000 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1002 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1003 /// We need to maintain a list, since selectors can have differing signatures
1004 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1005 /// of selectors are "overloaded").
1006 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1007 /// methods inside categories with a particular selector.
1008 GlobalMethodPool MethodPool;
1010 /// Method selectors used in a \@selector expression. Used for implementation
1012 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1014 /// Kinds of C++ special members.
1015 enum CXXSpecialMember {
1016 CXXDefaultConstructor,
1025 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1027 /// The C++ special members which we are currently in the process of
1028 /// declaring. If this process recursively triggers the declaration of the
1029 /// same special member, we should act as if it is not yet declared.
1030 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1032 void ReadMethodPool(Selector Sel);
1033 void updateOutOfDateSelector(Selector Sel);
1035 /// Private Helper predicate to check for 'self'.
1036 bool isSelfExpr(Expr *RExpr);
1037 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1039 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1040 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1041 /// should not be used elsewhere.
1042 void EmitCurrentDiagnostic(unsigned DiagID);
1044 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1046 class FPContractStateRAII {
1048 FPContractStateRAII(Sema& S)
1049 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1050 ~FPContractStateRAII() {
1051 S.FPFeatures.fp_contract = OldFPContractState;
1055 bool OldFPContractState : 1;
1058 void addImplicitTypedef(StringRef Name, QualType T);
1061 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1062 TranslationUnitKind TUKind = TU_Complete,
1063 CodeCompleteConsumer *CompletionConsumer = nullptr);
1066 /// \brief Perform initialization that occurs after the parser has been
1067 /// initialized but before it parses anything.
1070 const LangOptions &getLangOpts() const { return LangOpts; }
1071 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1072 FPOptions &getFPOptions() { return FPFeatures; }
1074 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1075 SourceManager &getSourceManager() const { return SourceMgr; }
1076 Preprocessor &getPreprocessor() const { return PP; }
1077 ASTContext &getASTContext() const { return Context; }
1078 ASTConsumer &getASTConsumer() const { return Consumer; }
1079 ASTMutationListener *getASTMutationListener() const;
1080 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1082 ///\brief Registers an external source. If an external source already exists,
1083 /// creates a multiplex external source and appends to it.
1085 ///\param[in] E - A non-null external sema source.
1087 void addExternalSource(ExternalSemaSource *E);
1089 void PrintStats() const;
1091 /// \brief Helper class that creates diagnostics with optional
1092 /// template instantiation stacks.
1094 /// This class provides a wrapper around the basic DiagnosticBuilder
1095 /// class that emits diagnostics. SemaDiagnosticBuilder is
1096 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1097 /// does) and, if the diagnostic comes from inside a template
1098 /// instantiation, printing the template instantiation stack as
1100 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1105 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1106 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1108 // This is a cunning lie. DiagnosticBuilder actually performs move
1109 // construction in its copy constructor (but due to varied uses, it's not
1110 // possible to conveniently express this as actual move construction). So
1111 // the default copy ctor here is fine, because the base class disables the
1112 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1113 // in that case anwyay.
1114 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1116 ~SemaDiagnosticBuilder() {
1117 // If we aren't active, there is nothing to do.
1118 if (!isActive()) return;
1120 // Otherwise, we need to emit the diagnostic. First flush the underlying
1121 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1122 // won't emit the diagnostic in its own destructor.
1124 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1125 // do its own needless checks to see if the diagnostic needs to be
1126 // emitted. However, because we take care to ensure that the builder
1127 // objects never escape, a sufficiently smart compiler will be able to
1128 // eliminate that code.
1132 // Dispatch to Sema to emit the diagnostic.
1133 SemaRef.EmitCurrentDiagnostic(DiagID);
1136 /// Teach operator<< to produce an object of the correct type.
1137 template<typename T>
1138 friend const SemaDiagnosticBuilder &operator<<(
1139 const SemaDiagnosticBuilder &Diag, const T &Value) {
1140 const DiagnosticBuilder &BaseDiag = Diag;
1146 /// \brief Emit a diagnostic.
1147 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1148 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1149 return SemaDiagnosticBuilder(DB, *this, DiagID);
1152 /// \brief Emit a partial diagnostic.
1153 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1155 /// \brief Build a partial diagnostic.
1156 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1158 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1160 /// \brief Get a string to suggest for zero-initialization of a type.
1162 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1163 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1165 /// \brief Calls \c Lexer::getLocForEndOfToken()
1166 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1168 /// \brief Retrieve the module loader associated with the preprocessor.
1169 ModuleLoader &getModuleLoader() const;
1171 void emitAndClearUnusedLocalTypedefWarnings();
1173 void ActOnEndOfTranslationUnit();
1175 void CheckDelegatingCtorCycles();
1177 Scope *getScopeForContext(DeclContext *Ctx);
1179 void PushFunctionScope();
1180 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1181 sema::LambdaScopeInfo *PushLambdaScope();
1183 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1184 /// is during Parsing. Currently it is used to pass on the depth
1185 /// when parsing generic lambda 'auto' parameters.
1186 void RecordParsingTemplateParameterDepth(unsigned Depth);
1188 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1190 CapturedRegionKind K);
1192 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1193 const Decl *D = nullptr,
1194 const BlockExpr *blkExpr = nullptr);
1196 sema::FunctionScopeInfo *getCurFunction() const {
1197 return FunctionScopes.back();
1200 sema::FunctionScopeInfo *getEnclosingFunction() const {
1201 if (FunctionScopes.empty())
1204 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1205 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1207 return FunctionScopes[e];
1212 template <typename ExprT>
1213 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1214 if (!isUnevaluatedContext())
1215 getCurFunction()->recordUseOfWeak(E, IsRead);
1218 void PushCompoundScope();
1219 void PopCompoundScope();
1221 sema::CompoundScopeInfo &getCurCompoundScope() const;
1223 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1225 /// \brief Retrieve the current block, if any.
1226 sema::BlockScopeInfo *getCurBlock();
1228 /// Retrieve the current lambda scope info, if any.
1229 /// \param IgnoreCapturedRegions true if should find the top-most lambda scope
1230 /// info ignoring all inner captured regions scope infos.
1231 sema::LambdaScopeInfo *getCurLambda(bool IgnoreCapturedRegions = false);
1233 /// \brief Retrieve the current generic lambda info, if any.
1234 sema::LambdaScopeInfo *getCurGenericLambda();
1236 /// \brief Retrieve the current captured region, if any.
1237 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1239 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1240 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1242 void ActOnComment(SourceRange Comment);
1244 //===--------------------------------------------------------------------===//
1245 // Type Analysis / Processing: SemaType.cpp.
1248 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1249 const DeclSpec *DS = nullptr);
1250 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1251 const DeclSpec *DS = nullptr);
1252 QualType BuildPointerType(QualType T,
1253 SourceLocation Loc, DeclarationName Entity);
1254 QualType BuildReferenceType(QualType T, bool LValueRef,
1255 SourceLocation Loc, DeclarationName Entity);
1256 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1257 Expr *ArraySize, unsigned Quals,
1258 SourceRange Brackets, DeclarationName Entity);
1259 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1260 SourceLocation AttrLoc);
1262 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1264 /// \brief Build a function type.
1266 /// This routine checks the function type according to C++ rules and
1267 /// under the assumption that the result type and parameter types have
1268 /// just been instantiated from a template. It therefore duplicates
1269 /// some of the behavior of GetTypeForDeclarator, but in a much
1270 /// simpler form that is only suitable for this narrow use case.
1272 /// \param T The return type of the function.
1274 /// \param ParamTypes The parameter types of the function. This array
1275 /// will be modified to account for adjustments to the types of the
1276 /// function parameters.
1278 /// \param Loc The location of the entity whose type involves this
1279 /// function type or, if there is no such entity, the location of the
1280 /// type that will have function type.
1282 /// \param Entity The name of the entity that involves the function
1285 /// \param EPI Extra information about the function type. Usually this will
1286 /// be taken from an existing function with the same prototype.
1288 /// \returns A suitable function type, if there are no errors. The
1289 /// unqualified type will always be a FunctionProtoType.
1290 /// Otherwise, returns a NULL type.
1291 QualType BuildFunctionType(QualType T,
1292 MutableArrayRef<QualType> ParamTypes,
1293 SourceLocation Loc, DeclarationName Entity,
1294 const FunctionProtoType::ExtProtoInfo &EPI);
1296 QualType BuildMemberPointerType(QualType T, QualType Class,
1298 DeclarationName Entity);
1299 QualType BuildBlockPointerType(QualType T,
1300 SourceLocation Loc, DeclarationName Entity);
1301 QualType BuildParenType(QualType T);
1302 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1303 QualType BuildReadPipeType(QualType T,
1304 SourceLocation Loc);
1305 QualType BuildWritePipeType(QualType T,
1306 SourceLocation Loc);
1308 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1309 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1310 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1311 TypeSourceInfo *ReturnTypeInfo);
1313 /// \brief Package the given type and TSI into a ParsedType.
1314 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1315 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1316 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1317 static QualType GetTypeFromParser(ParsedType Ty,
1318 TypeSourceInfo **TInfo = nullptr);
1319 CanThrowResult canThrow(const Expr *E);
1320 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1321 const FunctionProtoType *FPT);
1322 void UpdateExceptionSpec(FunctionDecl *FD,
1323 const FunctionProtoType::ExceptionSpecInfo &ESI);
1324 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1325 bool CheckDistantExceptionSpec(QualType T);
1326 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1327 bool CheckEquivalentExceptionSpec(
1328 const FunctionProtoType *Old, SourceLocation OldLoc,
1329 const FunctionProtoType *New, SourceLocation NewLoc);
1330 bool CheckEquivalentExceptionSpec(
1331 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1332 const FunctionProtoType *Old, SourceLocation OldLoc,
1333 const FunctionProtoType *New, SourceLocation NewLoc);
1334 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1335 const PartialDiagnostic &NestedDiagID,
1336 const PartialDiagnostic &NoteID,
1337 const FunctionProtoType *Superset,
1338 SourceLocation SuperLoc,
1339 const FunctionProtoType *Subset,
1340 SourceLocation SubLoc);
1341 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1342 const PartialDiagnostic &NoteID,
1343 const FunctionProtoType *Target,
1344 SourceLocation TargetLoc,
1345 const FunctionProtoType *Source,
1346 SourceLocation SourceLoc);
1348 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1350 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1351 /// in an Objective-C message declaration. Return the appropriate type.
1352 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1354 /// \brief Abstract class used to diagnose incomplete types.
1355 struct TypeDiagnoser {
1358 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1359 virtual ~TypeDiagnoser() {}
1362 static int getPrintable(int I) { return I; }
1363 static unsigned getPrintable(unsigned I) { return I; }
1364 static bool getPrintable(bool B) { return B; }
1365 static const char * getPrintable(const char *S) { return S; }
1366 static StringRef getPrintable(StringRef S) { return S; }
1367 static const std::string &getPrintable(const std::string &S) { return S; }
1368 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1371 static DeclarationName getPrintable(DeclarationName N) { return N; }
1372 static QualType getPrintable(QualType T) { return T; }
1373 static SourceRange getPrintable(SourceRange R) { return R; }
1374 static SourceRange getPrintable(SourceLocation L) { return L; }
1375 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1376 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1378 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1380 std::tuple<const Ts &...> Args;
1382 template <std::size_t... Is>
1383 void emit(const SemaDiagnosticBuilder &DB,
1384 llvm::index_sequence<Is...>) const {
1385 // Apply all tuple elements to the builder in order.
1386 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1391 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1392 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1393 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1396 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1397 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1398 emit(DB, llvm::index_sequence_for<Ts...>());
1404 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1405 TypeDiagnoser *Diagnoser);
1407 struct ModuleScope {
1408 clang::Module *Module;
1409 VisibleModuleSet OuterVisibleModules;
1411 /// The modules we're currently parsing.
1412 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1414 VisibleModuleSet VisibleModules;
1416 Module *CachedFakeTopLevelModule;
1419 /// \brief Get the module owning an entity.
1420 Module *getOwningModule(Decl *Entity);
1422 /// \brief Make a merged definition of an existing hidden definition \p ND
1423 /// visible at the specified location.
1424 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1426 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1428 /// Determine whether a declaration is visible to name lookup.
1429 bool isVisible(const NamedDecl *D) {
1430 return !D->isHidden() || isVisibleSlow(D);
1433 /// Determine whether any declaration of an entity is visible.
1435 hasVisibleDeclaration(const NamedDecl *D,
1436 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1437 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1439 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1440 llvm::SmallVectorImpl<Module *> *Modules);
1442 bool hasVisibleMergedDefinition(NamedDecl *Def);
1444 /// Determine if \p D has a visible definition. If not, suggest a declaration
1445 /// that should be made visible to expose the definition.
1446 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1447 bool OnlyNeedComplete = false);
1448 bool hasVisibleDefinition(const NamedDecl *D) {
1450 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1453 /// Determine if the template parameter \p D has a visible default argument.
1455 hasVisibleDefaultArgument(const NamedDecl *D,
1456 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1458 /// Determine if there is a visible declaration of \p D that is a member
1459 /// specialization declaration (as opposed to an instantiated declaration).
1460 bool hasVisibleMemberSpecialization(
1461 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1463 /// Determine if \p A and \p B are equivalent internal linkage declarations
1464 /// from different modules, and thus an ambiguity error can be downgraded to
1465 /// an extension warning.
1466 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1467 const NamedDecl *B);
1468 void diagnoseEquivalentInternalLinkageDeclarations(
1469 SourceLocation Loc, const NamedDecl *D,
1470 ArrayRef<const NamedDecl *> Equiv);
1472 bool isCompleteType(SourceLocation Loc, QualType T) {
1473 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1475 bool RequireCompleteType(SourceLocation Loc, QualType T,
1476 TypeDiagnoser &Diagnoser);
1477 bool RequireCompleteType(SourceLocation Loc, QualType T,
1480 template <typename... Ts>
1481 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1482 const Ts &...Args) {
1483 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1484 return RequireCompleteType(Loc, T, Diagnoser);
1487 void completeExprArrayBound(Expr *E);
1488 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1489 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1491 template <typename... Ts>
1492 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1493 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1494 return RequireCompleteExprType(E, Diagnoser);
1497 bool RequireLiteralType(SourceLocation Loc, QualType T,
1498 TypeDiagnoser &Diagnoser);
1499 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1501 template <typename... Ts>
1502 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1503 const Ts &...Args) {
1504 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1505 return RequireLiteralType(Loc, T, Diagnoser);
1508 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1509 const CXXScopeSpec &SS, QualType T);
1511 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1512 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1513 /// context, such as when building a type for decltype(auto).
1514 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1515 bool AsUnevaluated = true);
1516 QualType BuildUnaryTransformType(QualType BaseType,
1517 UnaryTransformType::UTTKind UKind,
1518 SourceLocation Loc);
1520 //===--------------------------------------------------------------------===//
1521 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1524 struct SkipBodyInfo {
1525 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1527 NamedDecl *Previous;
1530 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1532 void DiagnoseUseOfUnimplementedSelectors();
1534 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1536 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1537 Scope *S, CXXScopeSpec *SS = nullptr,
1538 bool isClassName = false, bool HasTrailingDot = false,
1539 ParsedType ObjectType = nullptr,
1540 bool IsCtorOrDtorName = false,
1541 bool WantNontrivialTypeSourceInfo = false,
1542 IdentifierInfo **CorrectedII = nullptr);
1543 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1544 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1545 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1546 SourceLocation IILoc,
1549 ParsedType &SuggestedType,
1550 bool AllowClassTemplates = false);
1552 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1553 /// type name has failed in a dependent context. In these situations, we
1554 /// automatically form a DependentTypeName that will retry lookup in a related
1555 /// scope during instantiation.
1556 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1557 SourceLocation NameLoc,
1558 bool IsTemplateTypeArg);
1560 /// \brief Describes the result of the name lookup and resolution performed
1561 /// by \c ClassifyName().
1562 enum NameClassificationKind {
1568 NC_NestedNameSpecifier,
1574 class NameClassification {
1575 NameClassificationKind Kind;
1577 TemplateName Template;
1579 const IdentifierInfo *Keyword;
1581 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1584 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1586 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1588 NameClassification(const IdentifierInfo *Keyword)
1589 : Kind(NC_Keyword), Keyword(Keyword) { }
1591 static NameClassification Error() {
1592 return NameClassification(NC_Error);
1595 static NameClassification Unknown() {
1596 return NameClassification(NC_Unknown);
1599 static NameClassification NestedNameSpecifier() {
1600 return NameClassification(NC_NestedNameSpecifier);
1603 static NameClassification TypeTemplate(TemplateName Name) {
1604 NameClassification Result(NC_TypeTemplate);
1605 Result.Template = Name;
1609 static NameClassification VarTemplate(TemplateName Name) {
1610 NameClassification Result(NC_VarTemplate);
1611 Result.Template = Name;
1615 static NameClassification FunctionTemplate(TemplateName Name) {
1616 NameClassification Result(NC_FunctionTemplate);
1617 Result.Template = Name;
1621 NameClassificationKind getKind() const { return Kind; }
1623 ParsedType getType() const {
1624 assert(Kind == NC_Type);
1628 ExprResult getExpression() const {
1629 assert(Kind == NC_Expression);
1633 TemplateName getTemplateName() const {
1634 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1635 Kind == NC_VarTemplate);
1639 TemplateNameKind getTemplateNameKind() const {
1641 case NC_TypeTemplate:
1642 return TNK_Type_template;
1643 case NC_FunctionTemplate:
1644 return TNK_Function_template;
1645 case NC_VarTemplate:
1646 return TNK_Var_template;
1648 llvm_unreachable("unsupported name classification.");
1653 /// \brief Perform name lookup on the given name, classifying it based on
1654 /// the results of name lookup and the following token.
1656 /// This routine is used by the parser to resolve identifiers and help direct
1657 /// parsing. When the identifier cannot be found, this routine will attempt
1658 /// to correct the typo and classify based on the resulting name.
1660 /// \param S The scope in which we're performing name lookup.
1662 /// \param SS The nested-name-specifier that precedes the name.
1664 /// \param Name The identifier. If typo correction finds an alternative name,
1665 /// this pointer parameter will be updated accordingly.
1667 /// \param NameLoc The location of the identifier.
1669 /// \param NextToken The token following the identifier. Used to help
1670 /// disambiguate the name.
1672 /// \param IsAddressOfOperand True if this name is the operand of a unary
1673 /// address of ('&') expression, assuming it is classified as an
1676 /// \param CCC The correction callback, if typo correction is desired.
1678 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1679 SourceLocation NameLoc, const Token &NextToken,
1680 bool IsAddressOfOperand,
1681 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1683 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1685 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1686 MultiTemplateParamsArg TemplateParameterLists);
1687 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1688 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1689 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1690 DeclarationName Name,
1691 SourceLocation Loc);
1693 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1694 SourceLocation FallbackLoc,
1695 SourceLocation ConstQualLoc = SourceLocation(),
1696 SourceLocation VolatileQualLoc = SourceLocation(),
1697 SourceLocation RestrictQualLoc = SourceLocation(),
1698 SourceLocation AtomicQualLoc = SourceLocation(),
1699 SourceLocation UnalignedQualLoc = SourceLocation());
1701 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1702 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1703 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1704 void CheckShadow(Scope *S, VarDecl *D);
1706 /// Warn if 'E', which is an expression that is about to be modified, refers
1707 /// to a shadowing declaration.
1708 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1710 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1713 /// Map of current shadowing declarations to shadowed declarations. Warn if
1714 /// it looks like the user is trying to modify the shadowing declaration.
1715 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1718 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1719 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1720 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1721 TypedefNameDecl *NewTD);
1722 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1723 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1724 TypeSourceInfo *TInfo,
1725 LookupResult &Previous);
1726 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1727 LookupResult &Previous, bool &Redeclaration);
1728 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1729 TypeSourceInfo *TInfo,
1730 LookupResult &Previous,
1731 MultiTemplateParamsArg TemplateParamLists,
1733 ArrayRef<BindingDecl *> Bindings = None);
1735 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1736 MultiTemplateParamsArg TemplateParamLists);
1737 // Returns true if the variable declaration is a redeclaration
1738 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1739 void CheckVariableDeclarationType(VarDecl *NewVD);
1740 void CheckCompleteVariableDeclaration(VarDecl *VD);
1741 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1742 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1744 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1745 TypeSourceInfo *TInfo,
1746 LookupResult &Previous,
1747 MultiTemplateParamsArg TemplateParamLists,
1749 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1751 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1752 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1754 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1755 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1756 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1757 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1758 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1759 // Returns true if the function declaration is a redeclaration
1760 bool CheckFunctionDeclaration(Scope *S,
1761 FunctionDecl *NewFD, LookupResult &Previous,
1762 bool IsExplicitSpecialization);
1763 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1764 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1765 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1766 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1767 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1770 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1771 SourceLocation NameLoc, IdentifierInfo *Name,
1772 QualType T, TypeSourceInfo *TSInfo,
1774 void ActOnParamDefaultArgument(Decl *param,
1775 SourceLocation EqualLoc,
1777 void ActOnParamUnparsedDefaultArgument(Decl *param,
1778 SourceLocation EqualLoc,
1779 SourceLocation ArgLoc);
1780 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1781 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1782 SourceLocation EqualLoc);
1784 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1785 bool TypeMayContainAuto);
1786 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1787 void ActOnInitializerError(Decl *Dcl);
1788 bool canInitializeWithParenthesizedList(QualType TargetType);
1790 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1791 void ActOnCXXForRangeDecl(Decl *D);
1792 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1793 IdentifierInfo *Ident,
1794 ParsedAttributes &Attrs,
1795 SourceLocation AttrEnd);
1796 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1797 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1798 void FinalizeDeclaration(Decl *D);
1799 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1800 ArrayRef<Decl *> Group);
1801 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1802 bool TypeMayContainAuto = true);
1804 /// Should be called on all declarations that might have attached
1805 /// documentation comments.
1806 void ActOnDocumentableDecl(Decl *D);
1807 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1809 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1810 SourceLocation LocAfterDecls);
1811 void CheckForFunctionRedefinition(
1812 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1813 SkipBodyInfo *SkipBody = nullptr);
1814 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1815 MultiTemplateParamsArg TemplateParamLists,
1816 SkipBodyInfo *SkipBody = nullptr);
1817 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1818 SkipBodyInfo *SkipBody = nullptr);
1819 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1820 bool isObjCMethodDecl(Decl *D) {
1821 return D && isa<ObjCMethodDecl>(D);
1824 /// \brief Determine whether we can delay parsing the body of a function or
1825 /// function template until it is used, assuming we don't care about emitting
1826 /// code for that function.
1828 /// This will be \c false if we may need the body of the function in the
1829 /// middle of parsing an expression (where it's impractical to switch to
1830 /// parsing a different function), for instance, if it's constexpr in C++11
1831 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1832 bool canDelayFunctionBody(const Declarator &D);
1834 /// \brief Determine whether we can skip parsing the body of a function
1835 /// definition, assuming we don't care about analyzing its body or emitting
1836 /// code for that function.
1838 /// This will be \c false only if we may need the body of the function in
1839 /// order to parse the rest of the program (for instance, if it is
1840 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1841 bool canSkipFunctionBody(Decl *D);
1843 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1844 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1845 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1846 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1847 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1849 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1850 /// attribute for which parsing is delayed.
1851 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1853 /// \brief Diagnose any unused parameters in the given sequence of
1854 /// ParmVarDecl pointers.
1855 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1857 /// \brief Diagnose whether the size of parameters or return value of a
1858 /// function or obj-c method definition is pass-by-value and larger than a
1859 /// specified threshold.
1861 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1862 QualType ReturnTy, NamedDecl *D);
1864 void DiagnoseInvalidJumps(Stmt *Body);
1865 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1866 SourceLocation AsmLoc,
1867 SourceLocation RParenLoc);
1869 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1870 Decl *ActOnEmptyDeclaration(Scope *S,
1871 AttributeList *AttrList,
1872 SourceLocation SemiLoc);
1874 enum class ModuleDeclKind {
1875 Module, ///< 'module X;'
1876 Partition, ///< 'module partition X;'
1877 Implementation, ///< 'module implementation X;'
1880 /// The parser has processed a module-declaration that begins the definition
1881 /// of a module interface or implementation.
1882 DeclGroupPtrTy ActOnModuleDecl(SourceLocation ModuleLoc, ModuleDeclKind MDK,
1885 /// \brief The parser has processed a module import declaration.
1887 /// \param AtLoc The location of the '@' symbol, if any.
1889 /// \param ImportLoc The location of the 'import' keyword.
1891 /// \param Path The module access path.
1892 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1895 /// \brief The parser has processed a module import translated from a
1896 /// #include or similar preprocessing directive.
1897 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1898 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1900 /// \brief The parsed has entered a submodule.
1901 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1902 /// \brief The parser has left a submodule.
1903 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1905 /// \brief Create an implicit import of the given module at the given
1906 /// source location, for error recovery, if possible.
1908 /// This routine is typically used when an entity found by name lookup
1909 /// is actually hidden within a module that we know about but the user
1910 /// has forgotten to import.
1911 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1914 /// Kinds of missing import. Note, the values of these enumerators correspond
1915 /// to %select values in diagnostics.
1916 enum class MissingImportKind {
1920 ExplicitSpecialization,
1921 PartialSpecialization
1924 /// \brief Diagnose that the specified declaration needs to be visible but
1925 /// isn't, and suggest a module import that would resolve the problem.
1926 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1927 MissingImportKind MIK, bool Recover = true);
1928 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1929 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1930 MissingImportKind MIK, bool Recover);
1932 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1933 SourceLocation LBraceLoc);
1934 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1935 SourceLocation RBraceLoc);
1937 /// \brief We've found a use of a templated declaration that would trigger an
1938 /// implicit instantiation. Check that any relevant explicit specializations
1939 /// and partial specializations are visible, and diagnose if not.
1940 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1942 /// \brief We've found a use of a template specialization that would select a
1943 /// partial specialization. Check that the partial specialization is visible,
1944 /// and diagnose if not.
1945 void checkPartialSpecializationVisibility(SourceLocation Loc,
1948 /// \brief Retrieve a suitable printing policy.
1949 PrintingPolicy getPrintingPolicy() const {
1950 return getPrintingPolicy(Context, PP);
1953 /// \brief Retrieve a suitable printing policy.
1954 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1955 const Preprocessor &PP);
1958 void ActOnPopScope(SourceLocation Loc, Scope *S);
1959 void ActOnTranslationUnitScope(Scope *S);
1961 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1962 RecordDecl *&AnonRecord);
1963 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1964 MultiTemplateParamsArg TemplateParams,
1965 bool IsExplicitInstantiation,
1966 RecordDecl *&AnonRecord);
1968 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1971 const PrintingPolicy &Policy);
1973 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1974 RecordDecl *Record);
1976 /// Common ways to introduce type names without a tag for use in diagnostics.
1977 /// Keep in sync with err_tag_reference_non_tag.
1986 NTK_TypeAliasTemplate,
1987 NTK_TemplateTemplateArgument,
1990 /// Given a non-tag type declaration, returns an enum useful for indicating
1991 /// what kind of non-tag type this is.
1992 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
1994 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1995 TagTypeKind NewTag, bool isDefinition,
1996 SourceLocation NewTagLoc,
1997 const IdentifierInfo *Name);
2000 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2001 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2002 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2003 TUK_Friend // Friend declaration: 'friend struct foo;'
2006 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2007 SourceLocation KWLoc, CXXScopeSpec &SS,
2008 IdentifierInfo *Name, SourceLocation NameLoc,
2009 AttributeList *Attr, AccessSpecifier AS,
2010 SourceLocation ModulePrivateLoc,
2011 MultiTemplateParamsArg TemplateParameterLists,
2012 bool &OwnedDecl, bool &IsDependent,
2013 SourceLocation ScopedEnumKWLoc,
2014 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2015 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2017 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2018 unsigned TagSpec, SourceLocation TagLoc,
2020 IdentifierInfo *Name, SourceLocation NameLoc,
2021 AttributeList *Attr,
2022 MultiTemplateParamsArg TempParamLists);
2024 TypeResult ActOnDependentTag(Scope *S,
2027 const CXXScopeSpec &SS,
2028 IdentifierInfo *Name,
2029 SourceLocation TagLoc,
2030 SourceLocation NameLoc);
2032 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2033 IdentifierInfo *ClassName,
2034 SmallVectorImpl<Decl *> &Decls);
2035 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2036 Declarator &D, Expr *BitfieldWidth);
2038 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2039 Declarator &D, Expr *BitfieldWidth,
2040 InClassInitStyle InitStyle,
2041 AccessSpecifier AS);
2042 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2043 SourceLocation DeclStart,
2044 Declarator &D, Expr *BitfieldWidth,
2045 InClassInitStyle InitStyle,
2047 AttributeList *MSPropertyAttr);
2049 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2050 TypeSourceInfo *TInfo,
2051 RecordDecl *Record, SourceLocation Loc,
2052 bool Mutable, Expr *BitfieldWidth,
2053 InClassInitStyle InitStyle,
2054 SourceLocation TSSL,
2055 AccessSpecifier AS, NamedDecl *PrevDecl,
2056 Declarator *D = nullptr);
2058 bool CheckNontrivialField(FieldDecl *FD);
2059 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2060 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2061 bool Diagnose = false);
2062 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2063 void ActOnLastBitfield(SourceLocation DeclStart,
2064 SmallVectorImpl<Decl *> &AllIvarDecls);
2065 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2066 Declarator &D, Expr *BitfieldWidth,
2067 tok::ObjCKeywordKind visibility);
2069 // This is used for both record definitions and ObjC interface declarations.
2070 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2071 ArrayRef<Decl *> Fields,
2072 SourceLocation LBrac, SourceLocation RBrac,
2073 AttributeList *AttrList);
2075 /// ActOnTagStartDefinition - Invoked when we have entered the
2076 /// scope of a tag's definition (e.g., for an enumeration, class,
2077 /// struct, or union).
2078 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2080 typedef void *SkippedDefinitionContext;
2082 /// \brief Invoked when we enter a tag definition that we're skipping.
2083 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2085 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2087 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2088 /// C++ record definition's base-specifiers clause and are starting its
2089 /// member declarations.
2090 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2091 SourceLocation FinalLoc,
2092 bool IsFinalSpelledSealed,
2093 SourceLocation LBraceLoc);
2095 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2096 /// the definition of a tag (enumeration, class, struct, or union).
2097 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2098 SourceRange BraceRange);
2100 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2102 void ActOnObjCContainerFinishDefinition();
2104 /// \brief Invoked when we must temporarily exit the objective-c container
2105 /// scope for parsing/looking-up C constructs.
2107 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2108 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2109 void ActOnObjCReenterContainerContext(DeclContext *DC);
2111 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2112 /// error parsing the definition of a tag.
2113 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2115 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2116 EnumConstantDecl *LastEnumConst,
2117 SourceLocation IdLoc,
2120 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2121 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2122 QualType EnumUnderlyingTy,
2123 bool EnumUnderlyingIsImplicit,
2124 const EnumDecl *Prev);
2126 /// Determine whether the body of an anonymous enumeration should be skipped.
2127 /// \param II The name of the first enumerator.
2128 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2129 SourceLocation IILoc);
2131 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2132 SourceLocation IdLoc, IdentifierInfo *Id,
2133 AttributeList *Attrs,
2134 SourceLocation EqualLoc, Expr *Val);
2135 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2137 ArrayRef<Decl *> Elements,
2138 Scope *S, AttributeList *Attr);
2140 DeclContext *getContainingDC(DeclContext *DC);
2142 /// Set the current declaration context until it gets popped.
2143 void PushDeclContext(Scope *S, DeclContext *DC);
2144 void PopDeclContext();
2146 /// EnterDeclaratorContext - Used when we must lookup names in the context
2147 /// of a declarator's nested name specifier.
2148 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2149 void ExitDeclaratorContext(Scope *S);
2151 /// Push the parameters of D, which must be a function, into scope.
2152 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2153 void ActOnExitFunctionContext();
2155 DeclContext *getFunctionLevelDeclContext();
2157 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2158 /// to the function decl for the function being parsed. If we're currently
2159 /// in a 'block', this returns the containing context.
2160 FunctionDecl *getCurFunctionDecl();
2162 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2163 /// the method decl for the method being parsed. If we're currently
2164 /// in a 'block', this returns the containing context.
2165 ObjCMethodDecl *getCurMethodDecl();
2167 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2168 /// or C function we're in, otherwise return null. If we're currently
2169 /// in a 'block', this returns the containing context.
2170 NamedDecl *getCurFunctionOrMethodDecl();
2172 /// Add this decl to the scope shadowed decl chains.
2173 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2175 /// \brief Make the given externally-produced declaration visible at the
2176 /// top level scope.
2178 /// \param D The externally-produced declaration to push.
2180 /// \param Name The name of the externally-produced declaration.
2181 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2183 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2184 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2185 /// true if 'D' belongs to the given declaration context.
2187 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2188 /// enclosing namespace set of the context, rather than contained
2189 /// directly within it.
2190 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2191 bool AllowInlineNamespace = false);
2193 /// Finds the scope corresponding to the given decl context, if it
2194 /// happens to be an enclosing scope. Otherwise return NULL.
2195 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2197 /// Subroutines of ActOnDeclarator().
2198 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2199 TypeSourceInfo *TInfo);
2200 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2202 /// \brief Describes the kind of merge to perform for availability
2203 /// attributes (including "deprecated", "unavailable", and "availability").
2204 enum AvailabilityMergeKind {
2205 /// \brief Don't merge availability attributes at all.
2207 /// \brief Merge availability attributes for a redeclaration, which requires
2210 /// \brief Merge availability attributes for an override, which requires
2211 /// an exact match or a weakening of constraints.
2213 /// \brief Merge availability attributes for an implementation of
2214 /// a protocol requirement.
2215 AMK_ProtocolImplementation,
2218 /// Attribute merging methods. Return true if a new attribute was added.
2219 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2220 IdentifierInfo *Platform,
2222 VersionTuple Introduced,
2223 VersionTuple Deprecated,
2224 VersionTuple Obsoleted,
2227 bool IsStrict, StringRef Replacement,
2228 AvailabilityMergeKind AMK,
2229 unsigned AttrSpellingListIndex);
2230 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2231 TypeVisibilityAttr::VisibilityType Vis,
2232 unsigned AttrSpellingListIndex);
2233 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2234 VisibilityAttr::VisibilityType Vis,
2235 unsigned AttrSpellingListIndex);
2236 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2237 unsigned AttrSpellingListIndex, StringRef Uuid);
2238 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2239 unsigned AttrSpellingListIndex);
2240 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2241 unsigned AttrSpellingListIndex);
2243 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2244 unsigned AttrSpellingListIndex,
2245 MSInheritanceAttr::Spelling SemanticSpelling);
2246 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2247 IdentifierInfo *Format, int FormatIdx,
2248 int FirstArg, unsigned AttrSpellingListIndex);
2249 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2250 unsigned AttrSpellingListIndex);
2251 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2252 IdentifierInfo *Ident,
2253 unsigned AttrSpellingListIndex);
2254 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2255 unsigned AttrSpellingListIndex);
2256 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2257 unsigned AttrSpellingListIndex);
2258 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2259 IdentifierInfo *Ident,
2260 unsigned AttrSpellingListIndex);
2261 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2262 unsigned AttrSpellingListIndex);
2264 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2265 AvailabilityMergeKind AMK = AMK_Redeclaration);
2266 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2267 LookupResult &OldDecls);
2268 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2269 bool MergeTypeWithOld);
2270 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2271 Scope *S, bool MergeTypeWithOld);
2272 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2273 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2274 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2275 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2276 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2277 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2279 // AssignmentAction - This is used by all the assignment diagnostic functions
2280 // to represent what is actually causing the operation
2281 enum AssignmentAction {
2289 AA_Passing_CFAudited
2292 /// C++ Overloading.
2294 /// This is a legitimate overload: the existing declarations are
2295 /// functions or function templates with different signatures.
2298 /// This is not an overload because the signature exactly matches
2299 /// an existing declaration.
2302 /// This is not an overload because the lookup results contain a
2306 OverloadKind CheckOverload(Scope *S,
2308 const LookupResult &OldDecls,
2309 NamedDecl *&OldDecl,
2310 bool IsForUsingDecl);
2311 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2312 bool ConsiderCudaAttrs = true);
2314 /// \brief Checks availability of the function depending on the current
2315 /// function context.Inside an unavailable function,unavailability is ignored.
2317 /// \returns true if \p FD is unavailable and current context is inside
2318 /// an available function, false otherwise.
2319 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2321 ImplicitConversionSequence
2322 TryImplicitConversion(Expr *From, QualType ToType,
2323 bool SuppressUserConversions,
2325 bool InOverloadResolution,
2327 bool AllowObjCWritebackConversion);
2329 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2330 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2331 bool IsComplexPromotion(QualType FromType, QualType ToType);
2332 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2333 bool InOverloadResolution,
2334 QualType& ConvertedType, bool &IncompatibleObjC);
2335 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2336 QualType& ConvertedType, bool &IncompatibleObjC);
2337 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2338 QualType &ConvertedType);
2339 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2340 QualType& ConvertedType);
2341 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2342 const FunctionProtoType *NewType,
2343 unsigned *ArgPos = nullptr);
2344 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2345 QualType FromType, QualType ToType);
2347 void maybeExtendBlockObject(ExprResult &E);
2348 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2349 bool CheckPointerConversion(Expr *From, QualType ToType,
2351 CXXCastPath& BasePath,
2352 bool IgnoreBaseAccess,
2353 bool Diagnose = true);
2354 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2355 bool InOverloadResolution,
2356 QualType &ConvertedType);
2357 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2359 CXXCastPath &BasePath,
2360 bool IgnoreBaseAccess);
2361 bool IsQualificationConversion(QualType FromType, QualType ToType,
2362 bool CStyle, bool &ObjCLifetimeConversion);
2363 bool IsFunctionConversion(QualType FromType, QualType ToType,
2364 QualType &ResultTy);
2365 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2366 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2368 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2369 const VarDecl *NRVOCandidate,
2370 QualType ResultType,
2372 bool AllowNRVO = true);
2374 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2376 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2377 SourceLocation EqualLoc,
2379 bool TopLevelOfInitList = false,
2380 bool AllowExplicit = false);
2381 ExprResult PerformObjectArgumentInitialization(Expr *From,
2382 NestedNameSpecifier *Qualifier,
2383 NamedDecl *FoundDecl,
2384 CXXMethodDecl *Method);
2386 ExprResult PerformContextuallyConvertToBool(Expr *From);
2387 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2389 /// Contexts in which a converted constant expression is required.
2391 CCEK_CaseValue, ///< Expression in a case label.
2392 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2393 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2394 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2395 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2397 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2398 llvm::APSInt &Value, CCEKind CCE);
2399 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2400 APValue &Value, CCEKind CCE);
2402 /// \brief Abstract base class used to perform a contextual implicit
2403 /// conversion from an expression to any type passing a filter.
2404 class ContextualImplicitConverter {
2407 bool SuppressConversion;
2409 ContextualImplicitConverter(bool Suppress = false,
2410 bool SuppressConversion = false)
2411 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2413 /// \brief Determine whether the specified type is a valid destination type
2414 /// for this conversion.
2415 virtual bool match(QualType T) = 0;
2417 /// \brief Emits a diagnostic complaining that the expression does not have
2418 /// integral or enumeration type.
2419 virtual SemaDiagnosticBuilder
2420 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2422 /// \brief Emits a diagnostic when the expression has incomplete class type.
2423 virtual SemaDiagnosticBuilder
2424 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2426 /// \brief Emits a diagnostic when the only matching conversion function
2428 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2429 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2431 /// \brief Emits a note for the explicit conversion function.
2432 virtual SemaDiagnosticBuilder
2433 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2435 /// \brief Emits a diagnostic when there are multiple possible conversion
2437 virtual SemaDiagnosticBuilder
2438 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2440 /// \brief Emits a note for one of the candidate conversions.
2441 virtual SemaDiagnosticBuilder
2442 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2444 /// \brief Emits a diagnostic when we picked a conversion function
2445 /// (for cases when we are not allowed to pick a conversion function).
2446 virtual SemaDiagnosticBuilder diagnoseConversion(
2447 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2449 virtual ~ContextualImplicitConverter() {}
2452 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2453 bool AllowScopedEnumerations;
2456 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2457 bool Suppress, bool SuppressConversion)
2458 : ContextualImplicitConverter(Suppress, SuppressConversion),
2459 AllowScopedEnumerations(AllowScopedEnumerations) {}
2461 /// Match an integral or (possibly scoped) enumeration type.
2462 bool match(QualType T) override;
2464 SemaDiagnosticBuilder
2465 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2466 return diagnoseNotInt(S, Loc, T);
2469 /// \brief Emits a diagnostic complaining that the expression does not have
2470 /// integral or enumeration type.
2471 virtual SemaDiagnosticBuilder
2472 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2475 /// Perform a contextual implicit conversion.
2476 ExprResult PerformContextualImplicitConversion(
2477 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2480 enum ObjCSubscriptKind {
2485 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2487 // Note that LK_String is intentionally after the other literals, as
2488 // this is used for diagnostics logic.
2489 enum ObjCLiteralKind {
2498 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2500 ExprResult PerformObjectMemberConversion(Expr *From,
2501 NestedNameSpecifier *Qualifier,
2502 NamedDecl *FoundDecl,
2505 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2506 // TODO: make this is a typesafe union.
2507 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2508 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2510 void AddOverloadCandidate(FunctionDecl *Function,
2511 DeclAccessPair FoundDecl,
2512 ArrayRef<Expr *> Args,
2513 OverloadCandidateSet& CandidateSet,
2514 bool SuppressUserConversions = false,
2515 bool PartialOverloading = false,
2516 bool AllowExplicit = false);
2517 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2518 ArrayRef<Expr *> Args,
2519 OverloadCandidateSet &CandidateSet,
2520 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2521 bool SuppressUserConversions = false,
2522 bool PartialOverloading = false);
2523 void AddMethodCandidate(DeclAccessPair FoundDecl,
2524 QualType ObjectType,
2525 Expr::Classification ObjectClassification,
2526 ArrayRef<Expr *> Args,
2527 OverloadCandidateSet& CandidateSet,
2528 bool SuppressUserConversion = false);
2529 void AddMethodCandidate(CXXMethodDecl *Method,
2530 DeclAccessPair FoundDecl,
2531 CXXRecordDecl *ActingContext, QualType ObjectType,
2532 Expr::Classification ObjectClassification,
2533 ArrayRef<Expr *> Args,
2534 OverloadCandidateSet& CandidateSet,
2535 bool SuppressUserConversions = false,
2536 bool PartialOverloading = false);
2537 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2538 DeclAccessPair FoundDecl,
2539 CXXRecordDecl *ActingContext,
2540 TemplateArgumentListInfo *ExplicitTemplateArgs,
2541 QualType ObjectType,
2542 Expr::Classification ObjectClassification,
2543 ArrayRef<Expr *> Args,
2544 OverloadCandidateSet& CandidateSet,
2545 bool SuppressUserConversions = false,
2546 bool PartialOverloading = false);
2547 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2548 DeclAccessPair FoundDecl,
2549 TemplateArgumentListInfo *ExplicitTemplateArgs,
2550 ArrayRef<Expr *> Args,
2551 OverloadCandidateSet& CandidateSet,
2552 bool SuppressUserConversions = false,
2553 bool PartialOverloading = false);
2554 void AddConversionCandidate(CXXConversionDecl *Conversion,
2555 DeclAccessPair FoundDecl,
2556 CXXRecordDecl *ActingContext,
2557 Expr *From, QualType ToType,
2558 OverloadCandidateSet& CandidateSet,
2559 bool AllowObjCConversionOnExplicit);
2560 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2561 DeclAccessPair FoundDecl,
2562 CXXRecordDecl *ActingContext,
2563 Expr *From, QualType ToType,
2564 OverloadCandidateSet &CandidateSet,
2565 bool AllowObjCConversionOnExplicit);
2566 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2567 DeclAccessPair FoundDecl,
2568 CXXRecordDecl *ActingContext,
2569 const FunctionProtoType *Proto,
2570 Expr *Object, ArrayRef<Expr *> Args,
2571 OverloadCandidateSet& CandidateSet);
2572 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2573 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2574 OverloadCandidateSet& CandidateSet,
2575 SourceRange OpRange = SourceRange());
2576 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2577 ArrayRef<Expr *> Args,
2578 OverloadCandidateSet& CandidateSet,
2579 bool IsAssignmentOperator = false,
2580 unsigned NumContextualBoolArguments = 0);
2581 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2582 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2583 OverloadCandidateSet& CandidateSet);
2584 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2586 ArrayRef<Expr *> Args,
2587 TemplateArgumentListInfo *ExplicitTemplateArgs,
2588 OverloadCandidateSet& CandidateSet,
2589 bool PartialOverloading = false);
2591 // Emit as a 'note' the specific overload candidate
2592 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2593 QualType DestType = QualType(),
2594 bool TakingAddress = false);
2596 // Emit as a series of 'note's all template and non-templates identified by
2597 // the expression Expr
2598 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2599 bool TakingAddress = false);
2601 /// Check the enable_if expressions on the given function. Returns the first
2602 /// failing attribute, or NULL if they were all successful.
2603 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2604 bool MissingImplicitThis = false);
2606 /// Returns whether the given function's address can be taken or not,
2607 /// optionally emitting a diagnostic if the address can't be taken.
2609 /// Returns false if taking the address of the function is illegal.
2610 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2611 bool Complain = false,
2612 SourceLocation Loc = SourceLocation());
2614 // [PossiblyAFunctionType] --> [Return]
2615 // NonFunctionType --> NonFunctionType
2617 // R (*)(A) --> R (A)
2618 // R (&)(A) --> R (A)
2619 // R (S::*)(A) --> R (A)
2620 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2623 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2624 QualType TargetType,
2626 DeclAccessPair &Found,
2627 bool *pHadMultipleCandidates = nullptr);
2630 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2631 DeclAccessPair &FoundResult);
2633 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2636 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2637 bool Complain = false,
2638 DeclAccessPair *Found = nullptr);
2640 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2641 ExprResult &SrcExpr,
2642 bool DoFunctionPointerConverion = false,
2643 bool Complain = false,
2644 SourceRange OpRangeForComplaining = SourceRange(),
2645 QualType DestTypeForComplaining = QualType(),
2646 unsigned DiagIDForComplaining = 0);
2649 Expr *FixOverloadedFunctionReference(Expr *E,
2650 DeclAccessPair FoundDecl,
2652 ExprResult FixOverloadedFunctionReference(ExprResult,
2653 DeclAccessPair FoundDecl,
2656 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2657 ArrayRef<Expr *> Args,
2658 OverloadCandidateSet &CandidateSet,
2659 bool PartialOverloading = false);
2661 // An enum used to represent the different possible results of building a
2662 // range-based for loop.
2663 enum ForRangeStatus {
2665 FRS_NoViableFunction,
2666 FRS_DiagnosticIssued
2669 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2670 SourceLocation RangeLoc,
2671 const DeclarationNameInfo &NameInfo,
2672 LookupResult &MemberLookup,
2673 OverloadCandidateSet *CandidateSet,
2674 Expr *Range, ExprResult *CallExpr);
2676 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2677 UnresolvedLookupExpr *ULE,
2678 SourceLocation LParenLoc,
2680 SourceLocation RParenLoc,
2682 bool AllowTypoCorrection=true,
2683 bool CalleesAddressIsTaken=false);
2685 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2686 MultiExprArg Args, SourceLocation RParenLoc,
2687 OverloadCandidateSet *CandidateSet,
2688 ExprResult *Result);
2690 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2691 UnaryOperatorKind Opc,
2692 const UnresolvedSetImpl &Fns,
2695 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2696 BinaryOperatorKind Opc,
2697 const UnresolvedSetImpl &Fns,
2698 Expr *LHS, Expr *RHS);
2700 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2701 SourceLocation RLoc,
2702 Expr *Base,Expr *Idx);
2705 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2706 SourceLocation LParenLoc,
2708 SourceLocation RParenLoc);
2710 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2712 SourceLocation RParenLoc);
2714 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2715 SourceLocation OpLoc,
2716 bool *NoArrowOperatorFound = nullptr);
2718 /// CheckCallReturnType - Checks that a call expression's return type is
2719 /// complete. Returns true on failure. The location passed in is the location
2720 /// that best represents the call.
2721 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2722 CallExpr *CE, FunctionDecl *FD);
2724 /// Helpers for dealing with blocks and functions.
2725 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2726 bool CheckParameterNames);
2727 void CheckCXXDefaultArguments(FunctionDecl *FD);
2728 void CheckExtraCXXDefaultArguments(Declarator &D);
2729 Scope *getNonFieldDeclScope(Scope *S);
2731 /// \name Name lookup
2733 /// These routines provide name lookup that is used during semantic
2734 /// analysis to resolve the various kinds of names (identifiers,
2735 /// overloaded operator names, constructor names, etc.) into zero or
2736 /// more declarations within a particular scope. The major entry
2737 /// points are LookupName, which performs unqualified name lookup,
2738 /// and LookupQualifiedName, which performs qualified name lookup.
2740 /// All name lookup is performed based on some specific criteria,
2741 /// which specify what names will be visible to name lookup and how
2742 /// far name lookup should work. These criteria are important both
2743 /// for capturing language semantics (certain lookups will ignore
2744 /// certain names, for example) and for performance, since name
2745 /// lookup is often a bottleneck in the compilation of C++. Name
2746 /// lookup criteria is specified via the LookupCriteria enumeration.
2748 /// The results of name lookup can vary based on the kind of name
2749 /// lookup performed, the current language, and the translation
2750 /// unit. In C, for example, name lookup will either return nothing
2751 /// (no entity found) or a single declaration. In C++, name lookup
2752 /// can additionally refer to a set of overloaded functions or
2753 /// result in an ambiguity. All of the possible results of name
2754 /// lookup are captured by the LookupResult class, which provides
2755 /// the ability to distinguish among them.
2758 /// @brief Describes the kind of name lookup to perform.
2759 enum LookupNameKind {
2760 /// Ordinary name lookup, which finds ordinary names (functions,
2761 /// variables, typedefs, etc.) in C and most kinds of names
2762 /// (functions, variables, members, types, etc.) in C++.
2763 LookupOrdinaryName = 0,
2764 /// Tag name lookup, which finds the names of enums, classes,
2765 /// structs, and unions.
2767 /// Label name lookup.
2769 /// Member name lookup, which finds the names of
2770 /// class/struct/union members.
2772 /// Look up of an operator name (e.g., operator+) for use with
2773 /// operator overloading. This lookup is similar to ordinary name
2774 /// lookup, but will ignore any declarations that are class members.
2776 /// Look up of a name that precedes the '::' scope resolution
2777 /// operator in C++. This lookup completely ignores operator, object,
2778 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2779 LookupNestedNameSpecifierName,
2780 /// Look up a namespace name within a C++ using directive or
2781 /// namespace alias definition, ignoring non-namespace names (C++
2782 /// [basic.lookup.udir]p1).
2783 LookupNamespaceName,
2784 /// Look up all declarations in a scope with the given name,
2785 /// including resolved using declarations. This is appropriate
2786 /// for checking redeclarations for a using declaration.
2787 LookupUsingDeclName,
2788 /// Look up an ordinary name that is going to be redeclared as a
2789 /// name with linkage. This lookup ignores any declarations that
2790 /// are outside of the current scope unless they have linkage. See
2791 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2792 LookupRedeclarationWithLinkage,
2793 /// Look up a friend of a local class. This lookup does not look
2794 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2795 LookupLocalFriendName,
2796 /// Look up the name of an Objective-C protocol.
2797 LookupObjCProtocolName,
2798 /// Look up implicit 'self' parameter of an objective-c method.
2799 LookupObjCImplicitSelfParam,
2800 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2801 LookupOMPReductionName,
2802 /// \brief Look up any declaration with any name.
2806 /// \brief Specifies whether (or how) name lookup is being performed for a
2807 /// redeclaration (vs. a reference).
2808 enum RedeclarationKind {
2809 /// \brief The lookup is a reference to this name that is not for the
2810 /// purpose of redeclaring the name.
2811 NotForRedeclaration = 0,
2812 /// \brief The lookup results will be used for redeclaration of a name,
2813 /// if an entity by that name already exists.
2817 /// \brief The possible outcomes of name lookup for a literal operator.
2818 enum LiteralOperatorLookupResult {
2819 /// \brief The lookup resulted in an error.
2821 /// \brief The lookup found a single 'cooked' literal operator, which
2822 /// expects a normal literal to be built and passed to it.
2824 /// \brief The lookup found a single 'raw' literal operator, which expects
2825 /// a string literal containing the spelling of the literal token.
2827 /// \brief The lookup found an overload set of literal operator templates,
2828 /// which expect the characters of the spelling of the literal token to be
2829 /// passed as a non-type template argument pack.
2831 /// \brief The lookup found an overload set of literal operator templates,
2832 /// which expect the character type and characters of the spelling of the
2833 /// string literal token to be passed as template arguments.
2837 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2838 CXXSpecialMember SM,
2845 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2846 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2847 TypoRecoveryCallback;
2850 bool CppLookupName(LookupResult &R, Scope *S);
2852 struct TypoExprState {
2853 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2854 TypoDiagnosticGenerator DiagHandler;
2855 TypoRecoveryCallback RecoveryHandler;
2857 TypoExprState(TypoExprState &&other) noexcept;
2858 TypoExprState &operator=(TypoExprState &&other) noexcept;
2861 /// \brief The set of unhandled TypoExprs and their associated state.
2862 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2864 /// \brief Creates a new TypoExpr AST node.
2865 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2866 TypoDiagnosticGenerator TDG,
2867 TypoRecoveryCallback TRC);
2869 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2871 // The boolean value will be true to indicate that the namespace was loaded
2872 // from an AST/PCH file, or false otherwise.
2873 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2875 /// \brief Whether we have already loaded known namespaces from an extenal
2877 bool LoadedExternalKnownNamespaces;
2879 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2880 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2881 /// should be skipped entirely.
2882 std::unique_ptr<TypoCorrectionConsumer>
2883 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2884 Sema::LookupNameKind LookupKind, Scope *S,
2886 std::unique_ptr<CorrectionCandidateCallback> CCC,
2887 DeclContext *MemberContext, bool EnteringContext,
2888 const ObjCObjectPointerType *OPT,
2889 bool ErrorRecovery);
2892 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2894 /// \brief Clears the state of the given TypoExpr.
2895 void clearDelayedTypo(TypoExpr *TE);
2897 /// \brief Look up a name, looking for a single declaration. Return
2898 /// null if the results were absent, ambiguous, or overloaded.
2900 /// It is preferable to use the elaborated form and explicitly handle
2901 /// ambiguity and overloaded.
2902 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2904 LookupNameKind NameKind,
2905 RedeclarationKind Redecl
2906 = NotForRedeclaration);
2907 bool LookupName(LookupResult &R, Scope *S,
2908 bool AllowBuiltinCreation = false);
2909 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2910 bool InUnqualifiedLookup = false);
2911 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2913 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2914 bool AllowBuiltinCreation = false,
2915 bool EnteringContext = false);
2916 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2917 RedeclarationKind Redecl
2918 = NotForRedeclaration);
2919 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2921 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2922 QualType T1, QualType T2,
2923 UnresolvedSetImpl &Functions);
2924 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2925 DeclAccessPair Operator,
2926 QualType T1, QualType T2);
2928 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2929 SourceLocation GnuLabelLoc = SourceLocation());
2931 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2932 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2933 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2935 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2936 bool RValueThis, unsigned ThisQuals);
2937 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2939 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2940 bool RValueThis, unsigned ThisQuals);
2941 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2943 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2944 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2945 ArrayRef<QualType> ArgTys,
2948 bool AllowStringTemplate);
2949 bool isKnownName(StringRef name);
2951 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2952 ArrayRef<Expr *> Args, ADLResult &Functions);
2954 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2955 VisibleDeclConsumer &Consumer,
2956 bool IncludeGlobalScope = true);
2957 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2958 VisibleDeclConsumer &Consumer,
2959 bool IncludeGlobalScope = true);
2961 enum CorrectTypoKind {
2962 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2963 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2966 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2967 Sema::LookupNameKind LookupKind,
2968 Scope *S, CXXScopeSpec *SS,
2969 std::unique_ptr<CorrectionCandidateCallback> CCC,
2970 CorrectTypoKind Mode,
2971 DeclContext *MemberContext = nullptr,
2972 bool EnteringContext = false,
2973 const ObjCObjectPointerType *OPT = nullptr,
2974 bool RecordFailure = true);
2976 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2977 Sema::LookupNameKind LookupKind, Scope *S,
2979 std::unique_ptr<CorrectionCandidateCallback> CCC,
2980 TypoDiagnosticGenerator TDG,
2981 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2982 DeclContext *MemberContext = nullptr,
2983 bool EnteringContext = false,
2984 const ObjCObjectPointerType *OPT = nullptr);
2986 /// \brief Process any TypoExprs in the given Expr and its children,
2987 /// generating diagnostics as appropriate and returning a new Expr if there
2988 /// were typos that were all successfully corrected and ExprError if one or
2989 /// more typos could not be corrected.
2991 /// \param E The Expr to check for TypoExprs.
2993 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2996 /// \param Filter A function applied to a newly rebuilt Expr to determine if
2997 /// it is an acceptable/usable result from a single combination of typo
2998 /// corrections. As long as the filter returns ExprError, different
2999 /// combinations of corrections will be tried until all are exhausted.
3001 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3002 llvm::function_ref<ExprResult(Expr *)> Filter =
3003 [](Expr *E) -> ExprResult { return E; });
3006 CorrectDelayedTyposInExpr(Expr *E,
3007 llvm::function_ref<ExprResult(Expr *)> Filter) {
3008 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3012 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3013 llvm::function_ref<ExprResult(Expr *)> Filter =
3014 [](Expr *E) -> ExprResult { return E; }) {
3015 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3019 CorrectDelayedTyposInExpr(ExprResult ER,
3020 llvm::function_ref<ExprResult(Expr *)> Filter) {
3021 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3024 void diagnoseTypo(const TypoCorrection &Correction,
3025 const PartialDiagnostic &TypoDiag,
3026 bool ErrorRecovery = true);
3028 void diagnoseTypo(const TypoCorrection &Correction,
3029 const PartialDiagnostic &TypoDiag,
3030 const PartialDiagnostic &PrevNote,
3031 bool ErrorRecovery = true);
3033 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3034 ArrayRef<Expr *> Args,
3035 AssociatedNamespaceSet &AssociatedNamespaces,
3036 AssociatedClassSet &AssociatedClasses);
3038 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3039 bool ConsiderLinkage, bool AllowInlineNamespace);
3041 void DiagnoseAmbiguousLookup(LookupResult &Result);
3044 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3045 SourceLocation IdLoc,
3046 bool TypoCorrection = false);
3047 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3048 Scope *S, bool ForRedeclaration,
3049 SourceLocation Loc);
3050 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3052 void AddKnownFunctionAttributes(FunctionDecl *FD);
3054 // More parsing and symbol table subroutines.
3056 void ProcessPragmaWeak(Scope *S, Decl *D);
3057 // Decl attributes - this routine is the top level dispatcher.
3058 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3059 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3060 bool IncludeCXX11Attributes = true);
3061 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3062 const AttributeList *AttrList);
3064 void checkUnusedDeclAttributes(Declarator &D);
3066 /// Determine if type T is a valid subject for a nonnull and similar
3067 /// attributes. By default, we look through references (the behavior used by
3068 /// nonnull), but if the second parameter is true, then we treat a reference
3070 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3072 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3073 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3074 const FunctionDecl *FD = nullptr);
3075 bool CheckNoReturnAttr(const AttributeList &attr);
3076 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3077 unsigned ArgNum, StringRef &Str,
3078 SourceLocation *ArgLocation = nullptr);
3079 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3080 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3081 bool checkMSInheritanceAttrOnDefinition(
3082 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3083 MSInheritanceAttr::Spelling SemanticSpelling);
3085 void CheckAlignasUnderalignment(Decl *D);
3087 /// Adjust the calling convention of a method to be the ABI default if it
3088 /// wasn't specified explicitly. This handles method types formed from
3089 /// function type typedefs and typename template arguments.
3090 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3091 SourceLocation Loc);
3093 // Check if there is an explicit attribute, but only look through parens.
3094 // The intent is to look for an attribute on the current declarator, but not
3095 // one that came from a typedef.
3096 bool hasExplicitCallingConv(QualType &T);
3098 /// Get the outermost AttributedType node that sets a calling convention.
3099 /// Valid types should not have multiple attributes with different CCs.
3100 const AttributedType *getCallingConvAttributedType(QualType T) const;
3102 /// Check whether a nullability type specifier can be added to the given
3105 /// \param type The type to which the nullability specifier will be
3106 /// added. On success, this type will be updated appropriately.
3108 /// \param nullability The nullability specifier to add.
3110 /// \param nullabilityLoc The location of the nullability specifier.
3112 /// \param isContextSensitive Whether this nullability specifier was
3113 /// written as a context-sensitive keyword (in an Objective-C
3114 /// method) or an Objective-C property attribute, rather than as an
3115 /// underscored type specifier.
3117 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3118 /// array type (e.g., because it will decay to a pointer).
3120 /// \returns true if nullability cannot be applied, false otherwise.
3121 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3122 SourceLocation nullabilityLoc,
3123 bool isContextSensitive,
3124 bool allowArrayTypes);
3126 /// \brief Stmt attributes - this routine is the top level dispatcher.
3127 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3130 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3131 ObjCMethodDecl *MethodDecl,
3132 bool IsProtocolMethodDecl);
3134 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3135 ObjCMethodDecl *Overridden,
3136 bool IsProtocolMethodDecl);
3138 /// WarnExactTypedMethods - This routine issues a warning if method
3139 /// implementation declaration matches exactly that of its declaration.
3140 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3141 ObjCMethodDecl *MethodDecl,
3142 bool IsProtocolMethodDecl);
3144 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3145 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
3147 /// CheckImplementationIvars - This routine checks if the instance variables
3148 /// listed in the implelementation match those listed in the interface.
3149 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3150 ObjCIvarDecl **Fields, unsigned nIvars,
3151 SourceLocation Loc);
3153 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3154 /// remains unimplemented in the class or category \@implementation.
3155 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3156 ObjCContainerDecl* IDecl,
3157 bool IncompleteImpl = false);
3159 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3160 /// which must be implemented by this implementation.
3161 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3162 ObjCContainerDecl *CDecl,
3163 bool SynthesizeProperties);
3165 /// Diagnose any null-resettable synthesized setters.
3166 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3168 /// DefaultSynthesizeProperties - This routine default synthesizes all
3169 /// properties which must be synthesized in the class's \@implementation.
3170 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3171 ObjCInterfaceDecl *IDecl);
3172 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3174 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3175 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3176 /// declared in class 'IFace'.
3177 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3178 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3180 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3181 /// backs the property is not used in the property's accessor.
3182 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3183 const ObjCImplementationDecl *ImplD);
3185 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3186 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3187 /// It also returns ivar's property on success.
3188 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3189 const ObjCPropertyDecl *&PDecl) const;
3191 /// Called by ActOnProperty to handle \@property declarations in
3192 /// class extensions.
3193 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3194 SourceLocation AtLoc,
3195 SourceLocation LParenLoc,
3196 FieldDeclarator &FD,
3199 const bool isReadWrite,
3200 unsigned &Attributes,
3201 const unsigned AttributesAsWritten,
3203 TypeSourceInfo *TSI,
3204 tok::ObjCKeywordKind MethodImplKind);
3206 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3207 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3208 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3209 ObjCContainerDecl *CDecl,
3210 SourceLocation AtLoc,
3211 SourceLocation LParenLoc,
3212 FieldDeclarator &FD,
3215 const bool isReadWrite,
3216 const unsigned Attributes,
3217 const unsigned AttributesAsWritten,
3219 TypeSourceInfo *TSI,
3220 tok::ObjCKeywordKind MethodImplKind,
3221 DeclContext *lexicalDC = nullptr);
3223 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3224 /// warning) when atomic property has one but not the other user-declared
3225 /// setter or getter.
3226 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3227 ObjCInterfaceDecl* IDecl);
3229 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3231 void DiagnoseMissingDesignatedInitOverrides(
3232 const ObjCImplementationDecl *ImplD,
3233 const ObjCInterfaceDecl *IFD);
3235 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3237 enum MethodMatchStrategy {
3242 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3243 /// true, or false, accordingly.
3244 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3245 const ObjCMethodDecl *PrevMethod,
3246 MethodMatchStrategy strategy = MMS_strict);
3248 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3249 /// or protocol against those declared in their implementations.
3250 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3251 const SelectorSet &ClsMap,
3252 SelectorSet &InsMapSeen,
3253 SelectorSet &ClsMapSeen,
3254 ObjCImplDecl* IMPDecl,
3255 ObjCContainerDecl* IDecl,
3256 bool &IncompleteImpl,
3257 bool ImmediateClass,
3258 bool WarnCategoryMethodImpl=false);
3260 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3261 /// category matches with those implemented in its primary class and
3262 /// warns each time an exact match is found.
3263 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3265 /// \brief Add the given method to the list of globally-known methods.
3266 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3269 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3270 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3271 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3273 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3274 /// optionally warns if there are multiple signatures.
3275 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3276 bool receiverIdOrClass,
3280 /// \brief - Returns instance or factory methods in global method pool for
3281 /// given selector. It checks the desired kind first, if none is found, and
3282 /// parameter checkTheOther is set, it then checks the other kind. If no such
3283 /// method or only one method is found, function returns false; otherwise, it
3286 CollectMultipleMethodsInGlobalPool(Selector Sel,
3287 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3288 bool InstanceFirst, bool CheckTheOther,
3289 const ObjCObjectType *TypeBound = nullptr);
3292 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3293 SourceRange R, bool receiverIdOrClass,
3294 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3297 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3298 Selector Sel, SourceRange R,
3299 bool receiverIdOrClass);
3302 /// \brief - Returns a selector which best matches given argument list or
3303 /// nullptr if none could be found
3304 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3306 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3309 /// \brief Record the typo correction failure and return an empty correction.
3310 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3311 bool RecordFailure = true) {
3313 TypoCorrectionFailures[Typo].insert(TypoLoc);
3314 return TypoCorrection();
3318 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3319 /// unit are added to a global pool. This allows us to efficiently associate
3320 /// a selector with a method declaraation for purposes of typechecking
3321 /// messages sent to "id" (where the class of the object is unknown).
3322 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3323 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3326 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3327 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3328 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3331 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3333 void AddAnyMethodToGlobalPool(Decl *D);
3335 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3336 /// there are multiple signatures.
3337 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3338 bool receiverIdOrClass=false) {
3339 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3343 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3344 /// there are multiple signatures.
3345 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3346 bool receiverIdOrClass=false) {
3347 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3351 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3352 QualType ObjectType=QualType());
3353 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3355 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3357 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3359 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3360 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3362 //===--------------------------------------------------------------------===//
3363 // Statement Parsing Callbacks: SemaStmt.cpp.
3367 FullExprArg() : E(nullptr) { }
3368 FullExprArg(Sema &actions) : E(nullptr) { }
3370 ExprResult release() {
3374 Expr *get() const { return E; }
3376 Expr *operator->() {
3381 // FIXME: No need to make the entire Sema class a friend when it's just
3382 // Sema::MakeFullExpr that needs access to the constructor below.
3385 explicit FullExprArg(Expr *expr) : E(expr) {}
3390 FullExprArg MakeFullExpr(Expr *Arg) {
3391 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3393 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3394 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3396 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3398 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3399 /*DiscardedValue*/ true);
3400 return FullExprArg(FE.get());
3403 StmtResult ActOnExprStmt(ExprResult Arg);
3404 StmtResult ActOnExprStmtError();
3406 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3407 bool HasLeadingEmptyMacro = false);
3409 void ActOnStartOfCompoundStmt();
3410 void ActOnFinishOfCompoundStmt();
3411 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3412 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3414 /// \brief A RAII object to enter scope of a compound statement.
3415 class CompoundScopeRAII {
3417 CompoundScopeRAII(Sema &S): S(S) {
3418 S.ActOnStartOfCompoundStmt();
3421 ~CompoundScopeRAII() {
3422 S.ActOnFinishOfCompoundStmt();
3429 /// An RAII helper that pops function a function scope on exit.
3430 struct FunctionScopeRAII {
3433 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3434 ~FunctionScopeRAII() {
3436 S.PopFunctionScopeInfo();
3438 void disable() { Active = false; }
3441 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3442 SourceLocation StartLoc,
3443 SourceLocation EndLoc);
3444 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3445 StmtResult ActOnForEachLValueExpr(Expr *E);
3446 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3447 SourceLocation DotDotDotLoc, Expr *RHSVal,
3448 SourceLocation ColonLoc);
3449 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3451 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3452 SourceLocation ColonLoc,
3453 Stmt *SubStmt, Scope *CurScope);
3454 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3455 SourceLocation ColonLoc, Stmt *SubStmt);
3457 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3458 ArrayRef<const Attr*> Attrs,
3461 class ConditionResult;
3462 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3464 ConditionResult Cond, Stmt *ThenVal,
3465 SourceLocation ElseLoc, Stmt *ElseVal);
3466 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3468 ConditionResult Cond, Stmt *ThenVal,
3469 SourceLocation ElseLoc, Stmt *ElseVal);
3470 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3472 ConditionResult Cond);
3473 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3474 Stmt *Switch, Stmt *Body);
3475 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3477 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3478 SourceLocation WhileLoc, SourceLocation CondLParen,
3479 Expr *Cond, SourceLocation CondRParen);
3481 StmtResult ActOnForStmt(SourceLocation ForLoc,
3482 SourceLocation LParenLoc,
3484 ConditionResult Second,
3486 SourceLocation RParenLoc,
3488 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3490 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3491 Stmt *First, Expr *collection,
3492 SourceLocation RParenLoc);
3493 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3495 enum BuildForRangeKind {
3496 /// Initial building of a for-range statement.
3498 /// Instantiation or recovery rebuild of a for-range statement. Don't
3499 /// attempt any typo-correction.
3501 /// Determining whether a for-range statement could be built. Avoid any
3502 /// unnecessary or irreversible actions.
3506 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3507 SourceLocation CoawaitLoc,
3509 SourceLocation ColonLoc, Expr *Collection,
3510 SourceLocation RParenLoc,
3511 BuildForRangeKind Kind);
3512 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3513 SourceLocation CoawaitLoc,
3514 SourceLocation ColonLoc,
3515 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3516 Expr *Cond, Expr *Inc,
3518 SourceLocation RParenLoc,
3519 BuildForRangeKind Kind);
3520 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3522 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3523 SourceLocation LabelLoc,
3524 LabelDecl *TheDecl);
3525 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3526 SourceLocation StarLoc,
3528 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3529 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3531 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3532 CapturedRegionKind Kind, unsigned NumParams);
3533 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3534 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3535 CapturedRegionKind Kind,
3536 ArrayRef<CapturedParamNameType> Params);
3537 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3538 void ActOnCapturedRegionError();
3539 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3541 unsigned NumParams);
3542 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3543 bool AllowParamOrMoveConstructible);
3544 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3545 bool AllowParamOrMoveConstructible);
3547 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3549 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3550 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3552 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3553 bool IsVolatile, unsigned NumOutputs,
3554 unsigned NumInputs, IdentifierInfo **Names,
3555 MultiExprArg Constraints, MultiExprArg Exprs,
3556 Expr *AsmString, MultiExprArg Clobbers,
3557 SourceLocation RParenLoc);
3559 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3560 SourceLocation TemplateKWLoc,
3562 llvm::InlineAsmIdentifierInfo &Info,
3563 bool IsUnevaluatedContext);
3564 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3565 unsigned &Offset, SourceLocation AsmLoc);
3566 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3567 llvm::InlineAsmIdentifierInfo &Info,
3568 SourceLocation AsmLoc);
3569 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3570 ArrayRef<Token> AsmToks,
3571 StringRef AsmString,
3572 unsigned NumOutputs, unsigned NumInputs,
3573 ArrayRef<StringRef> Constraints,
3574 ArrayRef<StringRef> Clobbers,
3575 ArrayRef<Expr*> Exprs,
3576 SourceLocation EndLoc);
3577 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3578 SourceLocation Location,
3581 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3582 SourceLocation StartLoc,
3583 SourceLocation IdLoc, IdentifierInfo *Id,
3584 bool Invalid = false);
3586 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3588 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3589 Decl *Parm, Stmt *Body);
3591 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3593 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3594 MultiStmtArg Catch, Stmt *Finally);
3596 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3597 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3599 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3601 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3605 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3607 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3608 SourceLocation StartLoc,
3609 SourceLocation IdLoc,
3610 IdentifierInfo *Id);
3612 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3614 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3615 Decl *ExDecl, Stmt *HandlerBlock);
3616 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3617 ArrayRef<Stmt *> Handlers);
3619 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3620 SourceLocation TryLoc, Stmt *TryBlock,
3622 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3625 void ActOnStartSEHFinallyBlock();
3626 void ActOnAbortSEHFinallyBlock();
3627 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3628 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3630 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3632 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3634 /// \brief If it's a file scoped decl that must warn if not used, keep track
3636 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3638 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3639 /// whose result is unused, warn.
3640 void DiagnoseUnusedExprResult(const Stmt *S);
3641 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3642 void DiagnoseUnusedDecl(const NamedDecl *ND);
3644 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3645 /// statement as a \p Body, and it is located on the same line.
3647 /// This helps prevent bugs due to typos, such as:
3650 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3654 /// Warn if a for/while loop statement \p S, which is followed by
3655 /// \p PossibleBody, has a suspicious null statement as a body.
3656 void DiagnoseEmptyLoopBody(const Stmt *S,
3657 const Stmt *PossibleBody);
3659 /// Warn if a value is moved to itself.
3660 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3661 SourceLocation OpLoc);
3663 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3665 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3666 SourceLocation Loc);
3668 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3669 return DelayedDiagnostics.push(pool);
3671 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3673 typedef ProcessingContextState ParsingClassState;
3674 ParsingClassState PushParsingClass() {
3675 return DelayedDiagnostics.pushUndelayed();
3677 void PopParsingClass(ParsingClassState state) {
3678 DelayedDiagnostics.popUndelayed(state);
3681 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3683 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3684 StringRef Message, SourceLocation Loc,
3685 const ObjCInterfaceDecl *UnknownObjCClass,
3686 const ObjCPropertyDecl *ObjCProperty,
3687 bool ObjCPropertyAccess);
3689 bool makeUnavailableInSystemHeader(SourceLocation loc,
3690 UnavailableAttr::ImplicitReason reason);
3692 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3693 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3695 //===--------------------------------------------------------------------===//
3696 // Expression Parsing Callbacks: SemaExpr.cpp.
3698 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3699 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3700 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3701 bool ObjCPropertyAccess=false);
3702 void NoteDeletedFunction(FunctionDecl *FD);
3703 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3704 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3705 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3706 ObjCMethodDecl *Getter,
3707 SourceLocation Loc);
3708 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3709 ArrayRef<Expr *> Args);
3711 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3712 Decl *LambdaContextDecl = nullptr,
3713 bool IsDecltype = false);
3714 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3715 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3716 ReuseLambdaContextDecl_t,
3717 bool IsDecltype = false);
3718 void PopExpressionEvaluationContext();
3720 void DiscardCleanupsInEvaluationContext();
3722 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3723 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3725 ExprResult ActOnConstantExpression(ExprResult Res);
3727 // Functions for marking a declaration referenced. These functions also
3728 // contain the relevant logic for marking if a reference to a function or
3729 // variable is an odr-use (in the C++11 sense). There are separate variants
3730 // for expressions referring to a decl; these exist because odr-use marking
3731 // needs to be delayed for some constant variables when we build one of the
3732 // named expressions.
3734 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3735 // should usually be true. This only needs to be set to false if the lack of
3736 // odr-use cannot be determined from the current context (for instance,
3737 // because the name denotes a virtual function and was written without an
3738 // explicit nested-name-specifier).
3739 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3740 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3741 bool MightBeOdrUse = true);
3742 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3743 void MarkDeclRefReferenced(DeclRefExpr *E);
3744 void MarkMemberReferenced(MemberExpr *E);
3746 void UpdateMarkingForLValueToRValue(Expr *E);
3747 void CleanupVarDeclMarking();
3749 enum TryCaptureKind {
3750 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3753 /// \brief Try to capture the given variable.
3755 /// \param Var The variable to capture.
3757 /// \param Loc The location at which the capture occurs.
3759 /// \param Kind The kind of capture, which may be implicit (for either a
3760 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3762 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3763 /// an explicit lambda capture.
3765 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3766 /// captures or diagnose errors. If false, this routine merely check whether
3767 /// the capture can occur without performing the capture itself or complaining
3768 /// if the variable cannot be captured.
3770 /// \param CaptureType Will be set to the type of the field used to capture
3771 /// this variable in the innermost block or lambda. Only valid when the
3772 /// variable can be captured.
3774 /// \param DeclRefType Will be set to the type of a reference to the capture
3775 /// from within the current scope. Only valid when the variable can be
3778 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3779 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3780 /// This is useful when enclosing lambdas must speculatively capture
3781 /// variables that may or may not be used in certain specializations of
3782 /// a nested generic lambda.
3784 /// \returns true if an error occurred (i.e., the variable cannot be
3785 /// captured) and false if the capture succeeded.
3786 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3787 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3788 QualType &CaptureType,
3789 QualType &DeclRefType,
3790 const unsigned *const FunctionScopeIndexToStopAt);
3792 /// \brief Try to capture the given variable.
3793 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3794 TryCaptureKind Kind = TryCapture_Implicit,
3795 SourceLocation EllipsisLoc = SourceLocation());
3797 /// \brief Checks if the variable must be captured.
3798 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3800 /// \brief Given a variable, determine the type that a reference to that
3801 /// variable will have in the given scope.
3802 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3804 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3805 void MarkDeclarationsReferencedInExpr(Expr *E,
3806 bool SkipLocalVariables = false);
3808 /// \brief Try to recover by turning the given expression into a
3809 /// call. Returns true if recovery was attempted or an error was
3810 /// emitted; this may also leave the ExprResult invalid.
3811 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3812 bool ForceComplain = false,
3813 bool (*IsPlausibleResult)(QualType) = nullptr);
3815 /// \brief Figure out if an expression could be turned into a call.
3816 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3817 UnresolvedSetImpl &NonTemplateOverloads);
3819 /// \brief Conditionally issue a diagnostic based on the current
3820 /// evaluation context.
3822 /// \param Statement If Statement is non-null, delay reporting the
3823 /// diagnostic until the function body is parsed, and then do a basic
3824 /// reachability analysis to determine if the statement is reachable.
3825 /// If it is unreachable, the diagnostic will not be emitted.
3826 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3827 const PartialDiagnostic &PD);
3829 // Primary Expressions.
3830 SourceRange getExprRange(Expr *E) const;
3832 ExprResult ActOnIdExpression(
3833 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3834 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3835 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3836 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3838 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3839 TemplateArgumentListInfo &Buffer,
3840 DeclarationNameInfo &NameInfo,
3841 const TemplateArgumentListInfo *&TemplateArgs);
3844 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3845 std::unique_ptr<CorrectionCandidateCallback> CCC,
3846 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3847 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3849 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3851 bool AllowBuiltinCreation=false);
3853 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3854 SourceLocation TemplateKWLoc,
3855 const DeclarationNameInfo &NameInfo,
3856 bool isAddressOfOperand,
3857 const TemplateArgumentListInfo *TemplateArgs);
3859 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3862 const CXXScopeSpec *SS = nullptr);
3864 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3865 const DeclarationNameInfo &NameInfo,
3866 const CXXScopeSpec *SS = nullptr,
3867 NamedDecl *FoundD = nullptr,
3868 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3870 BuildAnonymousStructUnionMemberReference(
3871 const CXXScopeSpec &SS,
3872 SourceLocation nameLoc,
3873 IndirectFieldDecl *indirectField,
3874 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3875 Expr *baseObjectExpr = nullptr,
3876 SourceLocation opLoc = SourceLocation());
3878 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3879 SourceLocation TemplateKWLoc,
3881 const TemplateArgumentListInfo *TemplateArgs,
3883 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3884 SourceLocation TemplateKWLoc,
3886 const TemplateArgumentListInfo *TemplateArgs,
3887 bool IsDefiniteInstance,
3889 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3890 const LookupResult &R,
3891 bool HasTrailingLParen);
3894 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3895 const DeclarationNameInfo &NameInfo,
3896 bool IsAddressOfOperand, const Scope *S,
3897 TypeSourceInfo **RecoveryTSI = nullptr);
3899 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3900 SourceLocation TemplateKWLoc,
3901 const DeclarationNameInfo &NameInfo,
3902 const TemplateArgumentListInfo *TemplateArgs);
3904 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3907 bool AcceptInvalidDecl = false);
3908 ExprResult BuildDeclarationNameExpr(
3909 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3910 NamedDecl *FoundD = nullptr,
3911 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3912 bool AcceptInvalidDecl = false);
3914 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3915 DeclarationNameInfo &SuffixInfo,
3916 ArrayRef<Expr *> Args,
3917 SourceLocation LitEndLoc,
3918 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3920 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3921 PredefinedExpr::IdentType IT);
3922 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3923 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3925 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3927 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3928 ExprResult ActOnCharacterConstant(const Token &Tok,
3929 Scope *UDLScope = nullptr);
3930 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3931 ExprResult ActOnParenListExpr(SourceLocation L,
3935 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3936 /// fragments (e.g. "foo" "bar" L"baz").
3937 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3938 Scope *UDLScope = nullptr);
3940 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3941 SourceLocation DefaultLoc,
3942 SourceLocation RParenLoc,
3943 Expr *ControllingExpr,
3944 ArrayRef<ParsedType> ArgTypes,
3945 ArrayRef<Expr *> ArgExprs);
3946 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3947 SourceLocation DefaultLoc,
3948 SourceLocation RParenLoc,
3949 Expr *ControllingExpr,
3950 ArrayRef<TypeSourceInfo *> Types,
3951 ArrayRef<Expr *> Exprs);
3953 // Binary/Unary Operators. 'Tok' is the token for the operator.
3954 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3956 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3957 UnaryOperatorKind Opc, Expr *Input);
3958 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3959 tok::TokenKind Op, Expr *Input);
3961 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3963 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3964 SourceLocation OpLoc,
3965 UnaryExprOrTypeTrait ExprKind,
3967 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3968 UnaryExprOrTypeTrait ExprKind);
3970 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3971 UnaryExprOrTypeTrait ExprKind,
3972 bool IsType, void *TyOrEx,
3973 SourceRange ArgRange);
3975 ExprResult CheckPlaceholderExpr(Expr *E);
3976 bool CheckVecStepExpr(Expr *E);
3978 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3979 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3980 SourceRange ExprRange,
3981 UnaryExprOrTypeTrait ExprKind);
3982 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3983 SourceLocation OpLoc,
3984 IdentifierInfo &Name,
3985 SourceLocation NameLoc,
3986 SourceLocation RParenLoc);
3987 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3988 tok::TokenKind Kind, Expr *Input);
3990 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3991 Expr *Idx, SourceLocation RLoc);
3992 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3993 Expr *Idx, SourceLocation RLoc);
3994 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3995 Expr *LowerBound, SourceLocation ColonLoc,
3996 Expr *Length, SourceLocation RBLoc);
3998 // This struct is for use by ActOnMemberAccess to allow
3999 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4000 // changing the access operator from a '.' to a '->' (to see if that is the
4001 // change needed to fix an error about an unknown member, e.g. when the class
4002 // defines a custom operator->).
4003 struct ActOnMemberAccessExtraArgs {
4009 ExprResult BuildMemberReferenceExpr(
4010 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4011 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4012 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4013 const TemplateArgumentListInfo *TemplateArgs,
4015 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4018 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4019 bool IsArrow, const CXXScopeSpec &SS,
4020 SourceLocation TemplateKWLoc,
4021 NamedDecl *FirstQualifierInScope, LookupResult &R,
4022 const TemplateArgumentListInfo *TemplateArgs,
4024 bool SuppressQualifierCheck = false,
4025 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4027 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4028 SourceLocation OpLoc,
4029 const CXXScopeSpec &SS, FieldDecl *Field,
4030 DeclAccessPair FoundDecl,
4031 const DeclarationNameInfo &MemberNameInfo);
4033 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4035 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4036 const CXXScopeSpec &SS,
4037 const LookupResult &R);
4039 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4040 bool IsArrow, SourceLocation OpLoc,
4041 const CXXScopeSpec &SS,
4042 SourceLocation TemplateKWLoc,
4043 NamedDecl *FirstQualifierInScope,
4044 const DeclarationNameInfo &NameInfo,
4045 const TemplateArgumentListInfo *TemplateArgs);
4047 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4048 SourceLocation OpLoc,
4049 tok::TokenKind OpKind,
4051 SourceLocation TemplateKWLoc,
4052 UnqualifiedId &Member,
4055 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4056 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4057 FunctionDecl *FDecl,
4058 const FunctionProtoType *Proto,
4059 ArrayRef<Expr *> Args,
4060 SourceLocation RParenLoc,
4061 bool ExecConfig = false);
4062 void CheckStaticArrayArgument(SourceLocation CallLoc,
4064 const Expr *ArgExpr);
4066 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4067 /// This provides the location of the left/right parens and a list of comma
4069 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4070 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4071 Expr *ExecConfig = nullptr,
4072 bool IsExecConfig = false);
4073 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4074 SourceLocation LParenLoc,
4075 ArrayRef<Expr *> Arg,
4076 SourceLocation RParenLoc,
4077 Expr *Config = nullptr,
4078 bool IsExecConfig = false);
4080 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4081 MultiExprArg ExecConfig,
4082 SourceLocation GGGLoc);
4084 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4085 Declarator &D, ParsedType &Ty,
4086 SourceLocation RParenLoc, Expr *CastExpr);
4087 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4089 SourceLocation RParenLoc,
4091 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4093 /// \brief Build an altivec or OpenCL literal.
4094 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4095 SourceLocation RParenLoc, Expr *E,
4096 TypeSourceInfo *TInfo);
4098 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4100 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4102 SourceLocation RParenLoc,
4105 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4106 TypeSourceInfo *TInfo,
4107 SourceLocation RParenLoc,
4110 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4111 MultiExprArg InitArgList,
4112 SourceLocation RBraceLoc);
4114 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4120 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4123 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4124 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4125 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4126 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4127 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4128 Expr *LHSExpr, Expr *RHSExpr);
4130 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4132 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4133 /// in the case of a the GNU conditional expr extension.
4134 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4135 SourceLocation ColonLoc,
4136 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4138 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4139 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4140 LabelDecl *TheDecl);
4142 void ActOnStartStmtExpr();
4143 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4144 SourceLocation RPLoc); // "({..})"
4145 void ActOnStmtExprError();
4147 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4148 struct OffsetOfComponent {
4149 SourceLocation LocStart, LocEnd;
4150 bool isBrackets; // true if [expr], false if .ident
4152 IdentifierInfo *IdentInfo;
4157 /// __builtin_offsetof(type, a.b[123][456].c)
4158 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4159 TypeSourceInfo *TInfo,
4160 ArrayRef<OffsetOfComponent> Components,
4161 SourceLocation RParenLoc);
4162 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4163 SourceLocation BuiltinLoc,
4164 SourceLocation TypeLoc,
4165 ParsedType ParsedArgTy,
4166 ArrayRef<OffsetOfComponent> Components,
4167 SourceLocation RParenLoc);
4169 // __builtin_choose_expr(constExpr, expr1, expr2)
4170 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4171 Expr *CondExpr, Expr *LHSExpr,
4172 Expr *RHSExpr, SourceLocation RPLoc);
4174 // __builtin_va_arg(expr, type)
4175 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4176 SourceLocation RPLoc);
4177 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4178 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4181 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4183 bool CheckCaseExpression(Expr *E);
4185 /// \brief Describes the result of an "if-exists" condition check.
4186 enum IfExistsResult {
4187 /// \brief The symbol exists.
4190 /// \brief The symbol does not exist.
4193 /// \brief The name is a dependent name, so the results will differ
4194 /// from one instantiation to the next.
4197 /// \brief An error occurred.
4202 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4203 const DeclarationNameInfo &TargetNameInfo);
4206 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4207 bool IsIfExists, CXXScopeSpec &SS,
4208 UnqualifiedId &Name);
4210 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4212 NestedNameSpecifierLoc QualifierLoc,
4213 DeclarationNameInfo NameInfo,
4215 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4217 CXXScopeSpec &SS, UnqualifiedId &Name,
4220 //===------------------------- "Block" Extension ------------------------===//
4222 /// ActOnBlockStart - This callback is invoked when a block literal is
4224 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4226 /// ActOnBlockArguments - This callback allows processing of block arguments.
4227 /// If there are no arguments, this is still invoked.
4228 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4231 /// ActOnBlockError - If there is an error parsing a block, this callback
4232 /// is invoked to pop the information about the block from the action impl.
4233 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4235 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4236 /// literal was successfully completed. ^(int x){...}
4237 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4240 //===---------------------------- Clang Extensions ----------------------===//
4242 /// __builtin_convertvector(...)
4243 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4244 SourceLocation BuiltinLoc,
4245 SourceLocation RParenLoc);
4247 //===---------------------------- OpenCL Features -----------------------===//
4249 /// __builtin_astype(...)
4250 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4251 SourceLocation BuiltinLoc,
4252 SourceLocation RParenLoc);
4254 //===---------------------------- C++ Features --------------------------===//
4256 // Act on C++ namespaces
4257 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4258 SourceLocation NamespaceLoc,
4259 SourceLocation IdentLoc,
4260 IdentifierInfo *Ident,
4261 SourceLocation LBrace,
4262 AttributeList *AttrList,
4263 UsingDirectiveDecl * &UsingDecl);
4264 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4266 NamespaceDecl *getStdNamespace() const;
4267 NamespaceDecl *getOrCreateStdNamespace();
4269 NamespaceDecl *lookupStdExperimentalNamespace();
4271 CXXRecordDecl *getStdBadAlloc() const;
4272 EnumDecl *getStdAlignValT() const;
4274 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4275 /// it is and Element is not NULL, assigns the element type to Element.
4276 bool isStdInitializerList(QualType Ty, QualType *Element);
4278 /// \brief Looks for the std::initializer_list template and instantiates it
4279 /// with Element, or emits an error if it's not found.
4281 /// \returns The instantiated template, or null on error.
4282 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4284 /// \brief Determine whether Ctor is an initializer-list constructor, as
4285 /// defined in [dcl.init.list]p2.
4286 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4288 Decl *ActOnUsingDirective(Scope *CurScope,
4289 SourceLocation UsingLoc,
4290 SourceLocation NamespcLoc,
4292 SourceLocation IdentLoc,
4293 IdentifierInfo *NamespcName,
4294 AttributeList *AttrList);
4296 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4298 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4299 SourceLocation NamespaceLoc,
4300 SourceLocation AliasLoc,
4301 IdentifierInfo *Alias,
4303 SourceLocation IdentLoc,
4304 IdentifierInfo *Ident);
4306 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4307 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4308 const LookupResult &PreviousDecls,
4309 UsingShadowDecl *&PrevShadow);
4310 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4312 UsingShadowDecl *PrevDecl);
4314 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4315 bool HasTypenameKeyword,
4316 const CXXScopeSpec &SS,
4317 SourceLocation NameLoc,
4318 const LookupResult &Previous);
4319 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4321 const CXXScopeSpec &SS,
4322 const DeclarationNameInfo &NameInfo,
4323 SourceLocation NameLoc);
4325 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4326 SourceLocation UsingLoc,
4327 bool HasTypenameKeyword,
4328 SourceLocation TypenameLoc,
4330 DeclarationNameInfo NameInfo,
4331 SourceLocation EllipsisLoc,
4332 AttributeList *AttrList,
4333 bool IsInstantiation);
4334 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4335 ArrayRef<NamedDecl *> Expansions);
4337 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4339 /// Given a derived-class using shadow declaration for a constructor and the
4340 /// correspnding base class constructor, find or create the implicit
4341 /// synthesized derived class constructor to use for this initialization.
4342 CXXConstructorDecl *
4343 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4344 ConstructorUsingShadowDecl *DerivedShadow);
4346 Decl *ActOnUsingDeclaration(Scope *CurScope,
4348 SourceLocation UsingLoc,
4349 SourceLocation TypenameLoc,
4351 UnqualifiedId &Name,
4352 SourceLocation EllipsisLoc,
4353 AttributeList *AttrList);
4354 Decl *ActOnAliasDeclaration(Scope *CurScope,
4356 MultiTemplateParamsArg TemplateParams,
4357 SourceLocation UsingLoc,
4358 UnqualifiedId &Name,
4359 AttributeList *AttrList,
4361 Decl *DeclFromDeclSpec);
4363 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4364 /// including handling of its default argument expressions.
4366 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4368 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4369 NamedDecl *FoundDecl,
4370 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4371 bool HadMultipleCandidates, bool IsListInitialization,
4372 bool IsStdInitListInitialization,
4373 bool RequiresZeroInit, unsigned ConstructKind,
4374 SourceRange ParenRange);
4376 /// Build a CXXConstructExpr whose constructor has already been resolved if
4377 /// it denotes an inherited constructor.
4379 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4380 CXXConstructorDecl *Constructor, bool Elidable,
4382 bool HadMultipleCandidates, bool IsListInitialization,
4383 bool IsStdInitListInitialization,
4384 bool RequiresZeroInit, unsigned ConstructKind,
4385 SourceRange ParenRange);
4387 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4388 // the constructor can be elidable?
4390 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4391 NamedDecl *FoundDecl,
4392 CXXConstructorDecl *Constructor, bool Elidable,
4393 MultiExprArg Exprs, bool HadMultipleCandidates,
4394 bool IsListInitialization,
4395 bool IsStdInitListInitialization, bool RequiresZeroInit,
4396 unsigned ConstructKind, SourceRange ParenRange);
4398 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4401 /// Instantiate or parse a C++ default argument expression as necessary.
4402 /// Return true on error.
4403 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4404 ParmVarDecl *Param);
4406 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4407 /// the default expr if needed.
4408 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4410 ParmVarDecl *Param);
4412 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4413 /// constructed variable.
4414 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4416 /// \brief Helper class that collects exception specifications for
4417 /// implicitly-declared special member functions.
4418 class ImplicitExceptionSpecification {
4419 // Pointer to allow copying
4421 // We order exception specifications thus:
4422 // noexcept is the most restrictive, but is only used in C++11.
4423 // throw() comes next.
4424 // Then a throw(collected exceptions)
4425 // Finally no specification, which is expressed as noexcept(false).
4426 // throw(...) is used instead if any called function uses it.
4427 ExceptionSpecificationType ComputedEST;
4428 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4429 SmallVector<QualType, 4> Exceptions;
4431 void ClearExceptions() {
4432 ExceptionsSeen.clear();
4437 explicit ImplicitExceptionSpecification(Sema &Self)
4438 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4439 if (!Self.getLangOpts().CPlusPlus11)
4440 ComputedEST = EST_DynamicNone;
4443 /// \brief Get the computed exception specification type.
4444 ExceptionSpecificationType getExceptionSpecType() const {
4445 assert(ComputedEST != EST_ComputedNoexcept &&
4446 "noexcept(expr) should not be a possible result");
4450 /// \brief The number of exceptions in the exception specification.
4451 unsigned size() const { return Exceptions.size(); }
4453 /// \brief The set of exceptions in the exception specification.
4454 const QualType *data() const { return Exceptions.data(); }
4456 /// \brief Integrate another called method into the collected data.
4457 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4459 /// \brief Integrate an invoked expression into the collected data.
4460 void CalledExpr(Expr *E);
4462 /// \brief Overwrite an EPI's exception specification with this
4463 /// computed exception specification.
4464 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4465 FunctionProtoType::ExceptionSpecInfo ESI;
4466 ESI.Type = getExceptionSpecType();
4467 if (ESI.Type == EST_Dynamic) {
4468 ESI.Exceptions = Exceptions;
4469 } else if (ESI.Type == EST_None) {
4470 /// C++11 [except.spec]p14:
4471 /// The exception-specification is noexcept(false) if the set of
4472 /// potential exceptions of the special member function contains "any"
4473 ESI.Type = EST_ComputedNoexcept;
4474 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4475 tok::kw_false).get();
4481 /// \brief Determine what sort of exception specification a defaulted
4482 /// copy constructor of a class will have.
4483 ImplicitExceptionSpecification
4484 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4487 /// \brief Determine what sort of exception specification a defaulted
4488 /// default constructor of a class will have, and whether the parameter
4490 ImplicitExceptionSpecification
4491 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4493 /// \brief Determine what sort of exception specification a defautled
4494 /// copy assignment operator of a class will have, and whether the
4495 /// parameter will be const.
4496 ImplicitExceptionSpecification
4497 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4499 /// \brief Determine what sort of exception specification a defaulted move
4500 /// constructor of a class will have.
4501 ImplicitExceptionSpecification
4502 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4504 /// \brief Determine what sort of exception specification a defaulted move
4505 /// assignment operator of a class will have.
4506 ImplicitExceptionSpecification
4507 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4509 /// \brief Determine what sort of exception specification a defaulted
4510 /// destructor of a class will have.
4511 ImplicitExceptionSpecification
4512 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4514 /// \brief Determine what sort of exception specification an inheriting
4515 /// constructor of a class will have.
4516 ImplicitExceptionSpecification
4517 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4518 CXXConstructorDecl *CD);
4520 /// \brief Evaluate the implicit exception specification for a defaulted
4521 /// special member function.
4522 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4524 /// \brief Check the given exception-specification and update the
4525 /// exception specification information with the results.
4526 void checkExceptionSpecification(bool IsTopLevel,
4527 ExceptionSpecificationType EST,
4528 ArrayRef<ParsedType> DynamicExceptions,
4529 ArrayRef<SourceRange> DynamicExceptionRanges,
4531 SmallVectorImpl<QualType> &Exceptions,
4532 FunctionProtoType::ExceptionSpecInfo &ESI);
4534 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4535 /// parse an exception specification to work around a libstdc++ bug.
4536 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4538 /// \brief Add an exception-specification to the given member function
4539 /// (or member function template). The exception-specification was parsed
4540 /// after the method itself was declared.
4541 void actOnDelayedExceptionSpecification(Decl *Method,
4542 ExceptionSpecificationType EST,
4543 SourceRange SpecificationRange,
4544 ArrayRef<ParsedType> DynamicExceptions,
4545 ArrayRef<SourceRange> DynamicExceptionRanges,
4546 Expr *NoexceptExpr);
4548 class InheritedConstructorInfo;
4550 /// \brief Determine if a special member function should have a deleted
4551 /// definition when it is defaulted.
4552 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4553 InheritedConstructorInfo *ICI = nullptr,
4554 bool Diagnose = false);
4556 /// \brief Declare the implicit default constructor for the given class.
4558 /// \param ClassDecl The class declaration into which the implicit
4559 /// default constructor will be added.
4561 /// \returns The implicitly-declared default constructor.
4562 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4563 CXXRecordDecl *ClassDecl);
4565 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4566 /// defining this constructor as the default constructor.
4567 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4568 CXXConstructorDecl *Constructor);
4570 /// \brief Declare the implicit destructor for the given class.
4572 /// \param ClassDecl The class declaration into which the implicit
4573 /// destructor will be added.
4575 /// \returns The implicitly-declared destructor.
4576 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4578 /// DefineImplicitDestructor - Checks for feasibility of
4579 /// defining this destructor as the default destructor.
4580 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4581 CXXDestructorDecl *Destructor);
4583 /// \brief Build an exception spec for destructors that don't have one.
4585 /// C++11 says that user-defined destructors with no exception spec get one
4586 /// that looks as if the destructor was implicitly declared.
4587 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4588 CXXDestructorDecl *Destructor);
4590 /// \brief Define the specified inheriting constructor.
4591 void DefineInheritingConstructor(SourceLocation UseLoc,
4592 CXXConstructorDecl *Constructor);
4594 /// \brief Declare the implicit copy constructor for the given class.
4596 /// \param ClassDecl The class declaration into which the implicit
4597 /// copy constructor will be added.
4599 /// \returns The implicitly-declared copy constructor.
4600 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4602 /// DefineImplicitCopyConstructor - Checks for feasibility of
4603 /// defining this constructor as the copy constructor.
4604 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4605 CXXConstructorDecl *Constructor);
4607 /// \brief Declare the implicit move constructor for the given class.
4609 /// \param ClassDecl The Class declaration into which the implicit
4610 /// move constructor will be added.
4612 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4614 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4616 /// DefineImplicitMoveConstructor - Checks for feasibility of
4617 /// defining this constructor as the move constructor.
4618 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4619 CXXConstructorDecl *Constructor);
4621 /// \brief Declare the implicit copy assignment operator for the given class.
4623 /// \param ClassDecl The class declaration into which the implicit
4624 /// copy assignment operator will be added.
4626 /// \returns The implicitly-declared copy assignment operator.
4627 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4629 /// \brief Defines an implicitly-declared copy assignment operator.
4630 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4631 CXXMethodDecl *MethodDecl);
4633 /// \brief Declare the implicit move assignment operator for the given class.
4635 /// \param ClassDecl The Class declaration into which the implicit
4636 /// move assignment operator will be added.
4638 /// \returns The implicitly-declared move assignment operator, or NULL if it
4639 /// wasn't declared.
4640 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4642 /// \brief Defines an implicitly-declared move assignment operator.
4643 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4644 CXXMethodDecl *MethodDecl);
4646 /// \brief Force the declaration of any implicitly-declared members of this
4648 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4650 /// \brief Check a completed declaration of an implicit special member.
4651 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4653 /// \brief Determine whether the given function is an implicitly-deleted
4654 /// special member function.
4655 bool isImplicitlyDeleted(FunctionDecl *FD);
4657 /// \brief Check whether 'this' shows up in the type of a static member
4658 /// function after the (naturally empty) cv-qualifier-seq would be.
4660 /// \returns true if an error occurred.
4661 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4663 /// \brief Whether this' shows up in the exception specification of a static
4664 /// member function.
4665 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4667 /// \brief Check whether 'this' shows up in the attributes of the given
4668 /// static member function.
4670 /// \returns true if an error occurred.
4671 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4673 /// MaybeBindToTemporary - If the passed in expression has a record type with
4674 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4675 /// it simply returns the passed in expression.
4676 ExprResult MaybeBindToTemporary(Expr *E);
4678 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4679 MultiExprArg ArgsPtr,
4681 SmallVectorImpl<Expr*> &ConvertedArgs,
4682 bool AllowExplicit = false,
4683 bool IsListInitialization = false);
4685 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4686 SourceLocation NameLoc,
4687 IdentifierInfo &Name);
4689 ParsedType getDestructorName(SourceLocation TildeLoc,
4690 IdentifierInfo &II, SourceLocation NameLoc,
4691 Scope *S, CXXScopeSpec &SS,
4692 ParsedType ObjectType,
4693 bool EnteringContext);
4695 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4697 // Checks that reinterpret casts don't have undefined behavior.
4698 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4699 bool IsDereference, SourceRange Range);
4701 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4702 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4703 tok::TokenKind Kind,
4704 SourceLocation LAngleBracketLoc,
4706 SourceLocation RAngleBracketLoc,
4707 SourceLocation LParenLoc,
4709 SourceLocation RParenLoc);
4711 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4712 tok::TokenKind Kind,
4715 SourceRange AngleBrackets,
4716 SourceRange Parens);
4718 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4719 SourceLocation TypeidLoc,
4720 TypeSourceInfo *Operand,
4721 SourceLocation RParenLoc);
4722 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4723 SourceLocation TypeidLoc,
4725 SourceLocation RParenLoc);
4727 /// ActOnCXXTypeid - Parse typeid( something ).
4728 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4729 SourceLocation LParenLoc, bool isType,
4731 SourceLocation RParenLoc);
4733 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4734 SourceLocation TypeidLoc,
4735 TypeSourceInfo *Operand,
4736 SourceLocation RParenLoc);
4737 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4738 SourceLocation TypeidLoc,
4740 SourceLocation RParenLoc);
4742 /// ActOnCXXUuidof - Parse __uuidof( something ).
4743 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4744 SourceLocation LParenLoc, bool isType,
4746 SourceLocation RParenLoc);
4748 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4749 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4750 tok::TokenKind Operator,
4751 SourceLocation EllipsisLoc, Expr *RHS,
4752 SourceLocation RParenLoc);
4753 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4754 BinaryOperatorKind Operator,
4755 SourceLocation EllipsisLoc, Expr *RHS,
4756 SourceLocation RParenLoc);
4757 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4758 BinaryOperatorKind Operator);
4760 //// ActOnCXXThis - Parse 'this' pointer.
4761 ExprResult ActOnCXXThis(SourceLocation loc);
4763 /// \brief Try to retrieve the type of the 'this' pointer.
4765 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4766 QualType getCurrentThisType();
4768 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4769 /// current context not being a non-static member function. In such cases,
4770 /// this provides the type used for 'this'.
4771 QualType CXXThisTypeOverride;
4773 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4774 /// to be used, with the given qualifiers on the current class type.
4775 class CXXThisScopeRAII {
4777 QualType OldCXXThisTypeOverride;
4781 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4782 /// using the given declaration (which is either a class template or a
4783 /// class) along with the given qualifiers.
4784 /// along with the qualifiers placed on '*this'.
4785 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4786 bool Enabled = true);
4788 ~CXXThisScopeRAII();
4791 /// \brief Make sure the value of 'this' is actually available in the current
4792 /// context, if it is a potentially evaluated context.
4794 /// \param Loc The location at which the capture of 'this' occurs.
4796 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4799 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4800 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4801 /// This is useful when enclosing lambdas must speculatively capture
4802 /// 'this' that may or may not be used in certain specializations of
4803 /// a nested generic lambda (depending on whether the name resolves to
4804 /// a non-static member function or a static function).
4805 /// \return returns 'true' if failed, 'false' if success.
4806 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4807 bool BuildAndDiagnose = true,
4808 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4809 bool ByCopy = false);
4811 /// \brief Determine whether the given type is the type of *this that is used
4812 /// outside of the body of a member function for a type that is currently
4814 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4816 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4817 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4820 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4821 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4824 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4825 SourceLocation AtLoc, SourceLocation RParen);
4827 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4828 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4830 //// ActOnCXXThrow - Parse throw expressions.
4831 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4832 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4833 bool IsThrownVarInScope);
4834 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4836 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4837 /// Can be interpreted either as function-style casting ("int(x)")
4838 /// or class type construction ("ClassType(x,y,z)")
4839 /// or creation of a value-initialized type ("int()").
4840 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4841 SourceLocation LParenLoc,
4843 SourceLocation RParenLoc);
4845 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4846 SourceLocation LParenLoc,
4848 SourceLocation RParenLoc);
4850 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4851 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4852 SourceLocation PlacementLParen,
4853 MultiExprArg PlacementArgs,
4854 SourceLocation PlacementRParen,
4855 SourceRange TypeIdParens, Declarator &D,
4857 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4858 SourceLocation PlacementLParen,
4859 MultiExprArg PlacementArgs,
4860 SourceLocation PlacementRParen,
4861 SourceRange TypeIdParens,
4863 TypeSourceInfo *AllocTypeInfo,
4865 SourceRange DirectInitRange,
4867 bool TypeMayContainAuto = true);
4869 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4871 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4872 bool UseGlobal, QualType AllocType, bool IsArray,
4873 bool &PassAlignment, MultiExprArg PlaceArgs,
4874 FunctionDecl *&OperatorNew,
4875 FunctionDecl *&OperatorDelete);
4876 void DeclareGlobalNewDelete();
4877 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4878 ArrayRef<QualType> Params);
4880 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4881 DeclarationName Name, FunctionDecl* &Operator,
4882 bool Diagnose = true);
4883 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4884 bool CanProvideSize,
4886 DeclarationName Name);
4887 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4890 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4891 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4892 bool UseGlobal, bool ArrayForm,
4894 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4895 bool IsDelete, bool CallCanBeVirtual,
4896 bool WarnOnNonAbstractTypes,
4897 SourceLocation DtorLoc);
4899 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4900 Expr *Operand, SourceLocation RParen);
4901 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4902 SourceLocation RParen);
4904 /// \brief Parsed one of the type trait support pseudo-functions.
4905 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4906 ArrayRef<ParsedType> Args,
4907 SourceLocation RParenLoc);
4908 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4909 ArrayRef<TypeSourceInfo *> Args,
4910 SourceLocation RParenLoc);
4912 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4913 /// pseudo-functions.
4914 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4915 SourceLocation KWLoc,
4918 SourceLocation RParen);
4920 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4921 SourceLocation KWLoc,
4922 TypeSourceInfo *TSInfo,
4924 SourceLocation RParen);
4926 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4927 /// pseudo-functions.
4928 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4929 SourceLocation KWLoc,
4931 SourceLocation RParen);
4933 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4934 SourceLocation KWLoc,
4936 SourceLocation RParen);
4938 ExprResult ActOnStartCXXMemberReference(Scope *S,
4940 SourceLocation OpLoc,
4941 tok::TokenKind OpKind,
4942 ParsedType &ObjectType,
4943 bool &MayBePseudoDestructor);
4945 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4946 SourceLocation OpLoc,
4947 tok::TokenKind OpKind,
4948 const CXXScopeSpec &SS,
4949 TypeSourceInfo *ScopeType,
4950 SourceLocation CCLoc,
4951 SourceLocation TildeLoc,
4952 PseudoDestructorTypeStorage DestroyedType);
4954 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4955 SourceLocation OpLoc,
4956 tok::TokenKind OpKind,
4958 UnqualifiedId &FirstTypeName,
4959 SourceLocation CCLoc,
4960 SourceLocation TildeLoc,
4961 UnqualifiedId &SecondTypeName);
4963 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4964 SourceLocation OpLoc,
4965 tok::TokenKind OpKind,
4966 SourceLocation TildeLoc,
4967 const DeclSpec& DS);
4969 /// MaybeCreateExprWithCleanups - If the current full-expression
4970 /// requires any cleanups, surround it with a ExprWithCleanups node.
4971 /// Otherwise, just returns the passed-in expression.
4972 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4973 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4974 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4976 MaterializeTemporaryExpr *
4977 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
4978 bool BoundToLvalueReference);
4980 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4981 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4982 : SourceLocation());
4984 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4985 bool DiscardedValue = false,
4986 bool IsConstexpr = false,
4987 bool IsLambdaInitCaptureInitializer = false);
4988 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4990 // Marks SS invalid if it represents an incomplete type.
4991 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4993 DeclContext *computeDeclContext(QualType T);
4994 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4995 bool EnteringContext = false);
4996 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4997 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4999 /// \brief The parser has parsed a global nested-name-specifier '::'.
5001 /// \param CCLoc The location of the '::'.
5003 /// \param SS The nested-name-specifier, which will be updated in-place
5004 /// to reflect the parsed nested-name-specifier.
5006 /// \returns true if an error occurred, false otherwise.
5007 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5009 /// \brief The parser has parsed a '__super' nested-name-specifier.
5011 /// \param SuperLoc The location of the '__super' keyword.
5013 /// \param ColonColonLoc The location of the '::'.
5015 /// \param SS The nested-name-specifier, which will be updated in-place
5016 /// to reflect the parsed nested-name-specifier.
5018 /// \returns true if an error occurred, false otherwise.
5019 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5020 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5022 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5023 bool *CanCorrect = nullptr);
5024 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5026 /// \brief Keeps information about an identifier in a nested-name-spec.
5028 struct NestedNameSpecInfo {
5029 /// \brief The type of the object, if we're parsing nested-name-specifier in
5030 /// a member access expression.
5031 ParsedType ObjectType;
5033 /// \brief The identifier preceding the '::'.
5034 IdentifierInfo *Identifier;
5036 /// \brief The location of the identifier.
5037 SourceLocation IdentifierLoc;
5039 /// \brief The location of the '::'.
5040 SourceLocation CCLoc;
5042 /// \brief Creates info object for the most typical case.
5043 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5044 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5045 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5046 CCLoc(ColonColonLoc) {
5049 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5050 SourceLocation ColonColonLoc, QualType ObjectType)
5051 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5052 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5056 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5057 NestedNameSpecInfo &IdInfo);
5059 bool BuildCXXNestedNameSpecifier(Scope *S,
5060 NestedNameSpecInfo &IdInfo,
5061 bool EnteringContext,
5063 NamedDecl *ScopeLookupResult,
5064 bool ErrorRecoveryLookup,
5065 bool *IsCorrectedToColon = nullptr);
5067 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5069 /// \param S The scope in which this nested-name-specifier occurs.
5071 /// \param IdInfo Parser information about an identifier in the
5072 /// nested-name-spec.
5074 /// \param EnteringContext Whether we're entering the context nominated by
5075 /// this nested-name-specifier.
5077 /// \param SS The nested-name-specifier, which is both an input
5078 /// parameter (the nested-name-specifier before this type) and an
5079 /// output parameter (containing the full nested-name-specifier,
5080 /// including this new type).
5082 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5083 /// error recovery. In this case do not emit error message.
5085 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5086 /// are allowed. The bool value pointed by this parameter is set to 'true'
5087 /// if the identifier is treated as if it was followed by ':', not '::'.
5089 /// \returns true if an error occurred, false otherwise.
5090 bool ActOnCXXNestedNameSpecifier(Scope *S,
5091 NestedNameSpecInfo &IdInfo,
5092 bool EnteringContext,
5094 bool ErrorRecoveryLookup = false,
5095 bool *IsCorrectedToColon = nullptr);
5097 ExprResult ActOnDecltypeExpression(Expr *E);
5099 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5101 SourceLocation ColonColonLoc);
5103 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5104 NestedNameSpecInfo &IdInfo,
5105 bool EnteringContext);
5107 /// \brief The parser has parsed a nested-name-specifier
5108 /// 'template[opt] template-name < template-args >::'.
5110 /// \param S The scope in which this nested-name-specifier occurs.
5112 /// \param SS The nested-name-specifier, which is both an input
5113 /// parameter (the nested-name-specifier before this type) and an
5114 /// output parameter (containing the full nested-name-specifier,
5115 /// including this new type).
5117 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5118 /// \param TemplateName the template name.
5119 /// \param TemplateNameLoc The location of the template name.
5120 /// \param LAngleLoc The location of the opening angle bracket ('<').
5121 /// \param TemplateArgs The template arguments.
5122 /// \param RAngleLoc The location of the closing angle bracket ('>').
5123 /// \param CCLoc The location of the '::'.
5125 /// \param EnteringContext Whether we're entering the context of the
5126 /// nested-name-specifier.
5129 /// \returns true if an error occurred, false otherwise.
5130 bool ActOnCXXNestedNameSpecifier(Scope *S,
5132 SourceLocation TemplateKWLoc,
5133 TemplateTy TemplateName,
5134 SourceLocation TemplateNameLoc,
5135 SourceLocation LAngleLoc,
5136 ASTTemplateArgsPtr TemplateArgs,
5137 SourceLocation RAngleLoc,
5138 SourceLocation CCLoc,
5139 bool EnteringContext);
5141 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5142 /// that the parser can use later to reconstruct the given
5143 /// nested-name-specifier.
5145 /// \param SS A nested-name-specifier.
5147 /// \returns A pointer containing all of the information in the
5148 /// nested-name-specifier \p SS.
5149 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5151 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5152 /// the nested-name-specifier structure.
5154 /// \param Annotation The annotation pointer, produced by
5155 /// \c SaveNestedNameSpecifierAnnotation().
5157 /// \param AnnotationRange The source range corresponding to the annotation.
5159 /// \param SS The nested-name-specifier that will be updated with the contents
5160 /// of the annotation pointer.
5161 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5162 SourceRange AnnotationRange,
5165 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5167 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5168 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5169 /// After this method is called, according to [C++ 3.4.3p3], names should be
5170 /// looked up in the declarator-id's scope, until the declarator is parsed and
5171 /// ActOnCXXExitDeclaratorScope is called.
5172 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5173 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5175 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5176 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5177 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5178 /// Used to indicate that names should revert to being looked up in the
5180 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5182 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5183 /// initializer for the declaration 'Dcl'.
5184 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5185 /// static data member of class X, names should be looked up in the scope of
5187 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5189 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5190 /// initializer for the declaration 'Dcl'.
5191 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5193 /// \brief Create a new lambda closure type.
5194 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5195 TypeSourceInfo *Info,
5196 bool KnownDependent,
5197 LambdaCaptureDefault CaptureDefault);
5199 /// \brief Start the definition of a lambda expression.
5200 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5201 SourceRange IntroducerRange,
5202 TypeSourceInfo *MethodType,
5203 SourceLocation EndLoc,
5204 ArrayRef<ParmVarDecl *> Params,
5205 bool IsConstexprSpecified);
5207 /// \brief Endow the lambda scope info with the relevant properties.
5208 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5209 CXXMethodDecl *CallOperator,
5210 SourceRange IntroducerRange,
5211 LambdaCaptureDefault CaptureDefault,
5212 SourceLocation CaptureDefaultLoc,
5213 bool ExplicitParams,
5214 bool ExplicitResultType,
5217 /// \brief Perform initialization analysis of the init-capture and perform
5218 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5219 /// not being used to initialize a reference.
5220 ParsedType actOnLambdaInitCaptureInitialization(
5221 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5222 LambdaCaptureInitKind InitKind, Expr *&Init) {
5223 return ParsedType::make(buildLambdaInitCaptureInitialization(
5224 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5226 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5228 bool DirectInit, Expr *&Init);
5230 /// \brief Create a dummy variable within the declcontext of the lambda's
5231 /// call operator, for name lookup purposes for a lambda init capture.
5233 /// CodeGen handles emission of lambda captures, ignoring these dummy
5234 /// variables appropriately.
5235 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5236 QualType InitCaptureType,
5238 unsigned InitStyle, Expr *Init);
5240 /// \brief Build the implicit field for an init-capture.
5241 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5243 /// \brief Note that we have finished the explicit captures for the
5245 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5247 /// \brief Introduce the lambda parameters into scope.
5248 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5250 /// \brief Deduce a block or lambda's return type based on the return
5251 /// statements present in the body.
5252 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5254 /// ActOnStartOfLambdaDefinition - This is called just before we start
5255 /// parsing the body of a lambda; it analyzes the explicit captures and
5256 /// arguments, and sets up various data-structures for the body of the
5258 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5259 Declarator &ParamInfo, Scope *CurScope);
5261 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5262 /// is invoked to pop the information about the lambda.
5263 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5264 bool IsInstantiation = false);
5266 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5267 /// was successfully completed.
5268 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5271 /// \brief Complete a lambda-expression having processed and attached the
5273 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5274 sema::LambdaScopeInfo *LSI);
5276 /// \brief Define the "body" of the conversion from a lambda object to a
5277 /// function pointer.
5279 /// This routine doesn't actually define a sensible body; rather, it fills
5280 /// in the initialization expression needed to copy the lambda object into
5281 /// the block, and IR generation actually generates the real body of the
5282 /// block pointer conversion.
5283 void DefineImplicitLambdaToFunctionPointerConversion(
5284 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5286 /// \brief Define the "body" of the conversion from a lambda object to a
5289 /// This routine doesn't actually define a sensible body; rather, it fills
5290 /// in the initialization expression needed to copy the lambda object into
5291 /// the block, and IR generation actually generates the real body of the
5292 /// block pointer conversion.
5293 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5294 CXXConversionDecl *Conv);
5296 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5297 SourceLocation ConvLocation,
5298 CXXConversionDecl *Conv,
5301 // ParseObjCStringLiteral - Parse Objective-C string literals.
5302 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5303 ArrayRef<Expr *> Strings);
5305 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5307 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5308 /// numeric literal expression. Type of the expression will be "NSNumber *"
5309 /// or "id" if NSNumber is unavailable.
5310 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5311 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5313 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5315 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5316 /// '@' prefixed parenthesized expression. The type of the expression will
5317 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5318 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5319 /// "const char *" or C structure with attribute 'objc_boxable'.
5320 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5322 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5324 ObjCMethodDecl *getterMethod,
5325 ObjCMethodDecl *setterMethod);
5327 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5328 MutableArrayRef<ObjCDictionaryElement> Elements);
5330 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5331 TypeSourceInfo *EncodedTypeInfo,
5332 SourceLocation RParenLoc);
5333 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5334 CXXConversionDecl *Method,
5335 bool HadMultipleCandidates);
5337 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5338 SourceLocation EncodeLoc,
5339 SourceLocation LParenLoc,
5341 SourceLocation RParenLoc);
5343 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5344 ExprResult ParseObjCSelectorExpression(Selector Sel,
5345 SourceLocation AtLoc,
5346 SourceLocation SelLoc,
5347 SourceLocation LParenLoc,
5348 SourceLocation RParenLoc,
5349 bool WarnMultipleSelectors);
5351 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5352 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5353 SourceLocation AtLoc,
5354 SourceLocation ProtoLoc,
5355 SourceLocation LParenLoc,
5356 SourceLocation ProtoIdLoc,
5357 SourceLocation RParenLoc);
5359 //===--------------------------------------------------------------------===//
5362 Decl *ActOnStartLinkageSpecification(Scope *S,
5363 SourceLocation ExternLoc,
5365 SourceLocation LBraceLoc);
5366 Decl *ActOnFinishLinkageSpecification(Scope *S,
5368 SourceLocation RBraceLoc);
5371 //===--------------------------------------------------------------------===//
5374 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5375 const CXXScopeSpec *SS = nullptr);
5376 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5378 bool ActOnAccessSpecifier(AccessSpecifier Access,
5379 SourceLocation ASLoc,
5380 SourceLocation ColonLoc,
5381 AttributeList *Attrs = nullptr);
5383 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5385 MultiTemplateParamsArg TemplateParameterLists,
5386 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5387 InClassInitStyle InitStyle);
5389 void ActOnStartCXXInClassMemberInitializer();
5390 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5391 SourceLocation EqualLoc,
5394 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5397 IdentifierInfo *MemberOrBase,
5398 ParsedType TemplateTypeTy,
5400 SourceLocation IdLoc,
5401 SourceLocation LParenLoc,
5402 ArrayRef<Expr *> Args,
5403 SourceLocation RParenLoc,
5404 SourceLocation EllipsisLoc);
5406 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5409 IdentifierInfo *MemberOrBase,
5410 ParsedType TemplateTypeTy,
5412 SourceLocation IdLoc,
5414 SourceLocation EllipsisLoc);
5416 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5419 IdentifierInfo *MemberOrBase,
5420 ParsedType TemplateTypeTy,
5422 SourceLocation IdLoc,
5424 SourceLocation EllipsisLoc);
5426 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5428 SourceLocation IdLoc);
5430 MemInitResult BuildBaseInitializer(QualType BaseType,
5431 TypeSourceInfo *BaseTInfo,
5433 CXXRecordDecl *ClassDecl,
5434 SourceLocation EllipsisLoc);
5436 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5438 CXXRecordDecl *ClassDecl);
5440 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5441 CXXCtorInitializer *Initializer);
5443 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5444 ArrayRef<CXXCtorInitializer *> Initializers = None);
5446 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5449 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5450 /// mark all the non-trivial destructors of its members and bases as
5452 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5453 CXXRecordDecl *Record);
5455 /// \brief The list of classes whose vtables have been used within
5456 /// this translation unit, and the source locations at which the
5457 /// first use occurred.
5458 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5460 /// \brief The list of vtables that are required but have not yet been
5462 SmallVector<VTableUse, 16> VTableUses;
5464 /// \brief The set of classes whose vtables have been used within
5465 /// this translation unit, and a bit that will be true if the vtable is
5466 /// required to be emitted (otherwise, it should be emitted only if needed
5467 /// by code generation).
5468 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5470 /// \brief Load any externally-stored vtable uses.
5471 void LoadExternalVTableUses();
5473 /// \brief Note that the vtable for the given class was used at the
5475 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5476 bool DefinitionRequired = false);
5478 /// \brief Mark the exception specifications of all virtual member functions
5479 /// in the given class as needed.
5480 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5481 const CXXRecordDecl *RD);
5483 /// MarkVirtualMembersReferenced - Will mark all members of the given
5484 /// CXXRecordDecl referenced.
5485 void MarkVirtualMembersReferenced(SourceLocation Loc,
5486 const CXXRecordDecl *RD);
5488 /// \brief Define all of the vtables that have been used in this
5489 /// translation unit and reference any virtual members used by those
5492 /// \returns true if any work was done, false otherwise.
5493 bool DefineUsedVTables();
5495 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5497 void ActOnMemInitializers(Decl *ConstructorDecl,
5498 SourceLocation ColonLoc,
5499 ArrayRef<CXXCtorInitializer*> MemInits,
5502 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5503 /// ensure that referenceDLLExportedClassMethods is called some point later
5504 /// when all outer classes of Class are complete.
5505 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5507 void referenceDLLExportedClassMethods();
5509 void propagateDLLAttrToBaseClassTemplate(
5510 CXXRecordDecl *Class, Attr *ClassAttr,
5511 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5512 SourceLocation BaseLoc);
5514 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5515 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5517 SourceLocation LBrac,
5518 SourceLocation RBrac,
5519 AttributeList *AttrList);
5520 void ActOnFinishCXXMemberDecls();
5521 void ActOnFinishCXXNonNestedClass(Decl *D);
5523 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5524 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5525 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5526 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5527 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5528 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5529 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5530 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5531 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5532 CachedTokens &Toks);
5533 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5534 bool IsInsideALocalClassWithinATemplateFunction();
5536 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5538 Expr *AssertMessageExpr,
5539 SourceLocation RParenLoc);
5540 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5542 StringLiteral *AssertMessageExpr,
5543 SourceLocation RParenLoc,
5546 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5547 SourceLocation FriendLoc,
5548 TypeSourceInfo *TSInfo);
5549 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5550 MultiTemplateParamsArg TemplateParams);
5551 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5552 MultiTemplateParamsArg TemplateParams);
5554 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5556 void CheckConstructor(CXXConstructorDecl *Constructor);
5557 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5559 bool CheckDestructor(CXXDestructorDecl *Destructor);
5560 void CheckConversionDeclarator(Declarator &D, QualType &R,
5562 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5564 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5565 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5566 const FunctionProtoType *T);
5567 void CheckDelayedMemberExceptionSpecs();
5569 //===--------------------------------------------------------------------===//
5570 // C++ Derived Classes
5573 /// ActOnBaseSpecifier - Parsed a base specifier
5574 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5575 SourceRange SpecifierRange,
5576 bool Virtual, AccessSpecifier Access,
5577 TypeSourceInfo *TInfo,
5578 SourceLocation EllipsisLoc);
5580 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5581 SourceRange SpecifierRange,
5582 ParsedAttributes &Attrs,
5583 bool Virtual, AccessSpecifier Access,
5584 ParsedType basetype,
5585 SourceLocation BaseLoc,
5586 SourceLocation EllipsisLoc);
5588 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5589 MutableArrayRef<CXXBaseSpecifier *> Bases);
5590 void ActOnBaseSpecifiers(Decl *ClassDecl,
5591 MutableArrayRef<CXXBaseSpecifier *> Bases);
5593 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5594 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5595 CXXBasePaths &Paths);
5597 // FIXME: I don't like this name.
5598 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5600 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5601 SourceLocation Loc, SourceRange Range,
5602 CXXCastPath *BasePath = nullptr,
5603 bool IgnoreAccess = false);
5604 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5605 unsigned InaccessibleBaseID,
5606 unsigned AmbigiousBaseConvID,
5607 SourceLocation Loc, SourceRange Range,
5608 DeclarationName Name,
5609 CXXCastPath *BasePath,
5610 bool IgnoreAccess = false);
5612 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5614 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5615 const CXXMethodDecl *Old);
5617 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5618 /// covariant, according to C++ [class.virtual]p5.
5619 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5620 const CXXMethodDecl *Old);
5622 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5623 /// spec is a subset of base spec.
5624 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5625 const CXXMethodDecl *Old);
5627 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5629 /// CheckOverrideControl - Check C++11 override control semantics.
5630 void CheckOverrideControl(NamedDecl *D);
5632 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5633 /// not used in the declaration of an overriding method.
5634 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5636 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5637 /// overrides a virtual member function marked 'final', according to
5638 /// C++11 [class.virtual]p4.
5639 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5640 const CXXMethodDecl *Old);
5643 //===--------------------------------------------------------------------===//
5644 // C++ Access Control
5654 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5655 NamedDecl *PrevMemberDecl,
5656 AccessSpecifier LexicalAS);
5658 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5659 DeclAccessPair FoundDecl);
5660 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5661 DeclAccessPair FoundDecl);
5662 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5663 SourceRange PlacementRange,
5664 CXXRecordDecl *NamingClass,
5665 DeclAccessPair FoundDecl,
5666 bool Diagnose = true);
5667 AccessResult CheckConstructorAccess(SourceLocation Loc,
5668 CXXConstructorDecl *D,
5669 DeclAccessPair FoundDecl,
5670 const InitializedEntity &Entity,
5671 bool IsCopyBindingRefToTemp = false);
5672 AccessResult CheckConstructorAccess(SourceLocation Loc,
5673 CXXConstructorDecl *D,
5674 DeclAccessPair FoundDecl,
5675 const InitializedEntity &Entity,
5676 const PartialDiagnostic &PDiag);
5677 AccessResult CheckDestructorAccess(SourceLocation Loc,
5678 CXXDestructorDecl *Dtor,
5679 const PartialDiagnostic &PDiag,
5680 QualType objectType = QualType());
5681 AccessResult CheckFriendAccess(NamedDecl *D);
5682 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5683 CXXRecordDecl *NamingClass,
5684 DeclAccessPair Found);
5685 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5688 DeclAccessPair FoundDecl);
5689 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5690 DeclAccessPair FoundDecl);
5691 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5692 QualType Base, QualType Derived,
5693 const CXXBasePath &Path,
5695 bool ForceCheck = false,
5696 bool ForceUnprivileged = false);
5697 void CheckLookupAccess(const LookupResult &R);
5698 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5699 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5700 AccessSpecifier access,
5701 QualType objectType);
5703 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5704 const MultiLevelTemplateArgumentList &TemplateArgs);
5705 void PerformDependentDiagnostics(const DeclContext *Pattern,
5706 const MultiLevelTemplateArgumentList &TemplateArgs);
5708 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5710 /// \brief When true, access checking violations are treated as SFINAE
5711 /// failures rather than hard errors.
5712 bool AccessCheckingSFINAE;
5714 enum AbstractDiagSelID {
5718 AbstractVariableType,
5721 AbstractSynthesizedIvarType,
5725 bool isAbstractType(SourceLocation Loc, QualType T);
5726 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5727 TypeDiagnoser &Diagnoser);
5728 template <typename... Ts>
5729 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5730 const Ts &...Args) {
5731 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5732 return RequireNonAbstractType(Loc, T, Diagnoser);
5735 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5737 //===--------------------------------------------------------------------===//
5738 // C++ Overloaded Operators [C++ 13.5]
5741 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5743 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5745 //===--------------------------------------------------------------------===//
5746 // C++ Templates [C++ 14]
5748 void FilterAcceptableTemplateNames(LookupResult &R,
5749 bool AllowFunctionTemplates = true);
5750 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5751 bool AllowFunctionTemplates = true);
5753 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5754 QualType ObjectType, bool EnteringContext,
5755 bool &MemberOfUnknownSpecialization);
5757 TemplateNameKind isTemplateName(Scope *S,
5759 bool hasTemplateKeyword,
5760 UnqualifiedId &Name,
5761 ParsedType ObjectType,
5762 bool EnteringContext,
5763 TemplateTy &Template,
5764 bool &MemberOfUnknownSpecialization);
5766 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5767 SourceLocation IILoc,
5769 const CXXScopeSpec *SS,
5770 TemplateTy &SuggestedTemplate,
5771 TemplateNameKind &SuggestedKind);
5773 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5774 NamedDecl *Instantiation,
5775 bool InstantiatedFromMember,
5776 const NamedDecl *Pattern,
5777 const NamedDecl *PatternDef,
5778 TemplateSpecializationKind TSK,
5779 bool Complain = true);
5781 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5782 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5784 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5785 SourceLocation EllipsisLoc,
5786 SourceLocation KeyLoc,
5787 IdentifierInfo *ParamName,
5788 SourceLocation ParamNameLoc,
5789 unsigned Depth, unsigned Position,
5790 SourceLocation EqualLoc,
5791 ParsedType DefaultArg);
5793 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5794 SourceLocation Loc);
5795 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5797 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5800 SourceLocation EqualLoc,
5802 Decl *ActOnTemplateTemplateParameter(Scope *S,
5803 SourceLocation TmpLoc,
5804 TemplateParameterList *Params,
5805 SourceLocation EllipsisLoc,
5806 IdentifierInfo *ParamName,
5807 SourceLocation ParamNameLoc,
5810 SourceLocation EqualLoc,
5811 ParsedTemplateArgument DefaultArg);
5813 TemplateParameterList *
5814 ActOnTemplateParameterList(unsigned Depth,
5815 SourceLocation ExportLoc,
5816 SourceLocation TemplateLoc,
5817 SourceLocation LAngleLoc,
5818 ArrayRef<Decl *> Params,
5819 SourceLocation RAngleLoc,
5820 Expr *RequiresClause);
5822 /// \brief The context in which we are checking a template parameter list.
5823 enum TemplateParamListContext {
5826 TPC_FunctionTemplate,
5827 TPC_ClassTemplateMember,
5828 TPC_FriendClassTemplate,
5829 TPC_FriendFunctionTemplate,
5830 TPC_FriendFunctionTemplateDefinition,
5831 TPC_TypeAliasTemplate
5834 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5835 TemplateParameterList *OldParams,
5836 TemplateParamListContext TPC);
5837 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5838 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5839 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5840 ArrayRef<TemplateParameterList *> ParamLists,
5841 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5843 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5844 SourceLocation KWLoc, CXXScopeSpec &SS,
5845 IdentifierInfo *Name, SourceLocation NameLoc,
5846 AttributeList *Attr,
5847 TemplateParameterList *TemplateParams,
5849 SourceLocation ModulePrivateLoc,
5850 SourceLocation FriendLoc,
5851 unsigned NumOuterTemplateParamLists,
5852 TemplateParameterList **OuterTemplateParamLists,
5853 SkipBodyInfo *SkipBody = nullptr);
5855 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5857 SourceLocation Loc);
5859 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5860 TemplateArgumentListInfo &Out);
5862 void NoteAllFoundTemplates(TemplateName Name);
5864 QualType CheckTemplateIdType(TemplateName Template,
5865 SourceLocation TemplateLoc,
5866 TemplateArgumentListInfo &TemplateArgs);
5869 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5870 TemplateTy Template, SourceLocation TemplateLoc,
5871 SourceLocation LAngleLoc,
5872 ASTTemplateArgsPtr TemplateArgs,
5873 SourceLocation RAngleLoc,
5874 bool IsCtorOrDtorName = false);
5876 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5877 /// such as \c class T::template apply<U>.
5878 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5879 TypeSpecifierType TagSpec,
5880 SourceLocation TagLoc,
5882 SourceLocation TemplateKWLoc,
5883 TemplateTy TemplateD,
5884 SourceLocation TemplateLoc,
5885 SourceLocation LAngleLoc,
5886 ASTTemplateArgsPtr TemplateArgsIn,
5887 SourceLocation RAngleLoc);
5889 DeclResult ActOnVarTemplateSpecialization(
5890 Scope *S, Declarator &D, TypeSourceInfo *DI,
5891 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5892 StorageClass SC, bool IsPartialSpecialization);
5894 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5895 SourceLocation TemplateLoc,
5896 SourceLocation TemplateNameLoc,
5897 const TemplateArgumentListInfo &TemplateArgs);
5899 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5900 const DeclarationNameInfo &NameInfo,
5901 VarTemplateDecl *Template,
5902 SourceLocation TemplateLoc,
5903 const TemplateArgumentListInfo *TemplateArgs);
5905 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5906 SourceLocation TemplateKWLoc,
5909 const TemplateArgumentListInfo *TemplateArgs);
5911 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5912 SourceLocation TemplateKWLoc,
5913 const DeclarationNameInfo &NameInfo,
5914 const TemplateArgumentListInfo *TemplateArgs);
5916 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5918 SourceLocation TemplateKWLoc,
5919 UnqualifiedId &Name,
5920 ParsedType ObjectType,
5921 bool EnteringContext,
5922 TemplateTy &Template);
5925 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5926 SourceLocation KWLoc,
5927 SourceLocation ModulePrivateLoc,
5928 TemplateIdAnnotation &TemplateId,
5929 AttributeList *Attr,
5930 MultiTemplateParamsArg TemplateParameterLists,
5931 SkipBodyInfo *SkipBody = nullptr);
5933 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
5934 TemplateDecl *PrimaryTemplate,
5935 unsigned NumExplicitArgs,
5936 ArrayRef<TemplateArgument> Args);
5937 void CheckTemplatePartialSpecialization(
5938 ClassTemplatePartialSpecializationDecl *Partial);
5939 void CheckTemplatePartialSpecialization(
5940 VarTemplatePartialSpecializationDecl *Partial);
5942 Decl *ActOnTemplateDeclarator(Scope *S,
5943 MultiTemplateParamsArg TemplateParameterLists,
5947 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5948 TemplateSpecializationKind NewTSK,
5949 NamedDecl *PrevDecl,
5950 TemplateSpecializationKind PrevTSK,
5951 SourceLocation PrevPtOfInstantiation,
5954 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5955 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5956 LookupResult &Previous);
5958 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5959 TemplateArgumentListInfo *ExplicitTemplateArgs,
5960 LookupResult &Previous);
5961 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5964 ActOnExplicitInstantiation(Scope *S,
5965 SourceLocation ExternLoc,
5966 SourceLocation TemplateLoc,
5968 SourceLocation KWLoc,
5969 const CXXScopeSpec &SS,
5970 TemplateTy Template,
5971 SourceLocation TemplateNameLoc,
5972 SourceLocation LAngleLoc,
5973 ASTTemplateArgsPtr TemplateArgs,
5974 SourceLocation RAngleLoc,
5975 AttributeList *Attr);
5978 ActOnExplicitInstantiation(Scope *S,
5979 SourceLocation ExternLoc,
5980 SourceLocation TemplateLoc,
5982 SourceLocation KWLoc,
5984 IdentifierInfo *Name,
5985 SourceLocation NameLoc,
5986 AttributeList *Attr);
5988 DeclResult ActOnExplicitInstantiation(Scope *S,
5989 SourceLocation ExternLoc,
5990 SourceLocation TemplateLoc,
5994 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5995 SourceLocation TemplateLoc,
5996 SourceLocation RAngleLoc,
5998 SmallVectorImpl<TemplateArgument>
6000 bool &HasDefaultArg);
6002 /// \brief Specifies the context in which a particular template
6003 /// argument is being checked.
6004 enum CheckTemplateArgumentKind {
6005 /// \brief The template argument was specified in the code or was
6006 /// instantiated with some deduced template arguments.
6009 /// \brief The template argument was deduced via template argument
6013 /// \brief The template argument was deduced from an array bound
6014 /// via template argument deduction.
6015 CTAK_DeducedFromArrayBound
6018 bool CheckTemplateArgument(NamedDecl *Param,
6019 TemplateArgumentLoc &Arg,
6020 NamedDecl *Template,
6021 SourceLocation TemplateLoc,
6022 SourceLocation RAngleLoc,
6023 unsigned ArgumentPackIndex,
6024 SmallVectorImpl<TemplateArgument> &Converted,
6025 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6027 /// \brief Check that the given template arguments can be be provided to
6028 /// the given template, converting the arguments along the way.
6030 /// \param Template The template to which the template arguments are being
6033 /// \param TemplateLoc The location of the template name in the source.
6035 /// \param TemplateArgs The list of template arguments. If the template is
6036 /// a template template parameter, this function may extend the set of
6037 /// template arguments to also include substituted, defaulted template
6040 /// \param PartialTemplateArgs True if the list of template arguments is
6041 /// intentionally partial, e.g., because we're checking just the initial
6042 /// set of template arguments.
6044 /// \param Converted Will receive the converted, canonicalized template
6047 /// \returns true if an error occurred, false otherwise.
6048 bool CheckTemplateArgumentList(TemplateDecl *Template,
6049 SourceLocation TemplateLoc,
6050 TemplateArgumentListInfo &TemplateArgs,
6051 bool PartialTemplateArgs,
6052 SmallVectorImpl<TemplateArgument> &Converted);
6054 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6055 TemplateArgumentLoc &Arg,
6056 SmallVectorImpl<TemplateArgument> &Converted);
6058 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6059 TypeSourceInfo *Arg);
6060 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6061 QualType InstantiatedParamType, Expr *Arg,
6062 TemplateArgument &Converted,
6063 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6064 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6065 TemplateArgumentLoc &Arg,
6066 unsigned ArgumentPackIndex);
6069 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6071 SourceLocation Loc);
6073 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6074 SourceLocation Loc);
6076 /// \brief Enumeration describing how template parameter lists are compared
6078 enum TemplateParameterListEqualKind {
6079 /// \brief We are matching the template parameter lists of two templates
6080 /// that might be redeclarations.
6083 /// template<typename T> struct X;
6084 /// template<typename T> struct X;
6088 /// \brief We are matching the template parameter lists of two template
6089 /// template parameters as part of matching the template parameter lists
6090 /// of two templates that might be redeclarations.
6093 /// template<template<int I> class TT> struct X;
6094 /// template<template<int Value> class Other> struct X;
6096 TPL_TemplateTemplateParmMatch,
6098 /// \brief We are matching the template parameter lists of a template
6099 /// template argument against the template parameter lists of a template
6100 /// template parameter.
6103 /// template<template<int Value> class Metafun> struct X;
6104 /// template<int Value> struct integer_c;
6105 /// X<integer_c> xic;
6107 TPL_TemplateTemplateArgumentMatch
6110 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6111 TemplateParameterList *Old,
6113 TemplateParameterListEqualKind Kind,
6114 SourceLocation TemplateArgLoc
6115 = SourceLocation());
6117 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6119 /// \brief Called when the parser has parsed a C++ typename
6120 /// specifier, e.g., "typename T::type".
6122 /// \param S The scope in which this typename type occurs.
6123 /// \param TypenameLoc the location of the 'typename' keyword
6124 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6125 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6126 /// \param IdLoc the location of the identifier.
6128 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6129 const CXXScopeSpec &SS, const IdentifierInfo &II,
6130 SourceLocation IdLoc);
6132 /// \brief Called when the parser has parsed a C++ typename
6133 /// specifier that ends in a template-id, e.g.,
6134 /// "typename MetaFun::template apply<T1, T2>".
6136 /// \param S The scope in which this typename type occurs.
6137 /// \param TypenameLoc the location of the 'typename' keyword
6138 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6139 /// \param TemplateLoc the location of the 'template' keyword, if any.
6140 /// \param TemplateName The template name.
6141 /// \param TemplateNameLoc The location of the template name.
6142 /// \param LAngleLoc The location of the opening angle bracket ('<').
6143 /// \param TemplateArgs The template arguments.
6144 /// \param RAngleLoc The location of the closing angle bracket ('>').
6146 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6147 const CXXScopeSpec &SS,
6148 SourceLocation TemplateLoc,
6149 TemplateTy TemplateName,
6150 SourceLocation TemplateNameLoc,
6151 SourceLocation LAngleLoc,
6152 ASTTemplateArgsPtr TemplateArgs,
6153 SourceLocation RAngleLoc);
6155 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6156 SourceLocation KeywordLoc,
6157 NestedNameSpecifierLoc QualifierLoc,
6158 const IdentifierInfo &II,
6159 SourceLocation IILoc);
6161 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6163 DeclarationName Name);
6164 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6166 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6167 bool RebuildTemplateParamsInCurrentInstantiation(
6168 TemplateParameterList *Params);
6171 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6172 const TemplateArgumentList &Args);
6175 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6176 const TemplateArgument *Args,
6179 //===--------------------------------------------------------------------===//
6180 // C++ Variadic Templates (C++0x [temp.variadic])
6181 //===--------------------------------------------------------------------===//
6183 /// Determine whether an unexpanded parameter pack might be permitted in this
6184 /// location. Useful for error recovery.
6185 bool isUnexpandedParameterPackPermitted();
6187 /// \brief The context in which an unexpanded parameter pack is
6188 /// being diagnosed.
6190 /// Note that the values of this enumeration line up with the first
6191 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6192 enum UnexpandedParameterPackContext {
6193 /// \brief An arbitrary expression.
6194 UPPC_Expression = 0,
6196 /// \brief The base type of a class type.
6199 /// \brief The type of an arbitrary declaration.
6200 UPPC_DeclarationType,
6202 /// \brief The type of a data member.
6203 UPPC_DataMemberType,
6205 /// \brief The size of a bit-field.
6208 /// \brief The expression in a static assertion.
6209 UPPC_StaticAssertExpression,
6211 /// \brief The fixed underlying type of an enumeration.
6212 UPPC_FixedUnderlyingType,
6214 /// \brief The enumerator value.
6215 UPPC_EnumeratorValue,
6217 /// \brief A using declaration.
6218 UPPC_UsingDeclaration,
6220 /// \brief A friend declaration.
6221 UPPC_FriendDeclaration,
6223 /// \brief A declaration qualifier.
6224 UPPC_DeclarationQualifier,
6226 /// \brief An initializer.
6229 /// \brief A default argument.
6230 UPPC_DefaultArgument,
6232 /// \brief The type of a non-type template parameter.
6233 UPPC_NonTypeTemplateParameterType,
6235 /// \brief The type of an exception.
6238 /// \brief Partial specialization.
6239 UPPC_PartialSpecialization,
6241 /// \brief Microsoft __if_exists.
6244 /// \brief Microsoft __if_not_exists.
6247 /// \brief Lambda expression.
6250 /// \brief Block expression,
6254 /// \brief Diagnose unexpanded parameter packs.
6256 /// \param Loc The location at which we should emit the diagnostic.
6258 /// \param UPPC The context in which we are diagnosing unexpanded
6259 /// parameter packs.
6261 /// \param Unexpanded the set of unexpanded parameter packs.
6263 /// \returns true if an error occurred, false otherwise.
6264 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6265 UnexpandedParameterPackContext UPPC,
6266 ArrayRef<UnexpandedParameterPack> Unexpanded);
6268 /// \brief If the given type contains an unexpanded parameter pack,
6269 /// diagnose the error.
6271 /// \param Loc The source location where a diagnostc should be emitted.
6273 /// \param T The type that is being checked for unexpanded parameter
6276 /// \returns true if an error occurred, false otherwise.
6277 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6278 UnexpandedParameterPackContext UPPC);
6280 /// \brief If the given expression contains an unexpanded parameter
6281 /// pack, diagnose the error.
6283 /// \param E The expression that is being checked for unexpanded
6284 /// parameter packs.
6286 /// \returns true if an error occurred, false otherwise.
6287 bool DiagnoseUnexpandedParameterPack(Expr *E,
6288 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6290 /// \brief If the given nested-name-specifier contains an unexpanded
6291 /// parameter pack, diagnose the error.
6293 /// \param SS The nested-name-specifier that is being checked for
6294 /// unexpanded parameter packs.
6296 /// \returns true if an error occurred, false otherwise.
6297 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6298 UnexpandedParameterPackContext UPPC);
6300 /// \brief If the given name contains an unexpanded parameter pack,
6301 /// diagnose the error.
6303 /// \param NameInfo The name (with source location information) that
6304 /// is being checked for unexpanded parameter packs.
6306 /// \returns true if an error occurred, false otherwise.
6307 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6308 UnexpandedParameterPackContext UPPC);
6310 /// \brief If the given template name contains an unexpanded parameter pack,
6311 /// diagnose the error.
6313 /// \param Loc The location of the template name.
6315 /// \param Template The template name that is being checked for unexpanded
6316 /// parameter packs.
6318 /// \returns true if an error occurred, false otherwise.
6319 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6320 TemplateName Template,
6321 UnexpandedParameterPackContext UPPC);
6323 /// \brief If the given template argument contains an unexpanded parameter
6324 /// pack, diagnose the error.
6326 /// \param Arg The template argument that is being checked for unexpanded
6327 /// parameter packs.
6329 /// \returns true if an error occurred, false otherwise.
6330 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6331 UnexpandedParameterPackContext UPPC);
6333 /// \brief Collect the set of unexpanded parameter packs within the given
6334 /// template argument.
6336 /// \param Arg The template argument that will be traversed to find
6337 /// unexpanded parameter packs.
6338 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6339 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6341 /// \brief Collect the set of unexpanded parameter packs within the given
6342 /// template argument.
6344 /// \param Arg The template argument that will be traversed to find
6345 /// unexpanded parameter packs.
6346 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6347 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6349 /// \brief Collect the set of unexpanded parameter packs within the given
6352 /// \param T The type that will be traversed to find
6353 /// unexpanded parameter packs.
6354 void collectUnexpandedParameterPacks(QualType T,
6355 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6357 /// \brief Collect the set of unexpanded parameter packs within the given
6360 /// \param TL The type that will be traversed to find
6361 /// unexpanded parameter packs.
6362 void collectUnexpandedParameterPacks(TypeLoc TL,
6363 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6365 /// \brief Collect the set of unexpanded parameter packs within the given
6366 /// nested-name-specifier.
6368 /// \param NNS The nested-name-specifier that will be traversed to find
6369 /// unexpanded parameter packs.
6370 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6371 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6373 /// \brief Collect the set of unexpanded parameter packs within the given
6376 /// \param NameInfo The name that will be traversed to find
6377 /// unexpanded parameter packs.
6378 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6379 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6381 /// \brief Invoked when parsing a template argument followed by an
6382 /// ellipsis, which creates a pack expansion.
6384 /// \param Arg The template argument preceding the ellipsis, which
6385 /// may already be invalid.
6387 /// \param EllipsisLoc The location of the ellipsis.
6388 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6389 SourceLocation EllipsisLoc);
6391 /// \brief Invoked when parsing a type followed by an ellipsis, which
6392 /// creates a pack expansion.
6394 /// \param Type The type preceding the ellipsis, which will become
6395 /// the pattern of the pack expansion.
6397 /// \param EllipsisLoc The location of the ellipsis.
6398 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6400 /// \brief Construct a pack expansion type from the pattern of the pack
6402 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6403 SourceLocation EllipsisLoc,
6404 Optional<unsigned> NumExpansions);
6406 /// \brief Construct a pack expansion type from the pattern of the pack
6408 QualType CheckPackExpansion(QualType Pattern,
6409 SourceRange PatternRange,
6410 SourceLocation EllipsisLoc,
6411 Optional<unsigned> NumExpansions);
6413 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6414 /// creates a pack expansion.
6416 /// \param Pattern The expression preceding the ellipsis, which will become
6417 /// the pattern of the pack expansion.
6419 /// \param EllipsisLoc The location of the ellipsis.
6420 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6422 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6423 /// creates a pack expansion.
6425 /// \param Pattern The expression preceding the ellipsis, which will become
6426 /// the pattern of the pack expansion.
6428 /// \param EllipsisLoc The location of the ellipsis.
6429 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6430 Optional<unsigned> NumExpansions);
6432 /// \brief Determine whether we could expand a pack expansion with the
6433 /// given set of parameter packs into separate arguments by repeatedly
6434 /// transforming the pattern.
6436 /// \param EllipsisLoc The location of the ellipsis that identifies the
6439 /// \param PatternRange The source range that covers the entire pattern of
6440 /// the pack expansion.
6442 /// \param Unexpanded The set of unexpanded parameter packs within the
6445 /// \param ShouldExpand Will be set to \c true if the transformer should
6446 /// expand the corresponding pack expansions into separate arguments. When
6447 /// set, \c NumExpansions must also be set.
6449 /// \param RetainExpansion Whether the caller should add an unexpanded
6450 /// pack expansion after all of the expanded arguments. This is used
6451 /// when extending explicitly-specified template argument packs per
6452 /// C++0x [temp.arg.explicit]p9.
6454 /// \param NumExpansions The number of separate arguments that will be in
6455 /// the expanded form of the corresponding pack expansion. This is both an
6456 /// input and an output parameter, which can be set by the caller if the
6457 /// number of expansions is known a priori (e.g., due to a prior substitution)
6458 /// and will be set by the callee when the number of expansions is known.
6459 /// The callee must set this value when \c ShouldExpand is \c true; it may
6460 /// set this value in other cases.
6462 /// \returns true if an error occurred (e.g., because the parameter packs
6463 /// are to be instantiated with arguments of different lengths), false
6464 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6466 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6467 SourceRange PatternRange,
6468 ArrayRef<UnexpandedParameterPack> Unexpanded,
6469 const MultiLevelTemplateArgumentList &TemplateArgs,
6471 bool &RetainExpansion,
6472 Optional<unsigned> &NumExpansions);
6474 /// \brief Determine the number of arguments in the given pack expansion
6477 /// This routine assumes that the number of arguments in the expansion is
6478 /// consistent across all of the unexpanded parameter packs in its pattern.
6480 /// Returns an empty Optional if the type can't be expanded.
6481 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6482 const MultiLevelTemplateArgumentList &TemplateArgs);
6484 /// \brief Determine whether the given declarator contains any unexpanded
6485 /// parameter packs.
6487 /// This routine is used by the parser to disambiguate function declarators
6488 /// with an ellipsis prior to the ')', e.g.,
6494 /// To determine whether we have an (unnamed) function parameter pack or
6495 /// a variadic function.
6497 /// \returns true if the declarator contains any unexpanded parameter packs,
6498 /// false otherwise.
6499 bool containsUnexpandedParameterPacks(Declarator &D);
6501 /// \brief Returns the pattern of the pack expansion for a template argument.
6503 /// \param OrigLoc The template argument to expand.
6505 /// \param Ellipsis Will be set to the location of the ellipsis.
6507 /// \param NumExpansions Will be set to the number of expansions that will
6508 /// be generated from this pack expansion, if known a priori.
6509 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6510 TemplateArgumentLoc OrigLoc,
6511 SourceLocation &Ellipsis,
6512 Optional<unsigned> &NumExpansions) const;
6514 /// Given a template argument that contains an unexpanded parameter pack, but
6515 /// which has already been substituted, attempt to determine the number of
6516 /// elements that will be produced once this argument is fully-expanded.
6518 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6519 /// avoid actually expanding the pack where possible.
6520 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6522 //===--------------------------------------------------------------------===//
6523 // C++ Template Argument Deduction (C++ [temp.deduct])
6524 //===--------------------------------------------------------------------===//
6526 /// Adjust the type \p ArgFunctionType to match the calling convention,
6527 /// noreturn, and optionally the exception specification of \p FunctionType.
6528 /// Deduction often wants to ignore these properties when matching function
6530 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6531 bool AdjustExceptionSpec = false);
6533 /// \brief Describes the result of template argument deduction.
6535 /// The TemplateDeductionResult enumeration describes the result of
6536 /// template argument deduction, as returned from
6537 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6538 /// structure provides additional information about the results of
6539 /// template argument deduction, e.g., the deduced template argument
6540 /// list (if successful) or the specific template parameters or
6541 /// deduced arguments that were involved in the failure.
6542 enum TemplateDeductionResult {
6543 /// \brief Template argument deduction was successful.
6545 /// \brief The declaration was invalid; do nothing.
6547 /// \brief Template argument deduction exceeded the maximum template
6548 /// instantiation depth (which has already been diagnosed).
6549 TDK_InstantiationDepth,
6550 /// \brief Template argument deduction did not deduce a value
6551 /// for every template parameter.
6553 /// \brief Template argument deduction produced inconsistent
6554 /// deduced values for the given template parameter.
6556 /// \brief Template argument deduction failed due to inconsistent
6557 /// cv-qualifiers on a template parameter type that would
6558 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6559 /// but were given a non-const "X".
6561 /// \brief Substitution of the deduced template argument values
6562 /// resulted in an error.
6563 TDK_SubstitutionFailure,
6564 /// \brief After substituting deduced template arguments, a dependent
6565 /// parameter type did not match the corresponding argument.
6566 TDK_DeducedMismatch,
6567 /// \brief A non-depnedent component of the parameter did not match the
6568 /// corresponding component of the argument.
6569 TDK_NonDeducedMismatch,
6570 /// \brief When performing template argument deduction for a function
6571 /// template, there were too many call arguments.
6572 TDK_TooManyArguments,
6573 /// \brief When performing template argument deduction for a function
6574 /// template, there were too few call arguments.
6575 TDK_TooFewArguments,
6576 /// \brief The explicitly-specified template arguments were not valid
6577 /// template arguments for the given template.
6578 TDK_InvalidExplicitArguments,
6579 /// \brief The arguments included an overloaded function name that could
6580 /// not be resolved to a suitable function.
6581 TDK_FailedOverloadResolution,
6582 /// \brief Deduction failed; that's all we know.
6583 TDK_MiscellaneousDeductionFailure,
6584 /// \brief CUDA Target attributes do not match.
6585 TDK_CUDATargetMismatch
6588 TemplateDeductionResult
6589 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6590 const TemplateArgumentList &TemplateArgs,
6591 sema::TemplateDeductionInfo &Info);
6593 TemplateDeductionResult
6594 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6595 const TemplateArgumentList &TemplateArgs,
6596 sema::TemplateDeductionInfo &Info);
6598 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6599 FunctionTemplateDecl *FunctionTemplate,
6600 TemplateArgumentListInfo &ExplicitTemplateArgs,
6601 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6602 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6603 sema::TemplateDeductionInfo &Info);
6605 /// brief A function argument from which we performed template argument
6606 // deduction for a call.
6607 struct OriginalCallArg {
6608 OriginalCallArg(QualType OriginalParamType,
6610 QualType OriginalArgType)
6611 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6612 OriginalArgType(OriginalArgType) { }
6614 QualType OriginalParamType;
6616 QualType OriginalArgType;
6619 TemplateDeductionResult
6620 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6621 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6622 unsigned NumExplicitlySpecified,
6623 FunctionDecl *&Specialization,
6624 sema::TemplateDeductionInfo &Info,
6625 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6626 bool PartialOverloading = false);
6628 TemplateDeductionResult
6629 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6630 TemplateArgumentListInfo *ExplicitTemplateArgs,
6631 ArrayRef<Expr *> Args,
6632 FunctionDecl *&Specialization,
6633 sema::TemplateDeductionInfo &Info,
6634 bool PartialOverloading = false);
6636 TemplateDeductionResult
6637 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6638 TemplateArgumentListInfo *ExplicitTemplateArgs,
6639 QualType ArgFunctionType,
6640 FunctionDecl *&Specialization,
6641 sema::TemplateDeductionInfo &Info,
6642 bool IsAddressOfFunction = false);
6644 TemplateDeductionResult
6645 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6647 CXXConversionDecl *&Specialization,
6648 sema::TemplateDeductionInfo &Info);
6650 TemplateDeductionResult
6651 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6652 TemplateArgumentListInfo *ExplicitTemplateArgs,
6653 FunctionDecl *&Specialization,
6654 sema::TemplateDeductionInfo &Info,
6655 bool IsAddressOfFunction = false);
6657 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6658 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6659 /// \brief Substitute Replacement for auto in TypeWithAuto
6660 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6661 QualType Replacement);
6663 /// \brief Result type of DeduceAutoType.
6664 enum DeduceAutoResult {
6667 DAR_FailedAlreadyDiagnosed
6671 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6672 Optional<unsigned> DependentDeductionDepth = None);
6674 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6675 Optional<unsigned> DependentDeductionDepth = None);
6676 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6677 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6678 bool Diagnose = true);
6680 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6681 QualType Type, TypeSourceInfo *TSI,
6682 SourceRange Range, bool DirectInit,
6685 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6687 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6688 SourceLocation ReturnLoc,
6689 Expr *&RetExpr, AutoType *AT);
6691 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6692 FunctionTemplateDecl *FT2,
6694 TemplatePartialOrderingContext TPOC,
6695 unsigned NumCallArguments1,
6696 unsigned NumCallArguments2);
6697 UnresolvedSetIterator
6698 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6699 TemplateSpecCandidateSet &FailedCandidates,
6701 const PartialDiagnostic &NoneDiag,
6702 const PartialDiagnostic &AmbigDiag,
6703 const PartialDiagnostic &CandidateDiag,
6704 bool Complain = true, QualType TargetType = QualType());
6706 ClassTemplatePartialSpecializationDecl *
6707 getMoreSpecializedPartialSpecialization(
6708 ClassTemplatePartialSpecializationDecl *PS1,
6709 ClassTemplatePartialSpecializationDecl *PS2,
6710 SourceLocation Loc);
6712 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6713 sema::TemplateDeductionInfo &Info);
6715 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6716 VarTemplatePartialSpecializationDecl *PS1,
6717 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6719 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6720 sema::TemplateDeductionInfo &Info);
6722 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6723 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6725 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6728 llvm::SmallBitVector &Used);
6729 void MarkDeducedTemplateParameters(
6730 const FunctionTemplateDecl *FunctionTemplate,
6731 llvm::SmallBitVector &Deduced) {
6732 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6734 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6735 const FunctionTemplateDecl *FunctionTemplate,
6736 llvm::SmallBitVector &Deduced);
6738 //===--------------------------------------------------------------------===//
6739 // C++ Template Instantiation
6742 MultiLevelTemplateArgumentList
6743 getTemplateInstantiationArgs(NamedDecl *D,
6744 const TemplateArgumentList *Innermost = nullptr,
6745 bool RelativeToPrimary = false,
6746 const FunctionDecl *Pattern = nullptr);
6748 /// \brief A template instantiation that is currently in progress.
6749 struct ActiveTemplateInstantiation {
6750 /// \brief The kind of template instantiation we are performing
6751 enum InstantiationKind {
6752 /// We are instantiating a template declaration. The entity is
6753 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6754 TemplateInstantiation,
6756 /// We are instantiating a default argument for a template
6757 /// parameter. The Entity is the template parameter whose argument is
6758 /// being instantiated, the Template is the template, and the
6759 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6761 DefaultTemplateArgumentInstantiation,
6763 /// We are instantiating a default argument for a function.
6764 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6765 /// provides the template arguments as specified.
6766 DefaultFunctionArgumentInstantiation,
6768 /// We are substituting explicit template arguments provided for
6769 /// a function template. The entity is a FunctionTemplateDecl.
6770 ExplicitTemplateArgumentSubstitution,
6772 /// We are substituting template argument determined as part of
6773 /// template argument deduction for either a class template
6774 /// partial specialization or a function template. The
6775 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6777 DeducedTemplateArgumentSubstitution,
6779 /// We are substituting prior template arguments into a new
6780 /// template parameter. The template parameter itself is either a
6781 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6782 PriorTemplateArgumentSubstitution,
6784 /// We are checking the validity of a default template argument that
6785 /// has been used when naming a template-id.
6786 DefaultTemplateArgumentChecking,
6788 /// We are instantiating the exception specification for a function
6789 /// template which was deferred until it was needed.
6790 ExceptionSpecInstantiation
6793 /// \brief The point of instantiation within the source code.
6794 SourceLocation PointOfInstantiation;
6796 /// \brief The template (or partial specialization) in which we are
6797 /// performing the instantiation, for substitutions of prior template
6799 NamedDecl *Template;
6801 /// \brief The entity that is being instantiated.
6804 /// \brief The list of template arguments we are substituting, if they
6805 /// are not part of the entity.
6806 const TemplateArgument *TemplateArgs;
6808 /// \brief The number of template arguments in TemplateArgs.
6809 unsigned NumTemplateArgs;
6811 ArrayRef<TemplateArgument> template_arguments() const {
6812 return {TemplateArgs, NumTemplateArgs};
6815 /// \brief The template deduction info object associated with the
6816 /// substitution or checking of explicit or deduced template arguments.
6817 sema::TemplateDeductionInfo *DeductionInfo;
6819 /// \brief The source range that covers the construct that cause
6820 /// the instantiation, e.g., the template-id that causes a class
6821 /// template instantiation.
6822 SourceRange InstantiationRange;
6824 ActiveTemplateInstantiation()
6825 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6826 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6828 /// \brief Determines whether this template is an actual instantiation
6829 /// that should be counted toward the maximum instantiation depth.
6830 bool isInstantiationRecord() const;
6832 friend bool operator==(const ActiveTemplateInstantiation &X,
6833 const ActiveTemplateInstantiation &Y) {
6834 if (X.Kind != Y.Kind)
6837 if (X.Entity != Y.Entity)
6841 case TemplateInstantiation:
6842 case ExceptionSpecInstantiation:
6845 case PriorTemplateArgumentSubstitution:
6846 case DefaultTemplateArgumentChecking:
6847 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6849 case DefaultTemplateArgumentInstantiation:
6850 case ExplicitTemplateArgumentSubstitution:
6851 case DeducedTemplateArgumentSubstitution:
6852 case DefaultFunctionArgumentInstantiation:
6853 return X.TemplateArgs == Y.TemplateArgs;
6857 llvm_unreachable("Invalid InstantiationKind!");
6860 friend bool operator!=(const ActiveTemplateInstantiation &X,
6861 const ActiveTemplateInstantiation &Y) {
6866 /// \brief List of active template instantiations.
6868 /// This vector is treated as a stack. As one template instantiation
6869 /// requires another template instantiation, additional
6870 /// instantiations are pushed onto the stack up to a
6871 /// user-configurable limit LangOptions::InstantiationDepth.
6872 SmallVector<ActiveTemplateInstantiation, 16>
6873 ActiveTemplateInstantiations;
6875 /// Specializations whose definitions are currently being instantiated.
6876 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
6878 /// \brief Extra modules inspected when performing a lookup during a template
6879 /// instantiation. Computed lazily.
6880 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6882 /// \brief Cache of additional modules that should be used for name lookup
6883 /// within the current template instantiation. Computed lazily; use
6884 /// getLookupModules() to get a complete set.
6885 llvm::DenseSet<Module*> LookupModulesCache;
6887 /// \brief Get the set of additional modules that should be checked during
6888 /// name lookup. A module and its imports become visible when instanting a
6889 /// template defined within it.
6890 llvm::DenseSet<Module*> &getLookupModules();
6892 /// \brief Map from the most recent declaration of a namespace to the most
6893 /// recent visible declaration of that namespace.
6894 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
6896 /// \brief Whether we are in a SFINAE context that is not associated with
6897 /// template instantiation.
6899 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6900 /// of a template instantiation or template argument deduction.
6901 bool InNonInstantiationSFINAEContext;
6903 /// \brief The number of ActiveTemplateInstantiation entries in
6904 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6905 /// therefore, should not be counted as part of the instantiation depth.
6906 unsigned NonInstantiationEntries;
6908 /// \brief The last template from which a template instantiation
6909 /// error or warning was produced.
6911 /// This value is used to suppress printing of redundant template
6912 /// instantiation backtraces when there are multiple errors in the
6913 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6914 /// to implement it anywhere else.
6915 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6917 /// \brief The current index into pack expansion arguments that will be
6918 /// used for substitution of parameter packs.
6920 /// The pack expansion index will be -1 to indicate that parameter packs
6921 /// should be instantiated as themselves. Otherwise, the index specifies
6922 /// which argument within the parameter pack will be used for substitution.
6923 int ArgumentPackSubstitutionIndex;
6925 /// \brief RAII object used to change the argument pack substitution index
6926 /// within a \c Sema object.
6928 /// See \c ArgumentPackSubstitutionIndex for more information.
6929 class ArgumentPackSubstitutionIndexRAII {
6931 int OldSubstitutionIndex;
6934 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6935 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6936 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6939 ~ArgumentPackSubstitutionIndexRAII() {
6940 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6944 friend class ArgumentPackSubstitutionRAII;
6946 /// \brief For each declaration that involved template argument deduction, the
6947 /// set of diagnostics that were suppressed during that template argument
6950 /// FIXME: Serialize this structure to the AST file.
6951 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6952 SuppressedDiagnosticsMap;
6953 SuppressedDiagnosticsMap SuppressedDiagnostics;
6955 /// \brief A stack object to be created when performing template
6958 /// Construction of an object of type \c InstantiatingTemplate
6959 /// pushes the current instantiation onto the stack of active
6960 /// instantiations. If the size of this stack exceeds the maximum
6961 /// number of recursive template instantiations, construction
6962 /// produces an error and evaluates true.
6964 /// Destruction of this object will pop the named instantiation off
6966 struct InstantiatingTemplate {
6967 /// \brief Note that we are instantiating a class template,
6968 /// function template, variable template, alias template,
6969 /// or a member thereof.
6970 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6972 SourceRange InstantiationRange = SourceRange());
6974 struct ExceptionSpecification {};
6975 /// \brief Note that we are instantiating an exception specification
6976 /// of a function template.
6977 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6978 FunctionDecl *Entity, ExceptionSpecification,
6979 SourceRange InstantiationRange = SourceRange());
6981 /// \brief Note that we are instantiating a default argument in a
6983 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6984 TemplateParameter Param, TemplateDecl *Template,
6985 ArrayRef<TemplateArgument> TemplateArgs,
6986 SourceRange InstantiationRange = SourceRange());
6988 /// \brief Note that we are substituting either explicitly-specified or
6989 /// deduced template arguments during function template argument deduction.
6990 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6991 FunctionTemplateDecl *FunctionTemplate,
6992 ArrayRef<TemplateArgument> TemplateArgs,
6993 ActiveTemplateInstantiation::InstantiationKind Kind,
6994 sema::TemplateDeductionInfo &DeductionInfo,
6995 SourceRange InstantiationRange = SourceRange());
6997 /// \brief Note that we are instantiating as part of template
6998 /// argument deduction for a class template declaration.
6999 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7000 TemplateDecl *Template,
7001 ArrayRef<TemplateArgument> TemplateArgs,
7002 sema::TemplateDeductionInfo &DeductionInfo,
7003 SourceRange InstantiationRange = SourceRange());
7005 /// \brief Note that we are instantiating as part of template
7006 /// argument deduction for a class template partial
7008 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7009 ClassTemplatePartialSpecializationDecl *PartialSpec,
7010 ArrayRef<TemplateArgument> TemplateArgs,
7011 sema::TemplateDeductionInfo &DeductionInfo,
7012 SourceRange InstantiationRange = SourceRange());
7014 /// \brief Note that we are instantiating as part of template
7015 /// argument deduction for a variable template partial
7017 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7018 VarTemplatePartialSpecializationDecl *PartialSpec,
7019 ArrayRef<TemplateArgument> TemplateArgs,
7020 sema::TemplateDeductionInfo &DeductionInfo,
7021 SourceRange InstantiationRange = SourceRange());
7023 /// \brief Note that we are instantiating a default argument for a function
7025 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7027 ArrayRef<TemplateArgument> TemplateArgs,
7028 SourceRange InstantiationRange = SourceRange());
7030 /// \brief Note that we are substituting prior template arguments into a
7031 /// non-type parameter.
7032 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7033 NamedDecl *Template,
7034 NonTypeTemplateParmDecl *Param,
7035 ArrayRef<TemplateArgument> TemplateArgs,
7036 SourceRange InstantiationRange);
7038 /// \brief Note that we are substituting prior template arguments into a
7039 /// template template parameter.
7040 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7041 NamedDecl *Template,
7042 TemplateTemplateParmDecl *Param,
7043 ArrayRef<TemplateArgument> TemplateArgs,
7044 SourceRange InstantiationRange);
7046 /// \brief Note that we are checking the default template argument
7047 /// against the template parameter for a given template-id.
7048 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7049 TemplateDecl *Template,
7051 ArrayRef<TemplateArgument> TemplateArgs,
7052 SourceRange InstantiationRange);
7055 /// \brief Note that we have finished instantiating this template.
7058 ~InstantiatingTemplate() { Clear(); }
7060 /// \brief Determines whether we have exceeded the maximum
7061 /// recursive template instantiations.
7062 bool isInvalid() const { return Invalid; }
7064 /// \brief Determine whether we are already instantiating this
7065 /// specialization in some surrounding active instantiation.
7066 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7071 bool AlreadyInstantiating;
7072 bool SavedInNonInstantiationSFINAEContext;
7073 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7074 SourceRange InstantiationRange);
7076 InstantiatingTemplate(
7077 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
7078 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7079 Decl *Entity, NamedDecl *Template = nullptr,
7080 ArrayRef<TemplateArgument> TemplateArgs = None,
7081 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7083 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7085 InstantiatingTemplate&
7086 operator=(const InstantiatingTemplate&) = delete;
7089 void PrintInstantiationStack();
7091 /// \brief Determines whether we are currently in a context where
7092 /// template argument substitution failures are not considered
7095 /// \returns An empty \c Optional if we're not in a SFINAE context.
7096 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7097 /// template-deduction context object, which can be used to capture
7098 /// diagnostics that will be suppressed.
7099 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7101 /// \brief Determines whether we are currently in a context that
7102 /// is not evaluated as per C++ [expr] p5.
7103 bool isUnevaluatedContext() const {
7104 assert(!ExprEvalContexts.empty() &&
7105 "Must be in an expression evaluation context");
7106 return ExprEvalContexts.back().isUnevaluated();
7109 /// \brief RAII class used to determine whether SFINAE has
7110 /// trapped any errors that occur during template argument
7114 unsigned PrevSFINAEErrors;
7115 bool PrevInNonInstantiationSFINAEContext;
7116 bool PrevAccessCheckingSFINAE;
7119 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7120 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7121 PrevInNonInstantiationSFINAEContext(
7122 SemaRef.InNonInstantiationSFINAEContext),
7123 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7125 if (!SemaRef.isSFINAEContext())
7126 SemaRef.InNonInstantiationSFINAEContext = true;
7127 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7131 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7132 SemaRef.InNonInstantiationSFINAEContext
7133 = PrevInNonInstantiationSFINAEContext;
7134 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7137 /// \brief Determine whether any SFINAE errors have been trapped.
7138 bool hasErrorOccurred() const {
7139 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7143 /// \brief RAII class used to indicate that we are performing provisional
7144 /// semantic analysis to determine the validity of a construct, so
7145 /// typo-correction and diagnostics in the immediate context (not within
7146 /// implicitly-instantiated templates) should be suppressed.
7147 class TentativeAnalysisScope {
7149 // FIXME: Using a SFINAETrap for this is a hack.
7151 bool PrevDisableTypoCorrection;
7153 explicit TentativeAnalysisScope(Sema &SemaRef)
7154 : SemaRef(SemaRef), Trap(SemaRef, true),
7155 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7156 SemaRef.DisableTypoCorrection = true;
7158 ~TentativeAnalysisScope() {
7159 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7163 /// \brief The current instantiation scope used to store local
7165 LocalInstantiationScope *CurrentInstantiationScope;
7167 /// \brief Tracks whether we are in a context where typo correction is
7169 bool DisableTypoCorrection;
7171 /// \brief The number of typos corrected by CorrectTypo.
7172 unsigned TyposCorrected;
7174 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7175 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7177 /// \brief A cache containing identifiers for which typo correction failed and
7178 /// their locations, so that repeated attempts to correct an identifier in a
7179 /// given location are ignored if typo correction already failed for it.
7180 IdentifierSourceLocations TypoCorrectionFailures;
7182 /// \brief Worker object for performing CFG-based warnings.
7183 sema::AnalysisBasedWarnings AnalysisWarnings;
7184 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7186 /// \brief An entity for which implicit template instantiation is required.
7188 /// The source location associated with the declaration is the first place in
7189 /// the source code where the declaration was "used". It is not necessarily
7190 /// the point of instantiation (which will be either before or after the
7191 /// namespace-scope declaration that triggered this implicit instantiation),
7192 /// However, it is the location that diagnostics should generally refer to,
7193 /// because users will need to know what code triggered the instantiation.
7194 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7196 /// \brief The queue of implicit template instantiations that are required
7197 /// but have not yet been performed.
7198 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7200 class SavePendingInstantiationsAndVTableUsesRAII {
7202 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7203 : S(S), Enabled(Enabled) {
7204 if (!Enabled) return;
7206 SavedPendingInstantiations.swap(S.PendingInstantiations);
7207 SavedVTableUses.swap(S.VTableUses);
7210 ~SavePendingInstantiationsAndVTableUsesRAII() {
7211 if (!Enabled) return;
7213 // Restore the set of pending vtables.
7214 assert(S.VTableUses.empty() &&
7215 "VTableUses should be empty before it is discarded.");
7216 S.VTableUses.swap(SavedVTableUses);
7218 // Restore the set of pending implicit instantiations.
7219 assert(S.PendingInstantiations.empty() &&
7220 "PendingInstantiations should be empty before it is discarded.");
7221 S.PendingInstantiations.swap(SavedPendingInstantiations);
7226 SmallVector<VTableUse, 16> SavedVTableUses;
7227 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7231 /// \brief The queue of implicit template instantiations that are required
7232 /// and must be performed within the current local scope.
7234 /// This queue is only used for member functions of local classes in
7235 /// templates, which must be instantiated in the same scope as their
7236 /// enclosing function, so that they can reference function-local
7237 /// types, static variables, enumerators, etc.
7238 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7240 class SavePendingLocalImplicitInstantiationsRAII {
7242 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7243 SavedPendingLocalImplicitInstantiations.swap(
7244 S.PendingLocalImplicitInstantiations);
7247 ~SavePendingLocalImplicitInstantiationsRAII() {
7248 assert(S.PendingLocalImplicitInstantiations.empty() &&
7249 "there shouldn't be any pending local implicit instantiations");
7250 SavedPendingLocalImplicitInstantiations.swap(
7251 S.PendingLocalImplicitInstantiations);
7256 std::deque<PendingImplicitInstantiation>
7257 SavedPendingLocalImplicitInstantiations;
7260 /// A helper class for building up ExtParameterInfos.
7261 class ExtParameterInfoBuilder {
7262 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7263 bool HasInteresting = false;
7266 /// Set the ExtParameterInfo for the parameter at the given index,
7268 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7269 assert(Infos.size() <= index);
7270 Infos.resize(index);
7271 Infos.push_back(info);
7273 if (!HasInteresting)
7274 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7277 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7278 /// ExtParameterInfo array we've built up.
7279 const FunctionProtoType::ExtParameterInfo *
7280 getPointerOrNull(unsigned numParams) {
7281 if (!HasInteresting) return nullptr;
7282 Infos.resize(numParams);
7283 return Infos.data();
7287 void PerformPendingInstantiations(bool LocalOnly = false);
7289 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7290 const MultiLevelTemplateArgumentList &TemplateArgs,
7291 SourceLocation Loc, DeclarationName Entity);
7293 QualType SubstType(QualType T,
7294 const MultiLevelTemplateArgumentList &TemplateArgs,
7295 SourceLocation Loc, DeclarationName Entity);
7297 TypeSourceInfo *SubstType(TypeLoc TL,
7298 const MultiLevelTemplateArgumentList &TemplateArgs,
7299 SourceLocation Loc, DeclarationName Entity);
7301 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7302 const MultiLevelTemplateArgumentList &TemplateArgs,
7304 DeclarationName Entity,
7305 CXXRecordDecl *ThisContext,
7306 unsigned ThisTypeQuals);
7307 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7308 const MultiLevelTemplateArgumentList &Args);
7309 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7310 const MultiLevelTemplateArgumentList &TemplateArgs,
7311 int indexAdjustment,
7312 Optional<unsigned> NumExpansions,
7313 bool ExpectParameterPack);
7314 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7315 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7316 const MultiLevelTemplateArgumentList &TemplateArgs,
7317 SmallVectorImpl<QualType> &ParamTypes,
7318 SmallVectorImpl<ParmVarDecl *> *OutParams,
7319 ExtParameterInfoBuilder &ParamInfos);
7320 ExprResult SubstExpr(Expr *E,
7321 const MultiLevelTemplateArgumentList &TemplateArgs);
7323 /// \brief Substitute the given template arguments into a list of
7324 /// expressions, expanding pack expansions if required.
7326 /// \param Exprs The list of expressions to substitute into.
7328 /// \param IsCall Whether this is some form of call, in which case
7329 /// default arguments will be dropped.
7331 /// \param TemplateArgs The set of template arguments to substitute.
7333 /// \param Outputs Will receive all of the substituted arguments.
7335 /// \returns true if an error occurred, false otherwise.
7336 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7337 const MultiLevelTemplateArgumentList &TemplateArgs,
7338 SmallVectorImpl<Expr *> &Outputs);
7340 StmtResult SubstStmt(Stmt *S,
7341 const MultiLevelTemplateArgumentList &TemplateArgs);
7343 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7344 const MultiLevelTemplateArgumentList &TemplateArgs);
7346 ExprResult SubstInitializer(Expr *E,
7347 const MultiLevelTemplateArgumentList &TemplateArgs,
7348 bool CXXDirectInit);
7351 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7352 CXXRecordDecl *Pattern,
7353 const MultiLevelTemplateArgumentList &TemplateArgs);
7356 InstantiateClass(SourceLocation PointOfInstantiation,
7357 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7358 const MultiLevelTemplateArgumentList &TemplateArgs,
7359 TemplateSpecializationKind TSK,
7360 bool Complain = true);
7362 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7363 EnumDecl *Instantiation, EnumDecl *Pattern,
7364 const MultiLevelTemplateArgumentList &TemplateArgs,
7365 TemplateSpecializationKind TSK);
7367 bool InstantiateInClassInitializer(
7368 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7369 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7371 struct LateInstantiatedAttribute {
7372 const Attr *TmplAttr;
7373 LocalInstantiationScope *Scope;
7376 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7378 : TmplAttr(A), Scope(S), NewDecl(D)
7381 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7383 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7384 const Decl *Pattern, Decl *Inst,
7385 LateInstantiatedAttrVec *LateAttrs = nullptr,
7386 LocalInstantiationScope *OuterMostScope = nullptr);
7389 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7390 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7391 TemplateSpecializationKind TSK,
7392 bool Complain = true);
7394 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7395 CXXRecordDecl *Instantiation,
7396 const MultiLevelTemplateArgumentList &TemplateArgs,
7397 TemplateSpecializationKind TSK);
7399 void InstantiateClassTemplateSpecializationMembers(
7400 SourceLocation PointOfInstantiation,
7401 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7402 TemplateSpecializationKind TSK);
7404 NestedNameSpecifierLoc
7405 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7406 const MultiLevelTemplateArgumentList &TemplateArgs);
7409 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7410 const MultiLevelTemplateArgumentList &TemplateArgs);
7412 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7414 const MultiLevelTemplateArgumentList &TemplateArgs);
7415 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7416 TemplateArgumentListInfo &Result,
7417 const MultiLevelTemplateArgumentList &TemplateArgs);
7419 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7420 FunctionDecl *Function);
7421 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7422 FunctionDecl *Function,
7423 bool Recursive = false,
7424 bool DefinitionRequired = false,
7425 bool AtEndOfTU = false);
7426 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7427 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7428 const TemplateArgumentList &TemplateArgList,
7429 const TemplateArgumentListInfo &TemplateArgsInfo,
7430 SmallVectorImpl<TemplateArgument> &Converted,
7431 SourceLocation PointOfInstantiation, void *InsertPos,
7432 LateInstantiatedAttrVec *LateAttrs = nullptr,
7433 LocalInstantiationScope *StartingScope = nullptr);
7434 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7435 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7436 const MultiLevelTemplateArgumentList &TemplateArgs);
7438 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7439 const MultiLevelTemplateArgumentList &TemplateArgs,
7440 LateInstantiatedAttrVec *LateAttrs,
7442 LocalInstantiationScope *StartingScope,
7443 bool InstantiatingVarTemplate = false);
7444 void InstantiateVariableInitializer(
7445 VarDecl *Var, VarDecl *OldVar,
7446 const MultiLevelTemplateArgumentList &TemplateArgs);
7447 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7448 VarDecl *Var, bool Recursive = false,
7449 bool DefinitionRequired = false,
7450 bool AtEndOfTU = false);
7451 void InstantiateStaticDataMemberDefinition(
7452 SourceLocation PointOfInstantiation,
7454 bool Recursive = false,
7455 bool DefinitionRequired = false);
7457 void InstantiateMemInitializers(CXXConstructorDecl *New,
7458 const CXXConstructorDecl *Tmpl,
7459 const MultiLevelTemplateArgumentList &TemplateArgs);
7461 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7462 const MultiLevelTemplateArgumentList &TemplateArgs);
7463 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7464 const MultiLevelTemplateArgumentList &TemplateArgs);
7466 // Objective-C declarations.
7467 enum ObjCContainerKind {
7474 OCK_CategoryImplementation
7476 ObjCContainerKind getObjCContainerKind() const;
7478 DeclResult actOnObjCTypeParam(Scope *S,
7479 ObjCTypeParamVariance variance,
7480 SourceLocation varianceLoc,
7482 IdentifierInfo *paramName,
7483 SourceLocation paramLoc,
7484 SourceLocation colonLoc,
7485 ParsedType typeBound);
7487 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7488 ArrayRef<Decl *> typeParams,
7489 SourceLocation rAngleLoc);
7490 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7492 Decl *ActOnStartClassInterface(Scope *S,
7493 SourceLocation AtInterfaceLoc,
7494 IdentifierInfo *ClassName,
7495 SourceLocation ClassLoc,
7496 ObjCTypeParamList *typeParamList,
7497 IdentifierInfo *SuperName,
7498 SourceLocation SuperLoc,
7499 ArrayRef<ParsedType> SuperTypeArgs,
7500 SourceRange SuperTypeArgsRange,
7501 Decl * const *ProtoRefs,
7502 unsigned NumProtoRefs,
7503 const SourceLocation *ProtoLocs,
7504 SourceLocation EndProtoLoc,
7505 AttributeList *AttrList);
7507 void ActOnSuperClassOfClassInterface(Scope *S,
7508 SourceLocation AtInterfaceLoc,
7509 ObjCInterfaceDecl *IDecl,
7510 IdentifierInfo *ClassName,
7511 SourceLocation ClassLoc,
7512 IdentifierInfo *SuperName,
7513 SourceLocation SuperLoc,
7514 ArrayRef<ParsedType> SuperTypeArgs,
7515 SourceRange SuperTypeArgsRange);
7517 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7518 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7519 IdentifierInfo *SuperName,
7520 SourceLocation SuperLoc);
7522 Decl *ActOnCompatibilityAlias(
7523 SourceLocation AtCompatibilityAliasLoc,
7524 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7525 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7527 bool CheckForwardProtocolDeclarationForCircularDependency(
7528 IdentifierInfo *PName,
7529 SourceLocation &PLoc, SourceLocation PrevLoc,
7530 const ObjCList<ObjCProtocolDecl> &PList);
7532 Decl *ActOnStartProtocolInterface(
7533 SourceLocation AtProtoInterfaceLoc,
7534 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7535 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7536 const SourceLocation *ProtoLocs,
7537 SourceLocation EndProtoLoc,
7538 AttributeList *AttrList);
7540 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7541 IdentifierInfo *ClassName,
7542 SourceLocation ClassLoc,
7543 ObjCTypeParamList *typeParamList,
7544 IdentifierInfo *CategoryName,
7545 SourceLocation CategoryLoc,
7546 Decl * const *ProtoRefs,
7547 unsigned NumProtoRefs,
7548 const SourceLocation *ProtoLocs,
7549 SourceLocation EndProtoLoc);
7551 Decl *ActOnStartClassImplementation(
7552 SourceLocation AtClassImplLoc,
7553 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7554 IdentifierInfo *SuperClassname,
7555 SourceLocation SuperClassLoc);
7557 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7558 IdentifierInfo *ClassName,
7559 SourceLocation ClassLoc,
7560 IdentifierInfo *CatName,
7561 SourceLocation CatLoc);
7563 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7564 ArrayRef<Decl *> Decls);
7566 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7567 IdentifierInfo **IdentList,
7568 SourceLocation *IdentLocs,
7569 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7572 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7573 ArrayRef<IdentifierLocPair> IdentList,
7574 AttributeList *attrList);
7576 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7577 ArrayRef<IdentifierLocPair> ProtocolId,
7578 SmallVectorImpl<Decl *> &Protocols);
7580 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7581 SourceLocation ProtocolLoc,
7582 IdentifierInfo *TypeArgId,
7583 SourceLocation TypeArgLoc,
7584 bool SelectProtocolFirst = false);
7586 /// Given a list of identifiers (and their locations), resolve the
7587 /// names to either Objective-C protocol qualifiers or type
7588 /// arguments, as appropriate.
7589 void actOnObjCTypeArgsOrProtocolQualifiers(
7591 ParsedType baseType,
7592 SourceLocation lAngleLoc,
7593 ArrayRef<IdentifierInfo *> identifiers,
7594 ArrayRef<SourceLocation> identifierLocs,
7595 SourceLocation rAngleLoc,
7596 SourceLocation &typeArgsLAngleLoc,
7597 SmallVectorImpl<ParsedType> &typeArgs,
7598 SourceLocation &typeArgsRAngleLoc,
7599 SourceLocation &protocolLAngleLoc,
7600 SmallVectorImpl<Decl *> &protocols,
7601 SourceLocation &protocolRAngleLoc,
7602 bool warnOnIncompleteProtocols);
7604 /// Build a an Objective-C protocol-qualified 'id' type where no
7605 /// base type was specified.
7606 TypeResult actOnObjCProtocolQualifierType(
7607 SourceLocation lAngleLoc,
7608 ArrayRef<Decl *> protocols,
7609 ArrayRef<SourceLocation> protocolLocs,
7610 SourceLocation rAngleLoc);
7612 /// Build a specialized and/or protocol-qualified Objective-C type.
7613 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7616 ParsedType BaseType,
7617 SourceLocation TypeArgsLAngleLoc,
7618 ArrayRef<ParsedType> TypeArgs,
7619 SourceLocation TypeArgsRAngleLoc,
7620 SourceLocation ProtocolLAngleLoc,
7621 ArrayRef<Decl *> Protocols,
7622 ArrayRef<SourceLocation> ProtocolLocs,
7623 SourceLocation ProtocolRAngleLoc);
7625 /// Build an Objective-C type parameter type.
7626 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7627 SourceLocation ProtocolLAngleLoc,
7628 ArrayRef<ObjCProtocolDecl *> Protocols,
7629 ArrayRef<SourceLocation> ProtocolLocs,
7630 SourceLocation ProtocolRAngleLoc,
7631 bool FailOnError = false);
7633 /// Build an Objective-C object pointer type.
7634 QualType BuildObjCObjectType(QualType BaseType,
7636 SourceLocation TypeArgsLAngleLoc,
7637 ArrayRef<TypeSourceInfo *> TypeArgs,
7638 SourceLocation TypeArgsRAngleLoc,
7639 SourceLocation ProtocolLAngleLoc,
7640 ArrayRef<ObjCProtocolDecl *> Protocols,
7641 ArrayRef<SourceLocation> ProtocolLocs,
7642 SourceLocation ProtocolRAngleLoc,
7643 bool FailOnError = false);
7645 /// Check the application of the Objective-C '__kindof' qualifier to
7647 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7649 /// Ensure attributes are consistent with type.
7650 /// \param [in, out] Attributes The attributes to check; they will
7651 /// be modified to be consistent with \p PropertyTy.
7652 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7654 unsigned &Attributes,
7655 bool propertyInPrimaryClass);
7657 /// Process the specified property declaration and create decls for the
7658 /// setters and getters as needed.
7659 /// \param property The property declaration being processed
7660 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7663 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7664 ObjCPropertyDecl *SuperProperty,
7665 const IdentifierInfo *Name,
7666 bool OverridingProtocolProperty);
7668 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7669 ObjCInterfaceDecl *ID);
7671 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7672 ArrayRef<Decl *> allMethods = None,
7673 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7675 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7676 SourceLocation LParenLoc,
7677 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7678 Selector GetterSel, Selector SetterSel,
7679 tok::ObjCKeywordKind MethodImplKind,
7680 DeclContext *lexicalDC = nullptr);
7682 Decl *ActOnPropertyImplDecl(Scope *S,
7683 SourceLocation AtLoc,
7684 SourceLocation PropertyLoc,
7686 IdentifierInfo *PropertyId,
7687 IdentifierInfo *PropertyIvar,
7688 SourceLocation PropertyIvarLoc,
7689 ObjCPropertyQueryKind QueryKind);
7691 enum ObjCSpecialMethodKind {
7697 OSMK_NonRetainingInit
7700 struct ObjCArgInfo {
7701 IdentifierInfo *Name;
7702 SourceLocation NameLoc;
7703 // The Type is null if no type was specified, and the DeclSpec is invalid
7706 ObjCDeclSpec DeclSpec;
7708 /// ArgAttrs - Attribute list for this argument.
7709 AttributeList *ArgAttrs;
7712 Decl *ActOnMethodDeclaration(
7714 SourceLocation BeginLoc, // location of the + or -.
7715 SourceLocation EndLoc, // location of the ; or {.
7716 tok::TokenKind MethodType,
7717 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7718 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7719 // optional arguments. The number of types/arguments is obtained
7720 // from the Sel.getNumArgs().
7721 ObjCArgInfo *ArgInfo,
7722 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7723 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7724 bool isVariadic, bool MethodDefinition);
7726 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7727 const ObjCObjectPointerType *OPT,
7729 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7732 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7733 bool inferObjCARCLifetime(ValueDecl *decl);
7736 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7738 SourceLocation OpLoc,
7739 DeclarationName MemberName,
7740 SourceLocation MemberLoc,
7741 SourceLocation SuperLoc, QualType SuperType,
7745 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7746 IdentifierInfo &propertyName,
7747 SourceLocation receiverNameLoc,
7748 SourceLocation propertyNameLoc);
7750 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7752 /// \brief Describes the kind of message expression indicated by a message
7753 /// send that starts with an identifier.
7754 enum ObjCMessageKind {
7755 /// \brief The message is sent to 'super'.
7757 /// \brief The message is an instance message.
7758 ObjCInstanceMessage,
7759 /// \brief The message is a class message, and the identifier is a type
7764 ObjCMessageKind getObjCMessageKind(Scope *S,
7765 IdentifierInfo *Name,
7766 SourceLocation NameLoc,
7768 bool HasTrailingDot,
7769 ParsedType &ReceiverType);
7771 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7773 SourceLocation LBracLoc,
7774 ArrayRef<SourceLocation> SelectorLocs,
7775 SourceLocation RBracLoc,
7778 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7779 QualType ReceiverType,
7780 SourceLocation SuperLoc,
7782 ObjCMethodDecl *Method,
7783 SourceLocation LBracLoc,
7784 ArrayRef<SourceLocation> SelectorLocs,
7785 SourceLocation RBracLoc,
7787 bool isImplicit = false);
7789 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7790 bool isSuperReceiver,
7793 ObjCMethodDecl *Method,
7796 ExprResult ActOnClassMessage(Scope *S,
7797 ParsedType Receiver,
7799 SourceLocation LBracLoc,
7800 ArrayRef<SourceLocation> SelectorLocs,
7801 SourceLocation RBracLoc,
7804 ExprResult BuildInstanceMessage(Expr *Receiver,
7805 QualType ReceiverType,
7806 SourceLocation SuperLoc,
7808 ObjCMethodDecl *Method,
7809 SourceLocation LBracLoc,
7810 ArrayRef<SourceLocation> SelectorLocs,
7811 SourceLocation RBracLoc,
7813 bool isImplicit = false);
7815 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7816 QualType ReceiverType,
7819 ObjCMethodDecl *Method,
7822 ExprResult ActOnInstanceMessage(Scope *S,
7825 SourceLocation LBracLoc,
7826 ArrayRef<SourceLocation> SelectorLocs,
7827 SourceLocation RBracLoc,
7830 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7831 ObjCBridgeCastKind Kind,
7832 SourceLocation BridgeKeywordLoc,
7833 TypeSourceInfo *TSInfo,
7836 ExprResult ActOnObjCBridgedCast(Scope *S,
7837 SourceLocation LParenLoc,
7838 ObjCBridgeCastKind Kind,
7839 SourceLocation BridgeKeywordLoc,
7841 SourceLocation RParenLoc,
7844 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7846 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7848 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7851 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7852 QualType DestType, QualType SrcType,
7853 ObjCInterfaceDecl *&RelatedClass,
7854 ObjCMethodDecl *&ClassMethod,
7855 ObjCMethodDecl *&InstanceMethod,
7856 TypedefNameDecl *&TDNDecl,
7857 bool CfToNs, bool Diagnose = true);
7859 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7860 QualType DestType, QualType SrcType,
7861 Expr *&SrcExpr, bool Diagnose = true);
7863 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7864 bool Diagnose = true);
7866 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7868 /// \brief Check whether the given new method is a valid override of the
7869 /// given overridden method, and set any properties that should be inherited.
7870 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7871 const ObjCMethodDecl *Overridden);
7873 /// \brief Describes the compatibility of a result type with its method.
7874 enum ResultTypeCompatibilityKind {
7880 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7881 ObjCInterfaceDecl *CurrentClass,
7882 ResultTypeCompatibilityKind RTC);
7884 enum PragmaOptionsAlignKind {
7885 POAK_Native, // #pragma options align=native
7886 POAK_Natural, // #pragma options align=natural
7887 POAK_Packed, // #pragma options align=packed
7888 POAK_Power, // #pragma options align=power
7889 POAK_Mac68k, // #pragma options align=mac68k
7890 POAK_Reset // #pragma options align=reset
7893 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7894 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7895 SourceLocation PragmaLoc);
7897 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7898 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
7899 StringRef SlotLabel, Expr *Alignment);
7901 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7902 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7904 /// ActOnPragmaMSComment - Called on well formed
7905 /// \#pragma comment(kind, "arg").
7906 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
7909 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7910 /// pointers_to_members(representation method[, general purpose
7911 /// representation]).
7912 void ActOnPragmaMSPointersToMembers(
7913 LangOptions::PragmaMSPointersToMembersKind Kind,
7914 SourceLocation PragmaLoc);
7916 /// \brief Called on well formed \#pragma vtordisp().
7917 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
7918 SourceLocation PragmaLoc,
7919 MSVtorDispAttr::Mode Value);
7921 enum PragmaSectionKind {
7928 bool UnifySection(StringRef SectionName,
7930 DeclaratorDecl *TheDecl);
7931 bool UnifySection(StringRef SectionName,
7933 SourceLocation PragmaSectionLocation);
7935 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7936 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7937 PragmaMsStackAction Action,
7938 llvm::StringRef StackSlotLabel,
7939 StringLiteral *SegmentName,
7940 llvm::StringRef PragmaName);
7942 /// \brief Called on well formed \#pragma section().
7943 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7944 int SectionFlags, StringLiteral *SegmentName);
7946 /// \brief Called on well-formed \#pragma init_seg().
7947 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7948 StringLiteral *SegmentName);
7950 /// \brief Called on #pragma clang __debug dump II
7951 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
7953 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7954 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
7957 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7958 void ActOnPragmaUnused(const Token &Identifier,
7960 SourceLocation PragmaLoc);
7962 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7963 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7964 SourceLocation PragmaLoc);
7966 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7967 SourceLocation Loc);
7968 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7970 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7971 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7972 SourceLocation PragmaLoc,
7973 SourceLocation WeakNameLoc);
7975 /// ActOnPragmaRedefineExtname - Called on well formed
7976 /// \#pragma redefine_extname oldname newname.
7977 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7978 IdentifierInfo* AliasName,
7979 SourceLocation PragmaLoc,
7980 SourceLocation WeakNameLoc,
7981 SourceLocation AliasNameLoc);
7983 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7984 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7985 IdentifierInfo* AliasName,
7986 SourceLocation PragmaLoc,
7987 SourceLocation WeakNameLoc,
7988 SourceLocation AliasNameLoc);
7990 /// ActOnPragmaFPContract - Called on well formed
7991 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7992 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7994 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7995 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7996 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7998 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7999 void AddMsStructLayoutForRecord(RecordDecl *RD);
8001 /// FreePackedContext - Deallocate and null out PackContext.
8002 void FreePackedContext();
8004 /// PushNamespaceVisibilityAttr - Note that we've entered a
8005 /// namespace with a visibility attribute.
8006 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8007 SourceLocation Loc);
8009 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8010 /// add an appropriate visibility attribute.
8011 void AddPushedVisibilityAttribute(Decl *RD);
8013 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8014 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8015 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8017 /// FreeVisContext - Deallocate and null out VisContext.
8018 void FreeVisContext();
8020 /// AddCFAuditedAttribute - Check whether we're currently within
8021 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8022 /// the appropriate attribute.
8023 void AddCFAuditedAttribute(Decl *D);
8025 /// \brief Called on well formed \#pragma clang optimize.
8026 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8028 /// \brief Get the location for the currently active "\#pragma clang optimize
8029 /// off". If this location is invalid, then the state of the pragma is "on".
8030 SourceLocation getOptimizeOffPragmaLocation() const {
8031 return OptimizeOffPragmaLocation;
8034 /// \brief Only called on function definitions; if there is a pragma in scope
8035 /// with the effect of a range-based optnone, consider marking the function
8036 /// with attribute optnone.
8037 void AddRangeBasedOptnone(FunctionDecl *FD);
8039 /// \brief Adds the 'optnone' attribute to the function declaration if there
8040 /// are no conflicts; Loc represents the location causing the 'optnone'
8041 /// attribute to be added (usually because of a pragma).
8042 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8044 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8045 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8046 unsigned SpellingListIndex, bool IsPackExpansion);
8047 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8048 unsigned SpellingListIndex, bool IsPackExpansion);
8050 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8052 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8053 unsigned SpellingListIndex);
8055 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8057 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8058 unsigned SpellingListIndex);
8060 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8062 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8063 Expr *MinBlocks, unsigned SpellingListIndex);
8065 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8066 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8067 unsigned SpellingListIndex, bool InInstantiation = false);
8069 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8070 ParameterABI ABI, unsigned SpellingListIndex);
8072 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8073 unsigned SpellingListIndex, bool isNSConsumed,
8074 bool isTemplateInstantiation);
8076 //===--------------------------------------------------------------------===//
8077 // C++ Coroutines TS
8079 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8080 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8081 StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
8083 ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
8084 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8085 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
8087 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8089 //===--------------------------------------------------------------------===//
8090 // OpenCL extensions.
8093 std::string CurrOpenCLExtension;
8094 /// Extensions required by an OpenCL type.
8095 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8096 /// Extensions required by an OpenCL declaration.
8097 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8099 llvm::StringRef getCurrentOpenCLExtension() const {
8100 return CurrOpenCLExtension;
8102 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8103 CurrOpenCLExtension = Ext;
8106 /// \brief Set OpenCL extensions for a type which can only be used when these
8107 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8108 /// \param Exts A space separated list of OpenCL extensions.
8109 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8111 /// \brief Set OpenCL extensions for a declaration which can only be
8112 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8114 /// \param Exts A space separated list of OpenCL extensions.
8115 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8117 /// \brief Set current OpenCL extensions for a type which can only be used
8118 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8119 /// empty, do nothing.
8120 void setCurrentOpenCLExtensionForType(QualType T);
8122 /// \brief Set current OpenCL extensions for a declaration which
8123 /// can only be used when these OpenCL extensions are enabled. If current
8124 /// OpenCL extension is empty, do nothing.
8125 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8127 bool isOpenCLDisabledDecl(Decl *FD);
8129 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8130 /// is disabled due to required OpenCL extensions being disabled. If so,
8131 /// emit diagnostics.
8132 /// \return true if type is disabled.
8133 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8135 /// \brief Check if declaration \p D used by expression \p E
8136 /// is disabled due to required OpenCL extensions being disabled. If so,
8137 /// emit diagnostics.
8138 /// \return true if type is disabled.
8139 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8141 //===--------------------------------------------------------------------===//
8142 // OpenMP directives and clauses.
8145 void *VarDataSharingAttributesStack;
8146 /// Set to true inside '#pragma omp declare target' region.
8147 bool IsInOpenMPDeclareTargetContext = false;
8148 /// \brief Initialization of data-sharing attributes stack.
8149 void InitDataSharingAttributesStack();
8150 void DestroyDataSharingAttributesStack();
8152 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8153 bool StrictlyPositive = true);
8154 /// Returns OpenMP nesting level for current directive.
8155 unsigned getOpenMPNestingLevel() const;
8157 /// Checks if a type or a declaration is disabled due to the owning extension
8158 /// being disabled, and emits diagnostic messages if it is disabled.
8159 /// \param D type or declaration to be checked.
8160 /// \param DiagLoc source location for the diagnostic message.
8161 /// \param DiagInfo information to be emitted for the diagnostic message.
8162 /// \param SrcRange source range of the declaration.
8163 /// \param Map maps type or declaration to the extensions.
8164 /// \param Selector selects diagnostic message: 0 for type and 1 for
8166 /// \return true if the type or declaration is disabled.
8167 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8168 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8169 MapT &Map, unsigned Selector = 0,
8170 SourceRange SrcRange = SourceRange());
8173 /// \brief Return true if the provided declaration \a VD should be captured by
8175 /// \param Level Relative level of nested OpenMP construct for that the check
8177 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8179 /// \brief Check if the specified variable is used in one of the private
8180 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8182 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8183 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8184 ExprObjectKind OK, SourceLocation Loc);
8186 /// \brief Check if the specified variable is used in 'private' clause.
8187 /// \param Level Relative level of nested OpenMP construct for that the check
8189 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8191 /// \brief Check if the specified variable is captured by 'target' directive.
8192 /// \param Level Relative level of nested OpenMP construct for that the check
8194 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8196 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8198 /// \brief Called on start of new data sharing attribute block.
8199 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8200 const DeclarationNameInfo &DirName, Scope *CurScope,
8201 SourceLocation Loc);
8202 /// \brief Start analysis of clauses.
8203 void StartOpenMPClause(OpenMPClauseKind K);
8204 /// \brief End analysis of clauses.
8205 void EndOpenMPClause();
8206 /// \brief Called on end of data sharing attribute block.
8207 void EndOpenMPDSABlock(Stmt *CurDirective);
8209 /// \brief Check if the current region is an OpenMP loop region and if it is,
8210 /// mark loop control variable, used in \p Init for loop initialization, as
8211 /// private by default.
8212 /// \param Init First part of the for loop.
8213 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8215 // OpenMP directives and clauses.
8216 /// \brief Called on correct id-expression from the '#pragma omp
8218 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8219 CXXScopeSpec &ScopeSpec,
8220 const DeclarationNameInfo &Id);
8221 /// \brief Called on well-formed '#pragma omp threadprivate'.
8222 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8224 ArrayRef<Expr *> VarList);
8225 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8226 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8228 ArrayRef<Expr *> VarList);
8229 /// \brief Check if the specified type is allowed to be used in 'omp declare
8230 /// reduction' construct.
8231 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8232 TypeResult ParsedType);
8233 /// \brief Called on start of '#pragma omp declare reduction'.
8234 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8235 Scope *S, DeclContext *DC, DeclarationName Name,
8236 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8237 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8238 /// \brief Initialize declare reduction construct initializer.
8239 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8240 /// \brief Finish current declare reduction construct initializer.
8241 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8242 /// \brief Initialize declare reduction construct initializer.
8243 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8244 /// \brief Finish current declare reduction construct initializer.
8245 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8246 /// \brief Called at the end of '#pragma omp declare reduction'.
8247 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8248 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8250 /// Called on the start of target region i.e. '#pragma omp declare target'.
8251 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8252 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8253 void ActOnFinishOpenMPDeclareTargetDirective();
8254 /// Called on correct id-expression from the '#pragma omp declare target'.
8255 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8256 const DeclarationNameInfo &Id,
8257 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8258 NamedDeclSetType &SameDirectiveDecls);
8259 /// Check declaration inside target region.
8260 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8261 /// Return true inside OpenMP target region.
8262 bool isInOpenMPDeclareTargetContext() const {
8263 return IsInOpenMPDeclareTargetContext;
8266 /// \brief Initialization of captured region for OpenMP region.
8267 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8268 /// \brief End of OpenMP region.
8270 /// \param S Statement associated with the current OpenMP region.
8271 /// \param Clauses List of clauses for the current OpenMP region.
8273 /// \returns Statement for finished OpenMP region.
8274 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8275 StmtResult ActOnOpenMPExecutableDirective(
8276 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8277 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8278 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8279 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8280 /// of the associated statement.
8281 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8283 SourceLocation StartLoc,
8284 SourceLocation EndLoc);
8285 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8286 /// of the associated statement.
8287 StmtResult ActOnOpenMPSimdDirective(
8288 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8289 SourceLocation EndLoc,
8290 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8291 /// \brief Called on well-formed '\#pragma omp for' after parsing
8292 /// of the associated statement.
8293 StmtResult ActOnOpenMPForDirective(
8294 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8295 SourceLocation EndLoc,
8296 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8297 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8298 /// of the associated statement.
8299 StmtResult ActOnOpenMPForSimdDirective(
8300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8301 SourceLocation EndLoc,
8302 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8303 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8304 /// of the associated statement.
8305 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8306 Stmt *AStmt, SourceLocation StartLoc,
8307 SourceLocation EndLoc);
8308 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8309 /// associated statement.
8310 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8311 SourceLocation EndLoc);
8312 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8313 /// associated statement.
8314 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8315 Stmt *AStmt, SourceLocation StartLoc,
8316 SourceLocation EndLoc);
8317 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8318 /// associated statement.
8319 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8320 SourceLocation EndLoc);
8321 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8322 /// associated statement.
8323 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8324 ArrayRef<OMPClause *> Clauses,
8325 Stmt *AStmt, SourceLocation StartLoc,
8326 SourceLocation EndLoc);
8327 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8328 /// of the associated statement.
8329 StmtResult ActOnOpenMPParallelForDirective(
8330 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8331 SourceLocation EndLoc,
8332 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8333 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8334 /// parsing of the associated statement.
8335 StmtResult ActOnOpenMPParallelForSimdDirective(
8336 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8337 SourceLocation EndLoc,
8338 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8339 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8340 /// parsing of the associated statement.
8341 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8343 SourceLocation StartLoc,
8344 SourceLocation EndLoc);
8345 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8346 /// associated statement.
8347 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8348 Stmt *AStmt, SourceLocation StartLoc,
8349 SourceLocation EndLoc);
8350 /// \brief Called on well-formed '\#pragma omp taskyield'.
8351 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8352 SourceLocation EndLoc);
8353 /// \brief Called on well-formed '\#pragma omp barrier'.
8354 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8355 SourceLocation EndLoc);
8356 /// \brief Called on well-formed '\#pragma omp taskwait'.
8357 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8358 SourceLocation EndLoc);
8359 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8360 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8361 SourceLocation EndLoc);
8362 /// \brief Called on well-formed '\#pragma omp flush'.
8363 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8364 SourceLocation StartLoc,
8365 SourceLocation EndLoc);
8366 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8367 /// associated statement.
8368 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8369 Stmt *AStmt, SourceLocation StartLoc,
8370 SourceLocation EndLoc);
8371 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8372 /// associated statement.
8373 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8374 Stmt *AStmt, SourceLocation StartLoc,
8375 SourceLocation EndLoc);
8376 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8377 /// associated statement.
8378 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8379 Stmt *AStmt, SourceLocation StartLoc,
8380 SourceLocation EndLoc);
8381 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8382 /// the associated statement.
8383 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8384 Stmt *AStmt, SourceLocation StartLoc,
8385 SourceLocation EndLoc);
8386 /// \brief Called on well-formed '\#pragma omp target enter data' after
8387 /// parsing of the associated statement.
8388 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8389 SourceLocation StartLoc,
8390 SourceLocation EndLoc);
8391 /// \brief Called on well-formed '\#pragma omp target exit data' after
8392 /// parsing of the associated statement.
8393 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8394 SourceLocation StartLoc,
8395 SourceLocation EndLoc);
8396 /// \brief Called on well-formed '\#pragma omp target parallel' after
8397 /// parsing of the associated statement.
8398 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8400 SourceLocation StartLoc,
8401 SourceLocation EndLoc);
8402 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8403 /// parsing of the associated statement.
8404 StmtResult ActOnOpenMPTargetParallelForDirective(
8405 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8406 SourceLocation EndLoc,
8407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8408 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8409 /// associated statement.
8410 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8411 Stmt *AStmt, SourceLocation StartLoc,
8412 SourceLocation EndLoc);
8413 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8415 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8416 SourceLocation EndLoc,
8417 OpenMPDirectiveKind CancelRegion);
8418 /// \brief Called on well-formed '\#pragma omp cancel'.
8419 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8420 SourceLocation StartLoc,
8421 SourceLocation EndLoc,
8422 OpenMPDirectiveKind CancelRegion);
8423 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8424 /// associated statement.
8425 StmtResult ActOnOpenMPTaskLoopDirective(
8426 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8427 SourceLocation EndLoc,
8428 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8429 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8430 /// the associated statement.
8431 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8432 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8433 SourceLocation EndLoc,
8434 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8435 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8436 /// of the associated statement.
8437 StmtResult ActOnOpenMPDistributeDirective(
8438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8439 SourceLocation EndLoc,
8440 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8441 /// \brief Called on well-formed '\#pragma omp target update'.
8442 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8443 SourceLocation StartLoc,
8444 SourceLocation EndLoc);
8445 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8446 /// parsing of the associated statement.
8447 StmtResult ActOnOpenMPDistributeParallelForDirective(
8448 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8449 SourceLocation EndLoc,
8450 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8451 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8452 /// after parsing of the associated statement.
8453 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8454 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8455 SourceLocation EndLoc,
8456 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8457 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8458 /// parsing of the associated statement.
8459 StmtResult ActOnOpenMPDistributeSimdDirective(
8460 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8461 SourceLocation EndLoc,
8462 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8463 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8464 /// parsing of the associated statement.
8465 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8466 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8467 SourceLocation EndLoc,
8468 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8469 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8470 /// the associated statement.
8471 StmtResult ActOnOpenMPTargetSimdDirective(
8472 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8473 SourceLocation EndLoc,
8474 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8475 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8476 /// the associated statement.
8477 StmtResult ActOnOpenMPTeamsDistributeDirective(
8478 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8479 SourceLocation EndLoc,
8480 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8481 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8482 /// of the associated statement.
8483 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8484 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8485 SourceLocation EndLoc,
8486 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8487 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8488 /// after parsing of the associated statement.
8489 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8490 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8491 SourceLocation EndLoc,
8492 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8493 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8494 /// after parsing of the associated statement.
8495 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8496 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8497 SourceLocation EndLoc,
8498 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8499 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8500 /// associated statement.
8501 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8503 SourceLocation StartLoc,
8504 SourceLocation EndLoc);
8505 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8506 /// of the associated statement.
8507 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8508 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8509 SourceLocation EndLoc,
8510 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8511 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8512 /// after parsing of the associated statement.
8513 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8514 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8515 SourceLocation EndLoc,
8516 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8518 /// Checks correctness of linear modifiers.
8519 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8520 SourceLocation LinLoc);
8521 /// Checks that the specified declaration matches requirements for the linear
8523 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8524 OpenMPLinearClauseKind LinKind, QualType Type);
8526 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8527 /// the associated method/function.
8528 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8529 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8530 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8531 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8532 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8534 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8536 SourceLocation StartLoc,
8537 SourceLocation LParenLoc,
8538 SourceLocation EndLoc);
8539 /// \brief Called on well-formed 'if' clause.
8540 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8541 Expr *Condition, SourceLocation StartLoc,
8542 SourceLocation LParenLoc,
8543 SourceLocation NameModifierLoc,
8544 SourceLocation ColonLoc,
8545 SourceLocation EndLoc);
8546 /// \brief Called on well-formed 'final' clause.
8547 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8548 SourceLocation LParenLoc,
8549 SourceLocation EndLoc);
8550 /// \brief Called on well-formed 'num_threads' clause.
8551 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8552 SourceLocation StartLoc,
8553 SourceLocation LParenLoc,
8554 SourceLocation EndLoc);
8555 /// \brief Called on well-formed 'safelen' clause.
8556 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8557 SourceLocation StartLoc,
8558 SourceLocation LParenLoc,
8559 SourceLocation EndLoc);
8560 /// \brief Called on well-formed 'simdlen' clause.
8561 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8562 SourceLocation LParenLoc,
8563 SourceLocation EndLoc);
8564 /// \brief Called on well-formed 'collapse' clause.
8565 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8566 SourceLocation StartLoc,
8567 SourceLocation LParenLoc,
8568 SourceLocation EndLoc);
8569 /// \brief Called on well-formed 'ordered' clause.
8571 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8572 SourceLocation LParenLoc = SourceLocation(),
8573 Expr *NumForLoops = nullptr);
8574 /// \brief Called on well-formed 'grainsize' clause.
8575 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8576 SourceLocation LParenLoc,
8577 SourceLocation EndLoc);
8578 /// \brief Called on well-formed 'num_tasks' clause.
8579 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8580 SourceLocation LParenLoc,
8581 SourceLocation EndLoc);
8582 /// \brief Called on well-formed 'hint' clause.
8583 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8584 SourceLocation LParenLoc,
8585 SourceLocation EndLoc);
8587 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8589 SourceLocation ArgumentLoc,
8590 SourceLocation StartLoc,
8591 SourceLocation LParenLoc,
8592 SourceLocation EndLoc);
8593 /// \brief Called on well-formed 'default' clause.
8594 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8595 SourceLocation KindLoc,
8596 SourceLocation StartLoc,
8597 SourceLocation LParenLoc,
8598 SourceLocation EndLoc);
8599 /// \brief Called on well-formed 'proc_bind' clause.
8600 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8601 SourceLocation KindLoc,
8602 SourceLocation StartLoc,
8603 SourceLocation LParenLoc,
8604 SourceLocation EndLoc);
8606 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8607 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8608 SourceLocation StartLoc, SourceLocation LParenLoc,
8609 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8610 SourceLocation EndLoc);
8611 /// \brief Called on well-formed 'schedule' clause.
8612 OMPClause *ActOnOpenMPScheduleClause(
8613 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8614 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8615 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8616 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8618 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8619 SourceLocation EndLoc);
8620 /// \brief Called on well-formed 'nowait' clause.
8621 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8622 SourceLocation EndLoc);
8623 /// \brief Called on well-formed 'untied' clause.
8624 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8625 SourceLocation EndLoc);
8626 /// \brief Called on well-formed 'mergeable' clause.
8627 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8628 SourceLocation EndLoc);
8629 /// \brief Called on well-formed 'read' clause.
8630 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8631 SourceLocation EndLoc);
8632 /// \brief Called on well-formed 'write' clause.
8633 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8634 SourceLocation EndLoc);
8635 /// \brief Called on well-formed 'update' clause.
8636 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8637 SourceLocation EndLoc);
8638 /// \brief Called on well-formed 'capture' clause.
8639 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8640 SourceLocation EndLoc);
8641 /// \brief Called on well-formed 'seq_cst' clause.
8642 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8643 SourceLocation EndLoc);
8644 /// \brief Called on well-formed 'threads' clause.
8645 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8646 SourceLocation EndLoc);
8647 /// \brief Called on well-formed 'simd' clause.
8648 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8649 SourceLocation EndLoc);
8650 /// \brief Called on well-formed 'nogroup' clause.
8651 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8652 SourceLocation EndLoc);
8654 OMPClause *ActOnOpenMPVarListClause(
8655 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8656 SourceLocation StartLoc, SourceLocation LParenLoc,
8657 SourceLocation ColonLoc, SourceLocation EndLoc,
8658 CXXScopeSpec &ReductionIdScopeSpec,
8659 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8660 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8661 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8662 SourceLocation DepLinMapLoc);
8663 /// \brief Called on well-formed 'private' clause.
8664 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8665 SourceLocation StartLoc,
8666 SourceLocation LParenLoc,
8667 SourceLocation EndLoc);
8668 /// \brief Called on well-formed 'firstprivate' clause.
8669 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8670 SourceLocation StartLoc,
8671 SourceLocation LParenLoc,
8672 SourceLocation EndLoc);
8673 /// \brief Called on well-formed 'lastprivate' clause.
8674 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8675 SourceLocation StartLoc,
8676 SourceLocation LParenLoc,
8677 SourceLocation EndLoc);
8678 /// \brief Called on well-formed 'shared' clause.
8679 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8680 SourceLocation StartLoc,
8681 SourceLocation LParenLoc,
8682 SourceLocation EndLoc);
8683 /// \brief Called on well-formed 'reduction' clause.
8684 OMPClause *ActOnOpenMPReductionClause(
8685 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8686 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8687 CXXScopeSpec &ReductionIdScopeSpec,
8688 const DeclarationNameInfo &ReductionId,
8689 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8690 /// \brief Called on well-formed 'linear' clause.
8692 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8693 SourceLocation StartLoc, SourceLocation LParenLoc,
8694 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8695 SourceLocation ColonLoc, SourceLocation EndLoc);
8696 /// \brief Called on well-formed 'aligned' clause.
8697 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8699 SourceLocation StartLoc,
8700 SourceLocation LParenLoc,
8701 SourceLocation ColonLoc,
8702 SourceLocation EndLoc);
8703 /// \brief Called on well-formed 'copyin' clause.
8704 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8705 SourceLocation StartLoc,
8706 SourceLocation LParenLoc,
8707 SourceLocation EndLoc);
8708 /// \brief Called on well-formed 'copyprivate' clause.
8709 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8710 SourceLocation StartLoc,
8711 SourceLocation LParenLoc,
8712 SourceLocation EndLoc);
8713 /// \brief Called on well-formed 'flush' pseudo clause.
8714 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8715 SourceLocation StartLoc,
8716 SourceLocation LParenLoc,
8717 SourceLocation EndLoc);
8718 /// \brief Called on well-formed 'depend' clause.
8720 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8721 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8722 SourceLocation StartLoc, SourceLocation LParenLoc,
8723 SourceLocation EndLoc);
8724 /// \brief Called on well-formed 'device' clause.
8725 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8726 SourceLocation LParenLoc,
8727 SourceLocation EndLoc);
8728 /// \brief Called on well-formed 'map' clause.
8730 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8731 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8732 SourceLocation MapLoc, SourceLocation ColonLoc,
8733 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8734 SourceLocation LParenLoc, SourceLocation EndLoc);
8735 /// \brief Called on well-formed 'num_teams' clause.
8736 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8737 SourceLocation LParenLoc,
8738 SourceLocation EndLoc);
8739 /// \brief Called on well-formed 'thread_limit' clause.
8740 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8741 SourceLocation StartLoc,
8742 SourceLocation LParenLoc,
8743 SourceLocation EndLoc);
8744 /// \brief Called on well-formed 'priority' clause.
8745 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8746 SourceLocation LParenLoc,
8747 SourceLocation EndLoc);
8748 /// \brief Called on well-formed 'dist_schedule' clause.
8749 OMPClause *ActOnOpenMPDistScheduleClause(
8750 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8751 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8752 SourceLocation CommaLoc, SourceLocation EndLoc);
8753 /// \brief Called on well-formed 'defaultmap' clause.
8754 OMPClause *ActOnOpenMPDefaultmapClause(
8755 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8756 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8757 SourceLocation KindLoc, SourceLocation EndLoc);
8758 /// \brief Called on well-formed 'to' clause.
8759 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8760 SourceLocation StartLoc,
8761 SourceLocation LParenLoc,
8762 SourceLocation EndLoc);
8763 /// \brief Called on well-formed 'from' clause.
8764 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8765 SourceLocation StartLoc,
8766 SourceLocation LParenLoc,
8767 SourceLocation EndLoc);
8768 /// Called on well-formed 'use_device_ptr' clause.
8769 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8770 SourceLocation StartLoc,
8771 SourceLocation LParenLoc,
8772 SourceLocation EndLoc);
8773 /// Called on well-formed 'is_device_ptr' clause.
8774 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8775 SourceLocation StartLoc,
8776 SourceLocation LParenLoc,
8777 SourceLocation EndLoc);
8779 /// \brief The kind of conversion being performed.
8780 enum CheckedConversionKind {
8781 /// \brief An implicit conversion.
8782 CCK_ImplicitConversion,
8783 /// \brief A C-style cast.
8785 /// \brief A functional-style cast.
8787 /// \brief A cast other than a C-style cast.
8791 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8792 /// cast. If there is already an implicit cast, merge into the existing one.
8793 /// If isLvalue, the result of the cast is an lvalue.
8794 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8795 ExprValueKind VK = VK_RValue,
8796 const CXXCastPath *BasePath = nullptr,
8797 CheckedConversionKind CCK
8798 = CCK_ImplicitConversion);
8800 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8801 /// to the conversion from scalar type ScalarTy to the Boolean type.
8802 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8804 /// IgnoredValueConversions - Given that an expression's result is
8805 /// syntactically ignored, perform any conversions that are
8807 ExprResult IgnoredValueConversions(Expr *E);
8809 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8810 // functions and arrays to their respective pointers (C99 6.3.2.1).
8811 ExprResult UsualUnaryConversions(Expr *E);
8813 /// CallExprUnaryConversions - a special case of an unary conversion
8814 /// performed on a function designator of a call expression.
8815 ExprResult CallExprUnaryConversions(Expr *E);
8817 // DefaultFunctionArrayConversion - converts functions and arrays
8818 // to their respective pointers (C99 6.3.2.1).
8819 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8821 // DefaultFunctionArrayLvalueConversion - converts functions and
8822 // arrays to their respective pointers and performs the
8823 // lvalue-to-rvalue conversion.
8824 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8825 bool Diagnose = true);
8827 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8828 // the operand. This is DefaultFunctionArrayLvalueConversion,
8829 // except that it assumes the operand isn't of function or array
8831 ExprResult DefaultLvalueConversion(Expr *E);
8833 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8834 // do not have a prototype. Integer promotions are performed on each
8835 // argument, and arguments that have type float are promoted to double.
8836 ExprResult DefaultArgumentPromotion(Expr *E);
8838 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
8839 /// it as an xvalue. In C++98, the result will still be a prvalue, because
8840 /// we don't have xvalues there.
8841 ExprResult TemporaryMaterializationConversion(Expr *E);
8843 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8844 enum VariadicCallType {
8848 VariadicConstructor,
8849 VariadicDoesNotApply
8852 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8853 const FunctionProtoType *Proto,
8856 // Used for determining in which context a type is allowed to be passed to a
8866 // Determines which VarArgKind fits an expression.
8867 VarArgKind isValidVarArgType(const QualType &Ty);
8869 /// Check to see if the given expression is a valid argument to a variadic
8870 /// function, issuing a diagnostic if not.
8871 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8873 /// Check to see if a given expression could have '.c_str()' called on it.
8874 bool hasCStrMethod(const Expr *E);
8876 /// GatherArgumentsForCall - Collector argument expressions for various
8877 /// form of call prototypes.
8878 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8879 const FunctionProtoType *Proto,
8880 unsigned FirstParam, ArrayRef<Expr *> Args,
8881 SmallVectorImpl<Expr *> &AllArgs,
8882 VariadicCallType CallType = VariadicDoesNotApply,
8883 bool AllowExplicit = false,
8884 bool IsListInitialization = false);
8886 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8887 // will create a runtime trap if the resulting type is not a POD type.
8888 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8889 FunctionDecl *FDecl);
8891 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8892 // operands and then handles various conversions that are common to binary
8893 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8894 // routine returns the first non-arithmetic type found. The client is
8895 // responsible for emitting appropriate error diagnostics.
8896 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8897 bool IsCompAssign = false);
8899 /// AssignConvertType - All of the 'assignment' semantic checks return this
8900 /// enum to indicate whether the assignment was allowed. These checks are
8901 /// done for simple assignments, as well as initialization, return from
8902 /// function, argument passing, etc. The query is phrased in terms of a
8903 /// source and destination type.
8904 enum AssignConvertType {
8905 /// Compatible - the types are compatible according to the standard.
8908 /// PointerToInt - The assignment converts a pointer to an int, which we
8909 /// accept as an extension.
8912 /// IntToPointer - The assignment converts an int to a pointer, which we
8913 /// accept as an extension.
8916 /// FunctionVoidPointer - The assignment is between a function pointer and
8917 /// void*, which the standard doesn't allow, but we accept as an extension.
8918 FunctionVoidPointer,
8920 /// IncompatiblePointer - The assignment is between two pointers types that
8921 /// are not compatible, but we accept them as an extension.
8922 IncompatiblePointer,
8924 /// IncompatiblePointerSign - The assignment is between two pointers types
8925 /// which point to integers which have a different sign, but are otherwise
8926 /// identical. This is a subset of the above, but broken out because it's by
8927 /// far the most common case of incompatible pointers.
8928 IncompatiblePointerSign,
8930 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8931 /// c/v/r qualifiers, which we accept as an extension.
8932 CompatiblePointerDiscardsQualifiers,
8934 /// IncompatiblePointerDiscardsQualifiers - The assignment
8935 /// discards qualifiers that we don't permit to be discarded,
8936 /// like address spaces.
8937 IncompatiblePointerDiscardsQualifiers,
8939 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8940 /// nested pointer types, and the qualifiers other than the first two
8941 /// levels differ e.g. char ** -> const char **, but we accept them as an
8943 IncompatibleNestedPointerQualifiers,
8945 /// IncompatibleVectors - The assignment is between two vector types that
8946 /// have the same size, which we accept as an extension.
8947 IncompatibleVectors,
8949 /// IntToBlockPointer - The assignment converts an int to a block
8950 /// pointer. We disallow this.
8953 /// IncompatibleBlockPointer - The assignment is between two block
8954 /// pointers types that are not compatible.
8955 IncompatibleBlockPointer,
8957 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8958 /// id type and something else (that is incompatible with it). For example,
8959 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8960 IncompatibleObjCQualifiedId,
8962 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8963 /// object with __weak qualifier.
8964 IncompatibleObjCWeakRef,
8966 /// Incompatible - We reject this conversion outright, it is invalid to
8967 /// represent it in the AST.
8971 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8972 /// assignment conversion type specified by ConvTy. This returns true if the
8973 /// conversion was invalid or false if the conversion was accepted.
8974 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8976 QualType DstType, QualType SrcType,
8977 Expr *SrcExpr, AssignmentAction Action,
8978 bool *Complained = nullptr);
8980 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8981 /// enum. If AllowMask is true, then we also allow the complement of a valid
8982 /// value, to be used as a mask.
8983 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8984 bool AllowMask) const;
8986 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8987 /// integer not in the range of enum values.
8988 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8991 /// CheckAssignmentConstraints - Perform type checking for assignment,
8992 /// argument passing, variable initialization, and function return values.
8994 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8998 /// Check assignment constraints and optionally prepare for a conversion of
8999 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9001 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9004 bool ConvertRHS = true);
9006 /// Check assignment constraints for an assignment of RHS to LHSType.
9008 /// \param LHSType The destination type for the assignment.
9009 /// \param RHS The source expression for the assignment.
9010 /// \param Diagnose If \c true, diagnostics may be produced when checking
9011 /// for assignability. If a diagnostic is produced, \p RHS will be
9012 /// set to ExprError(). Note that this function may still return
9013 /// without producing a diagnostic, even for an invalid assignment.
9014 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9015 /// in an audited Core Foundation API and does not need to be checked
9016 /// for ARC retain issues.
9017 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9018 /// conversions necessary to perform the assignment. If \c false,
9019 /// \p Diagnose must also be \c false.
9020 AssignConvertType CheckSingleAssignmentConstraints(
9021 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9022 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9024 // \brief If the lhs type is a transparent union, check whether we
9025 // can initialize the transparent union with the given expression.
9026 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9029 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9031 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9033 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9034 AssignmentAction Action,
9035 bool AllowExplicit = false);
9036 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9037 AssignmentAction Action,
9039 ImplicitConversionSequence& ICS);
9040 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9041 const ImplicitConversionSequence& ICS,
9042 AssignmentAction Action,
9043 CheckedConversionKind CCK
9044 = CCK_ImplicitConversion);
9045 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9046 const StandardConversionSequence& SCS,
9047 AssignmentAction Action,
9048 CheckedConversionKind CCK);
9050 /// the following "Check" methods will return a valid/converted QualType
9051 /// or a null QualType (indicating an error diagnostic was issued).
9053 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9054 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9056 QualType CheckPointerToMemberOperands( // C++ 5.5
9057 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9058 SourceLocation OpLoc, bool isIndirect);
9059 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9060 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9062 QualType CheckRemainderOperands( // C99 6.5.5
9063 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9064 bool IsCompAssign = false);
9065 QualType CheckAdditionOperands( // C99 6.5.6
9066 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9067 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9068 QualType CheckSubtractionOperands( // C99 6.5.6
9069 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9070 QualType* CompLHSTy = nullptr);
9071 QualType CheckShiftOperands( // C99 6.5.7
9072 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9073 BinaryOperatorKind Opc, bool IsCompAssign = false);
9074 QualType CheckCompareOperands( // C99 6.5.8/9
9075 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9076 BinaryOperatorKind Opc, bool isRelational);
9077 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9078 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9079 BinaryOperatorKind Opc);
9080 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9081 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9082 BinaryOperatorKind Opc);
9083 // CheckAssignmentOperands is used for both simple and compound assignment.
9084 // For simple assignment, pass both expressions and a null converted type.
9085 // For compound assignment, pass both expressions and the converted type.
9086 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9087 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9089 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9090 UnaryOperatorKind Opcode, Expr *Op);
9091 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9092 BinaryOperatorKind Opcode,
9093 Expr *LHS, Expr *RHS);
9094 ExprResult checkPseudoObjectRValue(Expr *E);
9095 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9097 QualType CheckConditionalOperands( // C99 6.5.15
9098 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9099 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9100 QualType CXXCheckConditionalOperands( // C++ 5.16
9101 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9102 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9103 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9104 bool ConvertArgs = true);
9105 QualType FindCompositePointerType(SourceLocation Loc,
9106 ExprResult &E1, ExprResult &E2,
9107 bool ConvertArgs = true) {
9108 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9109 QualType Composite =
9110 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9116 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9117 SourceLocation QuestionLoc);
9119 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9120 SourceLocation QuestionLoc);
9122 void DiagnoseAlwaysNonNullPointer(Expr *E,
9123 Expr::NullPointerConstantKind NullType,
9124 bool IsEqual, SourceRange Range);
9126 /// type checking for vector binary operators.
9127 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9128 SourceLocation Loc, bool IsCompAssign,
9129 bool AllowBothBool, bool AllowBoolConversion);
9130 QualType GetSignedVectorType(QualType V);
9131 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9132 SourceLocation Loc, bool isRelational);
9133 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9134 SourceLocation Loc);
9136 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9137 bool isLaxVectorConversion(QualType srcType, QualType destType);
9139 /// type checking declaration initializers (C99 6.7.8)
9140 bool CheckForConstantInitializer(Expr *e, QualType t);
9142 // type checking C++ declaration initializers (C++ [dcl.init]).
9144 /// ReferenceCompareResult - Expresses the result of comparing two
9145 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9146 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9147 enum ReferenceCompareResult {
9148 /// Ref_Incompatible - The two types are incompatible, so direct
9149 /// reference binding is not possible.
9150 Ref_Incompatible = 0,
9151 /// Ref_Related - The two types are reference-related, which means
9152 /// that their unqualified forms (T1 and T2) are either the same
9153 /// or T1 is a base class of T2.
9155 /// Ref_Compatible - The two types are reference-compatible.
9159 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9160 QualType T1, QualType T2,
9161 bool &DerivedToBase,
9162 bool &ObjCConversion,
9163 bool &ObjCLifetimeConversion);
9165 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9166 Expr *CastExpr, CastKind &CastKind,
9167 ExprValueKind &VK, CXXCastPath &Path);
9169 /// \brief Force an expression with unknown-type to an expression of the
9171 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9173 /// \brief Type-check an expression that's being passed to an
9174 /// __unknown_anytype parameter.
9175 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9176 Expr *result, QualType ¶mType);
9178 // CheckVectorCast - check type constraints for vectors.
9179 // Since vectors are an extension, there are no C standard reference for this.
9180 // We allow casting between vectors and integer datatypes of the same size.
9181 // returns true if the cast is invalid
9182 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9185 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9186 /// implicit casts if necessary.
9187 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9189 // CheckExtVectorCast - check type constraints for extended vectors.
9190 // Since vectors are an extension, there are no C standard reference for this.
9191 // We allow casting between vectors and integer datatypes of the same size,
9192 // or vectors and the element type of that vector.
9193 // returns the cast expr
9194 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9197 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
9198 SourceLocation LParenLoc,
9200 SourceLocation RParenLoc);
9202 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9204 /// \brief Checks for invalid conversions and casts between
9205 /// retainable pointers and other pointer kinds.
9206 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
9207 QualType castType, Expr *&op,
9208 CheckedConversionKind CCK,
9209 bool Diagnose = true,
9210 bool DiagnoseCFAudited = false,
9211 BinaryOperatorKind Opc = BO_PtrMemD
9214 Expr *stripARCUnbridgedCast(Expr *e);
9215 void diagnoseARCUnbridgedCast(Expr *e);
9217 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9220 /// checkRetainCycles - Check whether an Objective-C message send
9221 /// might create an obvious retain cycle.
9222 void checkRetainCycles(ObjCMessageExpr *msg);
9223 void checkRetainCycles(Expr *receiver, Expr *argument);
9224 void checkRetainCycles(VarDecl *Var, Expr *Init);
9226 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9227 /// to weak/__unsafe_unretained type.
9228 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9230 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9231 /// to weak/__unsafe_unretained expression.
9232 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9234 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9235 /// \param Method - May be null.
9236 /// \param [out] ReturnType - The return type of the send.
9237 /// \return true iff there were any incompatible types.
9238 bool CheckMessageArgumentTypes(QualType ReceiverType,
9239 MultiExprArg Args, Selector Sel,
9240 ArrayRef<SourceLocation> SelectorLocs,
9241 ObjCMethodDecl *Method, bool isClassMessage,
9242 bool isSuperMessage,
9243 SourceLocation lbrac, SourceLocation rbrac,
9244 SourceRange RecRange,
9245 QualType &ReturnType, ExprValueKind &VK);
9247 /// \brief Determine the result of a message send expression based on
9248 /// the type of the receiver, the method expected to receive the message,
9249 /// and the form of the message send.
9250 QualType getMessageSendResultType(QualType ReceiverType,
9251 ObjCMethodDecl *Method,
9252 bool isClassMessage, bool isSuperMessage);
9254 /// \brief If the given expression involves a message send to a method
9255 /// with a related result type, emit a note describing what happened.
9256 void EmitRelatedResultTypeNote(const Expr *E);
9258 /// \brief Given that we had incompatible pointer types in a return
9259 /// statement, check whether we're in a method with a related result
9260 /// type, and if so, emit a note describing what happened.
9261 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9263 class ConditionResult {
9265 FullExprArg Condition;
9271 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9273 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9274 HasKnownValue(IsConstexpr && Condition.get() &&
9275 !Condition.get()->isValueDependent()),
9276 KnownValue(HasKnownValue &&
9277 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9278 explicit ConditionResult(bool Invalid)
9279 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9280 HasKnownValue(false), KnownValue(false) {}
9283 ConditionResult() : ConditionResult(false) {}
9284 bool isInvalid() const { return Invalid; }
9285 std::pair<VarDecl *, Expr *> get() const {
9286 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9289 llvm::Optional<bool> getKnownValue() const {
9295 static ConditionResult ConditionError() { return ConditionResult(true); }
9297 enum class ConditionKind {
9298 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9299 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9300 Switch ///< An integral condition for a 'switch' statement.
9303 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9304 Expr *SubExpr, ConditionKind CK);
9306 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9307 SourceLocation StmtLoc,
9310 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9312 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9313 SourceLocation StmtLoc,
9315 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9317 /// CheckBooleanCondition - Diagnose problems involving the use of
9318 /// the given expression as a boolean condition (e.g. in an if
9319 /// statement). Also performs the standard function and array
9320 /// decays, possibly changing the input variable.
9322 /// \param Loc - A location associated with the condition, e.g. the
9324 /// \return true iff there were any errors
9325 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9326 bool IsConstexpr = false);
9328 /// DiagnoseAssignmentAsCondition - Given that an expression is
9329 /// being used as a boolean condition, warn if it's an assignment.
9330 void DiagnoseAssignmentAsCondition(Expr *E);
9332 /// \brief Redundant parentheses over an equality comparison can indicate
9333 /// that the user intended an assignment used as condition.
9334 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9336 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9337 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9339 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9340 /// the specified width and sign. If an overflow occurs, detect it and emit
9341 /// the specified diagnostic.
9342 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9343 unsigned NewWidth, bool NewSign,
9344 SourceLocation Loc, unsigned DiagID);
9346 /// Checks that the Objective-C declaration is declared in the global scope.
9347 /// Emits an error and marks the declaration as invalid if it's not declared
9348 /// in the global scope.
9349 bool CheckObjCDeclScope(Decl *D);
9351 /// \brief Abstract base class used for diagnosing integer constant
9352 /// expression violations.
9353 class VerifyICEDiagnoser {
9357 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9359 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9360 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9361 virtual ~VerifyICEDiagnoser() { }
9364 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9365 /// and reports the appropriate diagnostics. Returns false on success.
9366 /// Can optionally return the value of the expression.
9367 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9368 VerifyICEDiagnoser &Diagnoser,
9369 bool AllowFold = true);
9370 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9372 bool AllowFold = true);
9373 ExprResult VerifyIntegerConstantExpression(Expr *E,
9374 llvm::APSInt *Result = nullptr);
9376 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9377 /// the correct width, and that the field type is valid.
9378 /// Returns false on success.
9379 /// Can optionally return whether the bit-field is of width 0
9380 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9381 QualType FieldTy, bool IsMsStruct,
9382 Expr *BitWidth, bool *ZeroWidth = nullptr);
9385 unsigned ForceCUDAHostDeviceDepth = 0;
9388 /// Increments our count of the number of times we've seen a pragma forcing
9389 /// functions to be __host__ __device__. So long as this count is greater
9390 /// than zero, all functions encountered will be __host__ __device__.
9391 void PushForceCUDAHostDevice();
9393 /// Decrements our count of the number of times we've seen a pragma forcing
9394 /// functions to be __host__ __device__. Returns false if the count is 0
9395 /// before incrementing, so you can emit an error.
9396 bool PopForceCUDAHostDevice();
9398 /// Diagnostics that are emitted only if we discover that the given function
9399 /// must be codegen'ed. Because handling these correctly adds overhead to
9400 /// compilation, this is currently only enabled for CUDA compilations.
9401 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9402 std::vector<PartialDiagnosticAt>>
9405 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9406 /// key in a hashtable, both the FD and location are hashed.
9407 struct FunctionDeclAndLoc {
9408 CanonicalDeclPtr<FunctionDecl> FD;
9412 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9413 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9414 /// same deferred diag twice.
9415 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9417 /// An inverse call graph, mapping known-emitted functions to one of their
9418 /// known-emitted callers (plus the location of the call).
9420 /// Functions that we can tell a priori must be emitted aren't added to this
9422 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9423 /* Caller = */ FunctionDeclAndLoc>
9424 CUDAKnownEmittedFns;
9426 /// A partial call graph maintained during CUDA compilation to support
9427 /// deferred diagnostics.
9429 /// Functions are only added here if, at the time they're considered, they are
9430 /// not known-emitted. As soon as we discover that a function is
9431 /// known-emitted, we remove it and everything it transitively calls from this
9432 /// set and add those functions to CUDAKnownEmittedFns.
9433 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9434 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9438 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9440 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9441 /// which are not allowed to appear inside __device__ functions and are
9442 /// allowed to appear in __host__ __device__ functions only if the host+device
9443 /// function is never codegen'ed.
9445 /// To handle this, we use the notion of "deferred diagnostics", where we
9446 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9448 /// This class lets you emit either a regular diagnostic, a deferred
9449 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9450 /// its constructor, thus simplifying the process of creating these "maybe
9451 /// deferred" diagnostics.
9452 class CUDADiagBuilder {
9455 /// Emit no diagnostics.
9457 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9459 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9460 /// emit a call stack showing how this function can be reached by an a
9461 /// priori known-emitted function.
9462 K_ImmediateWithCallStack,
9463 /// Create a deferred diagnostic, which is emitted only if the function
9464 /// it's attached to is codegen'ed. Also emit a call stack as with
9465 /// K_ImmediateWithCallStack.
9469 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9470 FunctionDecl *Fn, Sema &S);
9473 /// Convertible to bool: True if we immediately emitted an error, false if
9474 /// we didn't emit an error or we created a deferred error.
9478 /// if (CUDADiagBuilder(...) << foo << bar)
9479 /// return ExprError();
9481 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9482 /// want to use these instead of creating a CUDADiagBuilder yourself.
9483 operator bool() const { return ImmediateDiag.hasValue(); }
9485 template <typename T>
9486 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9488 if (Diag.ImmediateDiag.hasValue())
9489 *Diag.ImmediateDiag << Value;
9490 else if (Diag.PartialDiag.hasValue())
9491 *Diag.PartialDiag << Value;
9502 // Invariant: At most one of these Optionals has a value.
9503 // FIXME: Switch these to a Variant once that exists.
9504 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9505 llvm::Optional<PartialDiagnostic> PartialDiag;
9508 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9509 /// is "used as device code".
9511 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9512 /// - If CurContext is a __device__ or __global__ function, emits the
9513 /// diagnostics immediately.
9514 /// - If CurContext is a __host__ __device__ function and we are compiling for
9515 /// the device, creates a diagnostic which is emitted if and when we realize
9516 /// that the function will be codegen'ed.
9520 /// // Variable-length arrays are not allowed in CUDA device code.
9521 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9522 /// return ExprError();
9523 /// // Otherwise, continue parsing as normal.
9524 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9526 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9527 /// is "used as host code".
9529 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9530 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9532 enum CUDAFunctionTarget {
9540 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9543 /// Use this rather than examining the function's attributes yourself -- you
9544 /// will get it wrong. Returns CFT_Host if D is null.
9545 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9546 bool IgnoreImplicitHDAttr = false);
9547 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9549 /// Gets the CUDA target for the current context.
9550 CUDAFunctionTarget CurrentCUDATarget() {
9551 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9554 // CUDA function call preference. Must be ordered numerically from
9556 enum CUDAFunctionPreference {
9557 CFP_Never, // Invalid caller/callee combination.
9558 CFP_WrongSide, // Calls from host-device to host or device
9559 // function that do not match current compilation
9561 CFP_HostDevice, // Any calls to host/device functions.
9562 CFP_SameSide, // Calls from host-device to host or device
9563 // function matching current compilation mode.
9564 CFP_Native, // host-to-host or device-to-device calls.
9567 /// Identifies relative preference of a given Caller/Callee
9568 /// combination, based on their host/device attributes.
9569 /// \param Caller function which needs address of \p Callee.
9570 /// nullptr in case of global context.
9571 /// \param Callee target function
9573 /// \returns preference value for particular Caller/Callee combination.
9574 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9575 const FunctionDecl *Callee);
9577 /// Determines whether Caller may invoke Callee, based on their CUDA
9578 /// host/device attributes. Returns false if the call is not allowed.
9580 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9581 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9582 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9583 const FunctionDecl *Callee) {
9584 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9587 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9588 /// depending on FD and the current compilation settings.
9589 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9590 const LookupResult &Previous);
9593 /// Check whether we're allowed to call Callee from the current context.
9595 /// - If the call is never allowed in a semantically-correct program
9596 /// (CFP_Never), emits an error and returns false.
9598 /// - If the call is allowed in semantically-correct programs, but only if
9599 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9600 /// be emitted if and when the caller is codegen'ed, and returns true.
9602 /// Will only create deferred diagnostics for a given SourceLocation once,
9603 /// so you can safely call this multiple times without generating duplicate
9604 /// deferred errors.
9606 /// - Otherwise, returns true without emitting any diagnostics.
9607 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9609 /// Set __device__ or __host__ __device__ attributes on the given lambda
9610 /// operator() method.
9612 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9613 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9614 /// functions become __host__ __device__ themselves.
9615 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9617 /// Finds a function in \p Matches with highest calling priority
9618 /// from \p Caller context and erases all functions with lower
9619 /// calling priority.
9620 void EraseUnwantedCUDAMatches(
9621 const FunctionDecl *Caller,
9622 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9624 /// Given a implicit special member, infer its CUDA target from the
9625 /// calls it needs to make to underlying base/field special members.
9626 /// \param ClassDecl the class for which the member is being created.
9627 /// \param CSM the kind of special member.
9628 /// \param MemberDecl the special member itself.
9629 /// \param ConstRHS true if this is a copy operation with a const object on
9631 /// \param Diagnose true if this call should emit diagnostics.
9632 /// \return true if there was an error inferring.
9633 /// The result of this call is implicit CUDA target attribute(s) attached to
9634 /// the member declaration.
9635 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9636 CXXSpecialMember CSM,
9637 CXXMethodDecl *MemberDecl,
9641 /// \return true if \p CD can be considered empty according to CUDA
9642 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9643 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9644 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9646 /// Check whether NewFD is a valid overload for CUDA. Emits
9647 /// diagnostics and invalidates NewFD if not.
9648 void checkCUDATargetOverload(FunctionDecl *NewFD,
9649 const LookupResult &Previous);
9650 /// Copies target attributes from the template TD to the function FD.
9651 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9653 /// \name Code completion
9655 /// \brief Describes the context in which code completion occurs.
9656 enum ParserCompletionContext {
9657 /// \brief Code completion occurs at top-level or namespace context.
9659 /// \brief Code completion occurs within a class, struct, or union.
9661 /// \brief Code completion occurs within an Objective-C interface, protocol,
9664 /// \brief Code completion occurs within an Objective-C implementation or
9665 /// category implementation
9666 PCC_ObjCImplementation,
9667 /// \brief Code completion occurs within the list of instance variables
9668 /// in an Objective-C interface, protocol, category, or implementation.
9669 PCC_ObjCInstanceVariableList,
9670 /// \brief Code completion occurs following one or more template
9673 /// \brief Code completion occurs following one or more template
9674 /// headers within a class.
9676 /// \brief Code completion occurs within an expression.
9678 /// \brief Code completion occurs within a statement, which may
9679 /// also be an expression or a declaration.
9681 /// \brief Code completion occurs at the beginning of the
9682 /// initialization statement (or expression) in a for loop.
9684 /// \brief Code completion occurs within the condition of an if,
9685 /// while, switch, or for statement.
9687 /// \brief Code completion occurs within the body of a function on a
9688 /// recovery path, where we do not have a specific handle on our position
9690 PCC_RecoveryInFunction,
9691 /// \brief Code completion occurs where only a type is permitted.
9693 /// \brief Code completion occurs in a parenthesized expression, which
9694 /// might also be a type cast.
9695 PCC_ParenthesizedExpression,
9696 /// \brief Code completion occurs within a sequence of declaration
9697 /// specifiers within a function, method, or block.
9698 PCC_LocalDeclarationSpecifiers
9701 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9702 void CodeCompleteOrdinaryName(Scope *S,
9703 ParserCompletionContext CompletionContext);
9704 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9705 bool AllowNonIdentifiers,
9706 bool AllowNestedNameSpecifiers);
9708 struct CodeCompleteExpressionData;
9709 void CodeCompleteExpression(Scope *S,
9710 const CodeCompleteExpressionData &Data);
9711 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9712 SourceLocation OpLoc, bool IsArrow,
9713 bool IsBaseExprStatement);
9714 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9715 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9716 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9717 void CodeCompleteBracketDeclarator(Scope *S);
9718 void CodeCompleteCase(Scope *S);
9719 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9720 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9721 ArrayRef<Expr *> Args);
9722 void CodeCompleteInitializer(Scope *S, Decl *D);
9723 void CodeCompleteReturn(Scope *S);
9724 void CodeCompleteAfterIf(Scope *S);
9725 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9727 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9728 bool EnteringContext);
9729 void CodeCompleteUsing(Scope *S);
9730 void CodeCompleteUsingDirective(Scope *S);
9731 void CodeCompleteNamespaceDecl(Scope *S);
9732 void CodeCompleteNamespaceAliasDecl(Scope *S);
9733 void CodeCompleteOperatorName(Scope *S);
9734 void CodeCompleteConstructorInitializer(
9736 ArrayRef<CXXCtorInitializer *> Initializers);
9738 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9739 bool AfterAmpersand);
9741 void CodeCompleteObjCAtDirective(Scope *S);
9742 void CodeCompleteObjCAtVisibility(Scope *S);
9743 void CodeCompleteObjCAtStatement(Scope *S);
9744 void CodeCompleteObjCAtExpression(Scope *S);
9745 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9746 void CodeCompleteObjCPropertyGetter(Scope *S);
9747 void CodeCompleteObjCPropertySetter(Scope *S);
9748 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9750 void CodeCompleteObjCMessageReceiver(Scope *S);
9751 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9752 ArrayRef<IdentifierInfo *> SelIdents,
9753 bool AtArgumentExpression);
9754 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9755 ArrayRef<IdentifierInfo *> SelIdents,
9756 bool AtArgumentExpression,
9757 bool IsSuper = false);
9758 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9759 ArrayRef<IdentifierInfo *> SelIdents,
9760 bool AtArgumentExpression,
9761 ObjCInterfaceDecl *Super = nullptr);
9762 void CodeCompleteObjCForCollection(Scope *S,
9763 DeclGroupPtrTy IterationVar);
9764 void CodeCompleteObjCSelector(Scope *S,
9765 ArrayRef<IdentifierInfo *> SelIdents);
9766 void CodeCompleteObjCProtocolReferences(
9767 ArrayRef<IdentifierLocPair> Protocols);
9768 void CodeCompleteObjCProtocolDecl(Scope *S);
9769 void CodeCompleteObjCInterfaceDecl(Scope *S);
9770 void CodeCompleteObjCSuperclass(Scope *S,
9771 IdentifierInfo *ClassName,
9772 SourceLocation ClassNameLoc);
9773 void CodeCompleteObjCImplementationDecl(Scope *S);
9774 void CodeCompleteObjCInterfaceCategory(Scope *S,
9775 IdentifierInfo *ClassName,
9776 SourceLocation ClassNameLoc);
9777 void CodeCompleteObjCImplementationCategory(Scope *S,
9778 IdentifierInfo *ClassName,
9779 SourceLocation ClassNameLoc);
9780 void CodeCompleteObjCPropertyDefinition(Scope *S);
9781 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9782 IdentifierInfo *PropertyName);
9783 void CodeCompleteObjCMethodDecl(Scope *S,
9784 bool IsInstanceMethod,
9785 ParsedType ReturnType);
9786 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9787 bool IsInstanceMethod,
9788 bool AtParameterName,
9789 ParsedType ReturnType,
9790 ArrayRef<IdentifierInfo *> SelIdents);
9791 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
9792 SourceLocation ClassNameLoc,
9793 bool IsBaseExprStatement);
9794 void CodeCompletePreprocessorDirective(bool InConditional);
9795 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9796 void CodeCompletePreprocessorMacroName(bool IsDefinition);
9797 void CodeCompletePreprocessorExpression();
9798 void CodeCompletePreprocessorMacroArgument(Scope *S,
9799 IdentifierInfo *Macro,
9800 MacroInfo *MacroInfo,
9802 void CodeCompleteNaturalLanguage();
9803 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9804 CodeCompletionTUInfo &CCTUInfo,
9805 SmallVectorImpl<CodeCompletionResult> &Results);
9808 //===--------------------------------------------------------------------===//
9809 // Extra semantic analysis beyond the C type system
9812 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9813 unsigned ByteNo) const;
9816 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9817 const ArraySubscriptExpr *ASE=nullptr,
9818 bool AllowOnePastEnd=true, bool IndexNegated=false);
9819 void CheckArrayAccess(const Expr *E);
9820 // Used to grab the relevant information from a FormatAttr and a
9821 // FunctionDeclaration.
9822 struct FormatStringInfo {
9824 unsigned FirstDataArg;
9828 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9829 FormatStringInfo *FSI);
9830 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9831 const FunctionProtoType *Proto);
9832 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9833 ArrayRef<const Expr *> Args);
9834 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9835 const FunctionProtoType *Proto);
9836 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9837 void CheckConstructorCall(FunctionDecl *FDecl,
9838 ArrayRef<const Expr *> Args,
9839 const FunctionProtoType *Proto,
9840 SourceLocation Loc);
9842 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
9843 ArrayRef<const Expr *> Args, bool IsMemberFunction,
9844 SourceLocation Loc, SourceRange Range,
9845 VariadicCallType CallType);
9847 bool CheckObjCString(Expr *Arg);
9848 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
9850 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
9851 unsigned BuiltinID, CallExpr *TheCall);
9853 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
9855 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9856 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9858 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9859 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9860 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9861 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
9862 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9863 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9865 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
9866 bool SemaBuiltinVAStart(CallExpr *TheCall);
9867 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
9868 bool SemaBuiltinVAStartARM(CallExpr *Call);
9869 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
9870 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
9871 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
9874 // Used by C++ template instantiation.
9875 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
9876 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
9877 SourceLocation BuiltinLoc,
9878 SourceLocation RParenLoc);
9881 bool SemaBuiltinPrefetch(CallExpr *TheCall);
9882 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
9883 bool SemaBuiltinAssume(CallExpr *TheCall);
9884 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
9885 bool SemaBuiltinLongjmp(CallExpr *TheCall);
9886 bool SemaBuiltinSetjmp(CallExpr *TheCall);
9887 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
9888 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
9889 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
9890 AtomicExpr::AtomicOp Op);
9891 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
9892 llvm::APSInt &Result);
9893 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
9895 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
9897 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
9898 int ArgNum, unsigned ExpectedFieldNum,
9901 enum FormatStringType {
9913 static FormatStringType GetFormatStringType(const FormatAttr *Format);
9915 bool FormatStringHasSArg(const StringLiteral *FExpr);
9917 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
9920 bool CheckFormatArguments(const FormatAttr *Format,
9921 ArrayRef<const Expr *> Args,
9923 VariadicCallType CallType,
9924 SourceLocation Loc, SourceRange Range,
9925 llvm::SmallBitVector &CheckedVarArgs);
9926 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
9927 bool HasVAListArg, unsigned format_idx,
9928 unsigned firstDataArg, FormatStringType Type,
9929 VariadicCallType CallType,
9930 SourceLocation Loc, SourceRange range,
9931 llvm::SmallBitVector &CheckedVarArgs);
9933 void CheckAbsoluteValueFunction(const CallExpr *Call,
9934 const FunctionDecl *FDecl);
9936 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
9938 void CheckMemaccessArguments(const CallExpr *Call,
9940 IdentifierInfo *FnName);
9942 void CheckStrlcpycatArguments(const CallExpr *Call,
9943 IdentifierInfo *FnName);
9945 void CheckStrncatArguments(const CallExpr *Call,
9946 IdentifierInfo *FnName);
9948 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9949 SourceLocation ReturnLoc,
9950 bool isObjCMethod = false,
9951 const AttrVec *Attrs = nullptr,
9952 const FunctionDecl *FD = nullptr);
9954 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
9955 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
9956 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
9957 void CheckForIntOverflow(Expr *E);
9958 void CheckUnsequencedOperations(Expr *E);
9960 /// \brief Perform semantic checks on a completed expression. This will either
9961 /// be a full-expression or a default argument expression.
9962 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
9963 bool IsConstexpr = false);
9965 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
9968 /// \brief Check if the given expression contains 'break' or 'continue'
9969 /// statement that produces control flow different from GCC.
9970 void CheckBreakContinueBinding(Expr *E);
9972 /// \brief Check whether receiver is mutable ObjC container which
9973 /// attempts to add itself into the container
9974 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
9976 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9977 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9978 bool DeleteWasArrayForm);
9980 /// \brief Register a magic integral constant to be used as a type tag.
9981 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9982 uint64_t MagicValue, QualType Type,
9983 bool LayoutCompatible, bool MustBeNull);
9985 struct TypeTagData {
9988 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
9989 Type(Type), LayoutCompatible(LayoutCompatible),
9990 MustBeNull(MustBeNull)
9995 /// If true, \c Type should be compared with other expression's types for
9996 /// layout-compatibility.
9997 unsigned LayoutCompatible : 1;
9998 unsigned MustBeNull : 1;
10001 /// A pair of ArgumentKind identifier and magic value. This uniquely
10002 /// identifies the magic value.
10003 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10006 /// \brief A map from magic value to type information.
10007 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10008 TypeTagForDatatypeMagicValues;
10010 /// \brief Peform checks on a call of a function with argument_with_type_tag
10011 /// or pointer_with_type_tag attributes.
10012 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10013 const Expr * const *ExprArgs);
10015 /// \brief Check if we are taking the address of a packed field
10016 /// as this may be a problem if the pointer value is dereferenced.
10017 void CheckAddressOfPackedMember(Expr *rhs);
10019 /// \brief The parser's current scope.
10021 /// The parser maintains this state here.
10024 mutable IdentifierInfo *Ident_super;
10025 mutable IdentifierInfo *Ident___float128;
10027 /// Nullability type specifiers.
10028 IdentifierInfo *Ident__Nonnull = nullptr;
10029 IdentifierInfo *Ident__Nullable = nullptr;
10030 IdentifierInfo *Ident__Null_unspecified = nullptr;
10032 IdentifierInfo *Ident_NSError = nullptr;
10035 friend class Parser;
10036 friend class InitializationSequence;
10037 friend class ASTReader;
10038 friend class ASTDeclReader;
10039 friend class ASTWriter;
10042 /// Retrieve the keyword associated
10043 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10045 /// The struct behind the CFErrorRef pointer.
10046 RecordDecl *CFError = nullptr;
10048 /// Retrieve the identifier "NSError".
10049 IdentifierInfo *getNSErrorIdent();
10051 /// \brief Retrieve the parser's current scope.
10053 /// This routine must only be used when it is certain that semantic analysis
10054 /// and the parser are in precisely the same context, which is not the case
10055 /// when, e.g., we are performing any kind of template instantiation.
10056 /// Therefore, the only safe places to use this scope are in the parser
10057 /// itself and in routines directly invoked from the parser and *never* from
10058 /// template substitution or instantiation.
10059 Scope *getCurScope() const { return CurScope; }
10061 void incrementMSManglingNumber() const {
10062 return CurScope->incrementMSManglingNumber();
10065 IdentifierInfo *getSuperIdentifier() const;
10066 IdentifierInfo *getFloat128Identifier() const;
10068 Decl *getObjCDeclContext() const;
10070 DeclContext *getCurLexicalContext() const {
10071 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10074 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10076 /// \param D The declaration to check. Note that this may be altered to point
10077 /// to another declaration that \c D gets it's availability from. i.e., we
10078 /// walk the list of typedefs to find an availability attribute.
10080 /// \param Message If non-null, this will be populated with the message from
10081 /// the availability attribute that is selected.
10082 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10083 std::string *Message);
10085 const DeclContext *getCurObjCLexicalContext() const {
10086 const DeclContext *DC = getCurLexicalContext();
10087 // A category implicitly has the attribute of the interface.
10088 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10089 DC = CatD->getClassInterface();
10093 /// \brief To be used for checking whether the arguments being passed to
10094 /// function exceeds the number of parameters expected for it.
10095 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10096 bool PartialOverloading = false) {
10097 // We check whether we're just after a comma in code-completion.
10098 if (NumArgs > 0 && PartialOverloading)
10099 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10100 return NumArgs > NumParams;
10103 // Emitting members of dllexported classes is delayed until the class
10104 // (including field initializers) is fully parsed.
10105 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10108 /// \brief Helper class that collects misaligned member designations and
10109 /// their location info for delayed diagnostics.
10110 struct MisalignedMember {
10114 CharUnits Alignment;
10116 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10117 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10118 CharUnits Alignment)
10119 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10120 explicit MisalignedMember(Expr *E)
10121 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10123 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10125 /// \brief Small set of gathered accesses to potentially misaligned members
10126 /// due to the packed attribute.
10127 SmallVector<MisalignedMember, 4> MisalignedMembers;
10129 /// \brief Adds an expression to the set of gathered misaligned members.
10130 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10131 CharUnits Alignment);
10134 /// \brief Diagnoses the current set of gathered accesses. This typically
10135 /// happens at full expression level. The set is cleared after emitting the
10137 void DiagnoseMisalignedMembers();
10139 /// \brief This function checks if the expression is in the sef of potentially
10140 /// misaligned members and it is converted to some pointer type T with lower
10141 /// or equal alignment requirements. If so it removes it. This is used when
10142 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10144 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10146 /// \brief This function calls Action when it determines that E designates a
10147 /// misaligned member due to the packed attribute. This is used to emit
10148 /// local diagnostics like in reference binding.
10149 void RefersToMemberWithReducedAlignment(
10151 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10155 /// \brief RAII object that enters a new expression evaluation context.
10156 class EnterExpressionEvaluationContext {
10158 bool Entered = true;
10161 EnterExpressionEvaluationContext(Sema &Actions,
10162 Sema::ExpressionEvaluationContext NewContext,
10163 Decl *LambdaContextDecl = nullptr,
10164 bool IsDecltype = false,
10165 bool ShouldEnter = true)
10166 : Actions(Actions), Entered(ShouldEnter) {
10168 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10171 EnterExpressionEvaluationContext(Sema &Actions,
10172 Sema::ExpressionEvaluationContext NewContext,
10173 Sema::ReuseLambdaContextDecl_t,
10174 bool IsDecltype = false)
10175 : Actions(Actions) {
10176 Actions.PushExpressionEvaluationContext(NewContext,
10177 Sema::ReuseLambdaContextDecl,
10181 ~EnterExpressionEvaluationContext() {
10183 Actions.PopExpressionEvaluationContext();
10187 DeductionFailureInfo
10188 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10189 sema::TemplateDeductionInfo &Info);
10191 /// \brief Contains a late templated function.
10192 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10193 struct LateParsedTemplate {
10195 /// \brief The template function declaration to be late parsed.
10199 } // end namespace clang
10202 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10204 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10205 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10206 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10208 static FunctionDeclAndLoc getEmptyKey() {
10209 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10212 static FunctionDeclAndLoc getTombstoneKey() {
10213 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10216 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10217 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10218 FDL.Loc.getRawEncoding());
10221 static bool isEqual(const FunctionDeclAndLoc &LHS,
10222 const FunctionDeclAndLoc &RHS) {
10223 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10226 } // namespace llvm