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/Expr.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExternalASTSource.h"
24 #include "clang/AST/LocInfoType.h"
25 #include "clang/AST/MangleNumberingContext.h"
26 #include "clang/AST/NSAPI.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ExpressionTraits.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/Module.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Basic/PragmaKinds.h"
34 #include "clang/Basic/Specifiers.h"
35 #include "clang/Basic/TemplateKinds.h"
36 #include "clang/Basic/TypeTraits.h"
37 #include "clang/Sema/AnalysisBasedWarnings.h"
38 #include "clang/Sema/CleanupInfo.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/ExternalSemaSource.h"
41 #include "clang/Sema/IdentifierResolver.h"
42 #include "clang/Sema/ObjCMethodList.h"
43 #include "clang/Sema/Ownership.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/TypoCorrection.h"
47 #include "clang/Sema/Weak.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/Optional.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/TinyPtrVector.h"
61 template <typename ValueT> struct DenseMapInfo;
62 template <typename ValueT, typename ValueInfoT> class DenseSet;
64 class InlineAsmIdentifierInfo;
71 class ASTMutationListener;
80 class CXXBindTemporaryExpr;
81 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
82 class CXXConstructorDecl;
83 class CXXConversionDecl;
85 class CXXDestructorDecl;
86 class CXXFieldCollector;
87 class CXXMemberCallExpr;
93 class ClassTemplateDecl;
94 class ClassTemplatePartialSpecializationDecl;
95 class ClassTemplateSpecializationDecl;
96 class VarTemplatePartialSpecializationDecl;
97 class CodeCompleteConsumer;
98 class CodeCompletionAllocator;
99 class CodeCompletionTUInfo;
100 class CodeCompletionResult;
102 class DeclAccessPair;
105 class DeclaratorDecl;
106 class DeducedTemplateArgument;
107 class DependentDiagnostic;
108 class DesignatedInitExpr;
111 class EnumConstantDecl;
117 class FunctionProtoType;
118 class FunctionTemplateDecl;
119 class ImplicitConversionSequence;
121 class InitializationKind;
122 class InitializationSequence;
123 class InitializedEntity;
124 class IntegerLiteral;
128 class LocalInstantiationScope;
131 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
133 class MultiLevelTemplateArgumentList;
135 class ObjCCategoryDecl;
136 class ObjCCategoryImplDecl;
137 class ObjCCompatibleAliasDecl;
138 class ObjCContainerDecl;
140 class ObjCImplementationDecl;
141 class ObjCInterfaceDecl;
143 template <class T> class ObjCList;
144 class ObjCMessageExpr;
145 class ObjCMethodDecl;
146 class ObjCPropertyDecl;
147 class ObjCProtocolDecl;
148 class OMPThreadPrivateDecl;
149 class OMPDeclareReductionDecl;
150 class OMPDeclareSimdDecl;
152 struct OverloadCandidate;
153 class OverloadCandidateSet;
158 class PseudoDestructorTypeStorage;
159 class PseudoObjectExpr;
161 class StandardConversionSequence;
165 class TemplateArgument;
166 class TemplateArgumentList;
167 class TemplateArgumentLoc;
169 class TemplateParameterList;
170 class TemplatePartialOrderingContext;
171 class TemplateTemplateParmDecl;
175 class TypedefNameDecl;
177 class TypoCorrectionConsumer;
179 class UnresolvedLookupExpr;
180 class UnresolvedMemberExpr;
181 class UnresolvedSetImpl;
182 class UnresolvedSetIterator;
184 class UsingShadowDecl;
187 class VarTemplateSpecializationDecl;
188 class VisibilityAttr;
189 class VisibleDeclConsumer;
190 class IndirectFieldDecl;
191 struct DeductionFailureInfo;
192 class TemplateSpecCandidateSet;
195 class AccessedEntity;
196 class BlockScopeInfo;
197 class CapturedRegionScopeInfo;
198 class CapturingScopeInfo;
199 class CompoundScopeInfo;
200 class DelayedDiagnostic;
201 class DelayedDiagnosticPool;
202 class FunctionScopeInfo;
203 class LambdaScopeInfo;
204 class PossiblyUnreachableDiag;
205 class TemplateDeductionInfo;
208 namespace threadSafety {
210 void threadSafetyCleanup(BeforeSet* Cache);
213 // FIXME: No way to easily map from TemplateTypeParmTypes to
214 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
215 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
216 SourceLocation> UnexpandedParameterPack;
218 /// Describes whether we've seen any nullability information for the given
220 struct FileNullability {
221 /// The first pointer declarator (of any pointer kind) in the file that does
222 /// not have a corresponding nullability annotation.
223 SourceLocation PointerLoc;
225 /// Which kind of pointer declarator we saw.
228 /// Whether we saw any type nullability annotations in the given file.
229 bool SawTypeNullability = false;
232 /// A mapping from file IDs to a record of whether we've seen nullability
233 /// information in that file.
234 class FileNullabilityMap {
235 /// A mapping from file IDs to the nullability information for each file ID.
236 llvm::DenseMap<FileID, FileNullability> Map;
238 /// A single-element cache based on the file ID.
241 FileNullability Nullability;
245 FileNullability &operator[](FileID file) {
246 // Check the single-element cache.
247 if (file == Cache.File)
248 return Cache.Nullability;
250 // It's not in the single-element cache; flush the cache if we have one.
251 if (!Cache.File.isInvalid()) {
252 Map[Cache.File] = Cache.Nullability;
255 // Pull this entry into the cache.
257 Cache.Nullability = Map[file];
258 return Cache.Nullability;
262 /// Sema - This implements semantic analysis and AST building for C.
264 Sema(const Sema &) = delete;
265 void operator=(const Sema &) = delete;
267 ///\brief Source of additional semantic information.
268 ExternalSemaSource *ExternalSource;
270 ///\brief Whether Sema has generated a multiplexer and has to delete it.
271 bool isMultiplexExternalSource;
273 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
275 bool isVisibleSlow(const NamedDecl *D);
277 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
278 const NamedDecl *New) {
279 // We are about to link these. It is now safe to compute the linkage of
280 // the new decl. If the new decl has external linkage, we will
281 // link it with the hidden decl (which also has external linkage) and
282 // it will keep having external linkage. If it has internal linkage, we
283 // will not link it. Since it has no previous decls, it will remain
284 // with internal linkage.
285 return isVisible(Old) || New->isExternallyVisible();
287 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
290 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
291 typedef OpaquePtr<TemplateName> TemplateTy;
292 typedef OpaquePtr<QualType> TypeTy;
294 OpenCLOptions OpenCLFeatures;
295 FPOptions FPFeatures;
297 const LangOptions &LangOpts;
300 ASTConsumer &Consumer;
301 DiagnosticsEngine &Diags;
302 SourceManager &SourceMgr;
304 /// \brief Flag indicating whether or not to collect detailed statistics.
307 /// \brief Code-completion consumer.
308 CodeCompleteConsumer *CodeCompleter;
310 /// CurContext - This is the current declaration context of parsing.
311 DeclContext *CurContext;
313 /// \brief Generally null except when we temporarily switch decl contexts,
314 /// like in \see ActOnObjCTemporaryExitContainerContext.
315 DeclContext *OriginalLexicalContext;
317 /// VAListTagName - The declaration name corresponding to __va_list_tag.
318 /// This is used as part of a hack to omit that class from ADL results.
319 DeclarationName VAListTagName;
321 bool MSStructPragmaOn; // True when \#pragma ms_struct on
323 /// \brief Controls member pointer representation format under the MS ABI.
324 LangOptions::PragmaMSPointersToMembersKind
325 MSPointerToMemberRepresentationMethod;
327 /// Stack of active SEH __finally scopes. Can be empty.
328 SmallVector<Scope*, 2> CurrentSEHFinally;
330 /// \brief Source location for newly created implicit MSInheritanceAttrs
331 SourceLocation ImplicitMSInheritanceAttrLoc;
333 enum PragmaMsStackAction {
334 PSK_Reset = 0x0, // #pragma ()
335 PSK_Set = 0x1, // #pragma (value)
336 PSK_Push = 0x2, // #pragma (push[, id])
337 PSK_Pop = 0x4, // #pragma (pop[, id])
338 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
339 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
340 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
343 template<typename ValueType>
346 llvm::StringRef StackSlotLabel;
348 SourceLocation PragmaLocation;
349 Slot(llvm::StringRef StackSlotLabel,
351 SourceLocation PragmaLocation)
352 : StackSlotLabel(StackSlotLabel), Value(Value),
353 PragmaLocation(PragmaLocation) {}
355 void Act(SourceLocation PragmaLocation,
356 PragmaMsStackAction Action,
357 llvm::StringRef StackSlotLabel,
360 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
361 // method body to restore the stacks on exit, so it works like this:
364 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
366 // #pragma <name>(pop, InternalPragmaSlot)
369 // It works even with #pragma vtordisp, although MSVC doesn't support
370 // #pragma vtordisp(push [, id], n)
373 // Push / pop a named sentinel slot.
374 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
375 assert((Action == PSK_Push || Action == PSK_Pop) &&
376 "Can only push / pop #pragma stack sentinels!");
377 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
381 explicit PragmaStack(const ValueType &Default)
382 : DefaultValue(Default), CurrentValue(Default) {}
384 SmallVector<Slot, 2> Stack;
385 ValueType DefaultValue; // Value used for PSK_Reset action.
386 ValueType CurrentValue;
387 SourceLocation CurrentPragmaLocation;
389 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
390 // we shouldn't do so if they're in a module).
392 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
393 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
395 /// 0: Suppress all vtordisps
396 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
398 /// 2: Always insert vtordisps to support RTTI on partially constructed
400 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
402 // Sentinel to represent when the stack is set to mac68k alignment.
403 static const unsigned kMac68kAlignmentSentinel = ~0U;
404 PragmaStack<unsigned> PackStack;
406 PragmaStack<StringLiteral *> DataSegStack;
407 PragmaStack<StringLiteral *> BSSSegStack;
408 PragmaStack<StringLiteral *> ConstSegStack;
409 PragmaStack<StringLiteral *> CodeSegStack;
411 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
412 // Actions should be performed only if we enter / exit a C++ method body.
413 class PragmaStackSentinelRAII {
415 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
416 ~PragmaStackSentinelRAII();
424 /// A mapping that describes the nullability we've seen in each header file.
425 FileNullabilityMap NullabilityMap;
427 /// Last section used with #pragma init_seg.
428 StringLiteral *CurInitSeg;
429 SourceLocation CurInitSegLoc;
431 /// VisContext - Manages the stack for \#pragma GCC visibility.
432 void *VisContext; // Really a "PragmaVisStack*"
434 /// \brief This represents the last location of a "#pragma clang optimize off"
435 /// directive if such a directive has not been closed by an "on" yet. If
436 /// optimizations are currently "on", this is set to an invalid location.
437 SourceLocation OptimizeOffPragmaLocation;
439 /// \brief Flag indicating if Sema is building a recovery call expression.
441 /// This flag is used to avoid building recovery call expressions
442 /// if Sema is already doing so, which would cause infinite recursions.
443 bool IsBuildingRecoveryCallExpr;
445 /// Used to control the generation of ExprWithCleanups.
448 /// ExprCleanupObjects - This is the stack of objects requiring
449 /// cleanup that are created by the current full expression. The
450 /// element type here is ExprWithCleanups::Object.
451 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
453 /// \brief Store a list of either DeclRefExprs or MemberExprs
454 /// that contain a reference to a variable (constant) that may or may not
455 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
456 /// and discarded value conversions have been applied to all subexpressions
457 /// of the enclosing full expression. This is cleared at the end of each
459 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
461 /// \brief Stack containing information about each of the nested
462 /// function, block, and method scopes that are currently active.
464 /// This array is never empty. Clients should ignore the first
465 /// element, which is used to cache a single FunctionScopeInfo
466 /// that's used to parse every top-level function.
467 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
469 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
470 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
473 /// ExtVectorDecls - This is a list all the extended vector types. This allows
474 /// us to associate a raw vector type with one of the ext_vector type names.
475 /// This is only necessary for issuing pretty diagnostics.
476 ExtVectorDeclsType ExtVectorDecls;
478 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
479 std::unique_ptr<CXXFieldCollector> FieldCollector;
481 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
483 /// \brief Set containing all declared private fields that are not used.
484 NamedDeclSetType UnusedPrivateFields;
486 /// \brief Set containing all typedefs that are likely unused.
487 llvm::SmallSetVector<const TypedefNameDecl *, 4>
488 UnusedLocalTypedefNameCandidates;
490 /// \brief Delete-expressions to be analyzed at the end of translation unit
492 /// This list contains class members, and locations of delete-expressions
493 /// that could not be proven as to whether they mismatch with new-expression
494 /// used in initializer of the field.
495 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
496 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
497 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
499 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
501 /// PureVirtualClassDiagSet - a set of class declarations which we have
502 /// emitted a list of pure virtual functions. Used to prevent emitting the
503 /// same list more than once.
504 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
506 /// ParsingInitForAutoVars - a set of declarations with auto types for which
507 /// we are currently parsing the initializer.
508 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
510 /// \brief Look for a locally scoped extern "C" declaration by the given name.
511 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
513 typedef LazyVector<VarDecl *, ExternalSemaSource,
514 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
515 TentativeDefinitionsType;
517 /// \brief All the tentative definitions encountered in the TU.
518 TentativeDefinitionsType TentativeDefinitions;
520 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
521 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
522 UnusedFileScopedDeclsType;
524 /// \brief The set of file scoped decls seen so far that have not been used
525 /// and must warn if not used. Only contains the first declaration.
526 UnusedFileScopedDeclsType UnusedFileScopedDecls;
528 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
529 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
530 DelegatingCtorDeclsType;
532 /// \brief All the delegating constructors seen so far in the file, used for
533 /// cycle detection at the end of the TU.
534 DelegatingCtorDeclsType DelegatingCtorDecls;
536 /// \brief All the overriding functions seen during a class definition
537 /// that had their exception spec checks delayed, plus the overridden
539 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
540 DelayedExceptionSpecChecks;
542 /// \brief All the members seen during a class definition which were both
543 /// explicitly defaulted and had explicitly-specified exception
544 /// specifications, along with the function type containing their
545 /// user-specified exception specification. Those exception specifications
546 /// were overridden with the default specifications, but we still need to
547 /// check whether they are compatible with the default specification, and
548 /// we can't do that until the nesting set of class definitions is complete.
549 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
550 DelayedDefaultedMemberExceptionSpecs;
552 typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
553 LateParsedTemplateMapT;
554 LateParsedTemplateMapT LateParsedTemplateMap;
556 /// \brief Callback to the parser to parse templated functions when needed.
557 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
558 typedef void LateTemplateParserCleanupCB(void *P);
559 LateTemplateParserCB *LateTemplateParser;
560 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
563 void SetLateTemplateParser(LateTemplateParserCB *LTP,
564 LateTemplateParserCleanupCB *LTPCleanup,
566 LateTemplateParser = LTP;
567 LateTemplateParserCleanup = LTPCleanup;
571 class DelayedDiagnostics;
573 class DelayedDiagnosticsState {
574 sema::DelayedDiagnosticPool *SavedPool;
575 friend class Sema::DelayedDiagnostics;
577 typedef DelayedDiagnosticsState ParsingDeclState;
578 typedef DelayedDiagnosticsState ProcessingContextState;
580 /// A class which encapsulates the logic for delaying diagnostics
581 /// during parsing and other processing.
582 class DelayedDiagnostics {
583 /// \brief The current pool of diagnostics into which delayed
584 /// diagnostics should go.
585 sema::DelayedDiagnosticPool *CurPool;
588 DelayedDiagnostics() : CurPool(nullptr) {}
590 /// Adds a delayed diagnostic.
591 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
593 /// Determines whether diagnostics should be delayed.
594 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
596 /// Returns the current delayed-diagnostics pool.
597 sema::DelayedDiagnosticPool *getCurrentPool() const {
601 /// Enter a new scope. Access and deprecation diagnostics will be
602 /// collected in this pool.
603 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
604 DelayedDiagnosticsState state;
605 state.SavedPool = CurPool;
610 /// Leave a delayed-diagnostic state that was previously pushed.
611 /// Do not emit any of the diagnostics. This is performed as part
612 /// of the bookkeeping of popping a pool "properly".
613 void popWithoutEmitting(DelayedDiagnosticsState state) {
614 CurPool = state.SavedPool;
617 /// Enter a new scope where access and deprecation diagnostics are
619 DelayedDiagnosticsState pushUndelayed() {
620 DelayedDiagnosticsState state;
621 state.SavedPool = CurPool;
626 /// Undo a previous pushUndelayed().
627 void popUndelayed(DelayedDiagnosticsState state) {
628 assert(CurPool == nullptr);
629 CurPool = state.SavedPool;
631 } DelayedDiagnostics;
633 /// A RAII object to temporarily push a declaration context.
637 DeclContext *SavedContext;
638 ProcessingContextState SavedContextState;
639 QualType SavedCXXThisTypeOverride;
642 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
643 : S(S), SavedContext(S.CurContext),
644 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
645 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
647 assert(ContextToPush && "pushing null context");
648 S.CurContext = ContextToPush;
650 S.CXXThisTypeOverride = QualType();
654 if (!SavedContext) return;
655 S.CurContext = SavedContext;
656 S.DelayedDiagnostics.popUndelayed(SavedContextState);
657 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
658 SavedContext = nullptr;
666 /// \brief RAII object to handle the state changes required to synthesize
668 class SynthesizedFunctionScope {
670 Sema::ContextRAII SavedContext;
673 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
674 : S(S), SavedContext(S, DC)
676 S.PushFunctionScope();
677 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
680 ~SynthesizedFunctionScope() {
681 S.PopExpressionEvaluationContext();
682 S.PopFunctionScopeInfo();
686 /// WeakUndeclaredIdentifiers - Identifiers contained in
687 /// \#pragma weak before declared. rare. may alias another
688 /// identifier, declared or undeclared
689 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
691 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
692 /// \#pragma redefine_extname before declared. Used in Solaris system headers
693 /// to define functions that occur in multiple standards to call the version
694 /// in the currently selected standard.
695 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
698 /// \brief Load weak undeclared identifiers from the external source.
699 void LoadExternalWeakUndeclaredIdentifiers();
701 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
702 /// \#pragma weak during processing of other Decls.
703 /// I couldn't figure out a clean way to generate these in-line, so
704 /// we store them here and handle separately -- which is a hack.
705 /// It would be best to refactor this.
706 SmallVector<Decl*,2> WeakTopLevelDecl;
708 IdentifierResolver IdResolver;
710 /// Translation Unit Scope - useful to Objective-C actions that need
711 /// to lookup file scope declarations in the "ordinary" C decl namespace.
712 /// For example, user-defined classes, built-in "id" type, etc.
715 /// \brief The C++ "std" namespace, where the standard library resides.
716 LazyDeclPtr StdNamespace;
718 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
719 /// standard library.
720 LazyDeclPtr StdBadAlloc;
722 /// \brief The C++ "std::initializer_list" template, which is defined in
723 /// \<initializer_list>.
724 ClassTemplateDecl *StdInitializerList;
726 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
727 RecordDecl *CXXTypeInfoDecl;
729 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
730 RecordDecl *MSVCGuidDecl;
732 /// \brief Caches identifiers/selectors for NSFoundation APIs.
733 std::unique_ptr<NSAPI> NSAPIObj;
735 /// \brief The declaration of the Objective-C NSNumber class.
736 ObjCInterfaceDecl *NSNumberDecl;
738 /// \brief The declaration of the Objective-C NSValue class.
739 ObjCInterfaceDecl *NSValueDecl;
741 /// \brief Pointer to NSNumber type (NSNumber *).
742 QualType NSNumberPointer;
744 /// \brief Pointer to NSValue type (NSValue *).
745 QualType NSValuePointer;
747 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
748 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
750 /// \brief The declaration of the Objective-C NSString class.
751 ObjCInterfaceDecl *NSStringDecl;
753 /// \brief Pointer to NSString type (NSString *).
754 QualType NSStringPointer;
756 /// \brief The declaration of the stringWithUTF8String: method.
757 ObjCMethodDecl *StringWithUTF8StringMethod;
759 /// \brief The declaration of the valueWithBytes:objCType: method.
760 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
762 /// \brief The declaration of the Objective-C NSArray class.
763 ObjCInterfaceDecl *NSArrayDecl;
765 /// \brief The declaration of the arrayWithObjects:count: method.
766 ObjCMethodDecl *ArrayWithObjectsMethod;
768 /// \brief The declaration of the Objective-C NSDictionary class.
769 ObjCInterfaceDecl *NSDictionaryDecl;
771 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
772 ObjCMethodDecl *DictionaryWithObjectsMethod;
774 /// \brief id<NSCopying> type.
775 QualType QIDNSCopying;
777 /// \brief will hold 'respondsToSelector:'
778 Selector RespondsToSelectorSel;
780 /// \brief counter for internal MS Asm label names.
781 unsigned MSAsmLabelNameCounter;
783 /// A flag to remember whether the implicit forms of operator new and delete
784 /// have been declared.
785 bool GlobalNewDeleteDeclared;
787 /// A flag to indicate that we're in a context that permits abstract
788 /// references to fields. This is really a
789 bool AllowAbstractFieldReference;
791 /// \brief Describes how the expressions currently being parsed are
792 /// evaluated at run-time, if at all.
793 enum ExpressionEvaluationContext {
794 /// \brief The current expression and its subexpressions occur within an
795 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
796 /// \c sizeof, where the type of the expression may be significant but
797 /// no code will be generated to evaluate the value of the expression at
801 /// \brief The current expression occurs within a discarded statement.
802 /// This behaves largely similarly to an unevaluated operand in preventing
803 /// definitions from being required, but not in other ways.
806 /// \brief The current expression occurs within an unevaluated
807 /// operand that unconditionally permits abstract references to
808 /// fields, such as a SIZE operator in MS-style inline assembly.
811 /// \brief The current context is "potentially evaluated" in C++11 terms,
812 /// but the expression is evaluated at compile-time (like the values of
813 /// cases in a switch statement).
816 /// \brief The current expression is potentially evaluated at run time,
817 /// which means that code may be generated to evaluate the value of the
818 /// expression at run time.
819 PotentiallyEvaluated,
821 /// \brief The current expression is potentially evaluated, but any
822 /// declarations referenced inside that expression are only used if
823 /// in fact the current expression is used.
825 /// This value is used when parsing default function arguments, for which
826 /// we would like to provide diagnostics (e.g., passing non-POD arguments
827 /// through varargs) but do not want to mark declarations as "referenced"
828 /// until the default argument is used.
829 PotentiallyEvaluatedIfUsed
832 /// \brief Data structure used to record current or nested
833 /// expression evaluation contexts.
834 struct ExpressionEvaluationContextRecord {
835 /// \brief The expression evaluation context.
836 ExpressionEvaluationContext Context;
838 /// \brief Whether the enclosing context needed a cleanup.
839 CleanupInfo ParentCleanup;
841 /// \brief Whether we are in a decltype expression.
844 /// \brief The number of active cleanup objects when we entered
845 /// this expression evaluation context.
846 unsigned NumCleanupObjects;
848 /// \brief The number of typos encountered during this expression evaluation
849 /// context (i.e. the number of TypoExprs created).
852 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
854 /// \brief The lambdas that are present within this context, if it
855 /// is indeed an unevaluated context.
856 SmallVector<LambdaExpr *, 2> Lambdas;
858 /// \brief The declaration that provides context for lambda expressions
859 /// and block literals if the normal declaration context does not
860 /// suffice, e.g., in a default function argument.
861 Decl *ManglingContextDecl;
863 /// \brief The context information used to mangle lambda expressions
864 /// and block literals within this context.
866 /// This mangling information is allocated lazily, since most contexts
867 /// do not have lambda expressions or block literals.
868 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
870 /// \brief If we are processing a decltype type, a set of call expressions
871 /// for which we have deferred checking the completeness of the return type.
872 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
874 /// \brief If we are processing a decltype type, a set of temporary binding
875 /// expressions for which we have deferred checking the destructor.
876 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
878 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
879 unsigned NumCleanupObjects,
880 CleanupInfo ParentCleanup,
881 Decl *ManglingContextDecl,
883 : Context(Context), ParentCleanup(ParentCleanup),
884 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
886 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
888 /// \brief Retrieve the mangling numbering context, used to consistently
889 /// number constructs like lambdas for mangling.
890 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
892 bool isUnevaluated() const {
893 return Context == Unevaluated || Context == UnevaluatedAbstract;
897 /// A stack of expression evaluation contexts.
898 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
900 /// \brief Compute the mangling number context for a lambda expression or
903 /// \param DC - The DeclContext containing the lambda expression or
905 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
906 /// associated with the context, if relevant.
907 MangleNumberingContext *getCurrentMangleNumberContext(
908 const DeclContext *DC,
909 Decl *&ManglingContextDecl);
912 /// SpecialMemberOverloadResult - The overloading result for a special member
915 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
916 /// integer are used to determine whether overload resolution succeeded.
917 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
926 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
929 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
930 : FastFoldingSetNode(ID)
933 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
934 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
936 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
937 void setKind(Kind K) { Pair.setInt(K); }
940 /// \brief A cache of special member function overload resolution results
942 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
944 /// \brief A cache of the flags available in enumerations with the flag_bits
946 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
948 /// \brief The kind of translation unit we are processing.
950 /// When we're processing a complete translation unit, Sema will perform
951 /// end-of-translation-unit semantic tasks (such as creating
952 /// initializers for tentative definitions in C) once parsing has
953 /// completed. Modules and precompiled headers perform different kinds of
955 TranslationUnitKind TUKind;
957 llvm::BumpPtrAllocator BumpAlloc;
959 /// \brief The number of SFINAE diagnostics that have been trapped.
960 unsigned NumSFINAEErrors;
962 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
963 UnparsedDefaultArgInstantiationsMap;
965 /// \brief A mapping from parameters with unparsed default arguments to the
966 /// set of instantiations of each parameter.
968 /// This mapping is a temporary data structure used when parsing
969 /// nested class templates or nested classes of class templates,
970 /// where we might end up instantiating an inner class before the
971 /// default arguments of its methods have been parsed.
972 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
974 // Contains the locations of the beginning of unparsed default
975 // argument locations.
976 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
978 /// UndefinedInternals - all the used, undefined objects which require a
979 /// definition in this translation unit.
980 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
982 /// Obtain a sorted list of functions that are undefined but ODR-used.
983 void getUndefinedButUsed(
984 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
986 /// Retrieves list of suspicious delete-expressions that will be checked at
987 /// the end of translation unit.
988 const llvm::MapVector<FieldDecl *, DeleteLocs> &
989 getMismatchingDeleteExpressions() const;
991 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
992 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
994 /// Method Pool - allows efficient lookup when typechecking messages to "id".
995 /// We need to maintain a list, since selectors can have differing signatures
996 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
997 /// of selectors are "overloaded").
998 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
999 /// methods inside categories with a particular selector.
1000 GlobalMethodPool MethodPool;
1002 /// Method selectors used in a \@selector expression. Used for implementation
1004 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1006 /// Kinds of C++ special members.
1007 enum CXXSpecialMember {
1008 CXXDefaultConstructor,
1017 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1019 /// The C++ special members which we are currently in the process of
1020 /// declaring. If this process recursively triggers the declaration of the
1021 /// same special member, we should act as if it is not yet declared.
1022 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1024 void ReadMethodPool(Selector Sel);
1025 void updateOutOfDateSelector(Selector Sel);
1027 /// Private Helper predicate to check for 'self'.
1028 bool isSelfExpr(Expr *RExpr);
1029 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1031 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1032 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1033 /// should not be used elsewhere.
1034 void EmitCurrentDiagnostic(unsigned DiagID);
1036 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1038 class FPContractStateRAII {
1040 FPContractStateRAII(Sema& S)
1041 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1042 ~FPContractStateRAII() {
1043 S.FPFeatures.fp_contract = OldFPContractState;
1047 bool OldFPContractState : 1;
1050 void addImplicitTypedef(StringRef Name, QualType T);
1053 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1054 TranslationUnitKind TUKind = TU_Complete,
1055 CodeCompleteConsumer *CompletionConsumer = nullptr);
1058 /// \brief Perform initialization that occurs after the parser has been
1059 /// initialized but before it parses anything.
1062 const LangOptions &getLangOpts() const { return LangOpts; }
1063 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1064 FPOptions &getFPOptions() { return FPFeatures; }
1066 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1067 SourceManager &getSourceManager() const { return SourceMgr; }
1068 Preprocessor &getPreprocessor() const { return PP; }
1069 ASTContext &getASTContext() const { return Context; }
1070 ASTConsumer &getASTConsumer() const { return Consumer; }
1071 ASTMutationListener *getASTMutationListener() const;
1072 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1074 ///\brief Registers an external source. If an external source already exists,
1075 /// creates a multiplex external source and appends to it.
1077 ///\param[in] E - A non-null external sema source.
1079 void addExternalSource(ExternalSemaSource *E);
1081 void PrintStats() const;
1083 /// \brief Helper class that creates diagnostics with optional
1084 /// template instantiation stacks.
1086 /// This class provides a wrapper around the basic DiagnosticBuilder
1087 /// class that emits diagnostics. SemaDiagnosticBuilder is
1088 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1089 /// does) and, if the diagnostic comes from inside a template
1090 /// instantiation, printing the template instantiation stack as
1092 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1097 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1098 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1100 // This is a cunning lie. DiagnosticBuilder actually performs move
1101 // construction in its copy constructor (but due to varied uses, it's not
1102 // possible to conveniently express this as actual move construction). So
1103 // the default copy ctor here is fine, because the base class disables the
1104 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1105 // in that case anwyay.
1106 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1108 ~SemaDiagnosticBuilder() {
1109 // If we aren't active, there is nothing to do.
1110 if (!isActive()) return;
1112 // Otherwise, we need to emit the diagnostic. First flush the underlying
1113 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1114 // won't emit the diagnostic in its own destructor.
1116 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1117 // do its own needless checks to see if the diagnostic needs to be
1118 // emitted. However, because we take care to ensure that the builder
1119 // objects never escape, a sufficiently smart compiler will be able to
1120 // eliminate that code.
1124 // Dispatch to Sema to emit the diagnostic.
1125 SemaRef.EmitCurrentDiagnostic(DiagID);
1128 /// Teach operator<< to produce an object of the correct type.
1129 template<typename T>
1130 friend const SemaDiagnosticBuilder &operator<<(
1131 const SemaDiagnosticBuilder &Diag, const T &Value) {
1132 const DiagnosticBuilder &BaseDiag = Diag;
1138 /// \brief Emit a diagnostic.
1139 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1140 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1141 return SemaDiagnosticBuilder(DB, *this, DiagID);
1144 /// \brief Emit a partial diagnostic.
1145 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1147 /// \brief Build a partial diagnostic.
1148 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1150 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1152 /// \brief Get a string to suggest for zero-initialization of a type.
1154 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1155 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1157 /// \brief Calls \c Lexer::getLocForEndOfToken()
1158 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1160 /// \brief Retrieve the module loader associated with the preprocessor.
1161 ModuleLoader &getModuleLoader() const;
1163 void emitAndClearUnusedLocalTypedefWarnings();
1165 void ActOnEndOfTranslationUnit();
1167 void CheckDelegatingCtorCycles();
1169 Scope *getScopeForContext(DeclContext *Ctx);
1171 void PushFunctionScope();
1172 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1173 sema::LambdaScopeInfo *PushLambdaScope();
1175 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1176 /// is during Parsing. Currently it is used to pass on the depth
1177 /// when parsing generic lambda 'auto' parameters.
1178 void RecordParsingTemplateParameterDepth(unsigned Depth);
1180 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1182 CapturedRegionKind K);
1184 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1185 const Decl *D = nullptr,
1186 const BlockExpr *blkExpr = nullptr);
1188 sema::FunctionScopeInfo *getCurFunction() const {
1189 return FunctionScopes.back();
1192 sema::FunctionScopeInfo *getEnclosingFunction() const {
1193 if (FunctionScopes.empty())
1196 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1197 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1199 return FunctionScopes[e];
1204 template <typename ExprT>
1205 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1206 if (!isUnevaluatedContext())
1207 getCurFunction()->recordUseOfWeak(E, IsRead);
1210 void PushCompoundScope();
1211 void PopCompoundScope();
1213 sema::CompoundScopeInfo &getCurCompoundScope() const;
1215 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1217 /// \brief Retrieve the current block, if any.
1218 sema::BlockScopeInfo *getCurBlock();
1220 /// \brief Retrieve the current lambda scope info, if any.
1221 sema::LambdaScopeInfo *getCurLambda();
1223 /// \brief Retrieve the current generic lambda info, if any.
1224 sema::LambdaScopeInfo *getCurGenericLambda();
1226 /// \brief Retrieve the current captured region, if any.
1227 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1229 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1230 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1232 void ActOnComment(SourceRange Comment);
1234 //===--------------------------------------------------------------------===//
1235 // Type Analysis / Processing: SemaType.cpp.
1238 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1239 const DeclSpec *DS = nullptr);
1240 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1241 const DeclSpec *DS = nullptr);
1242 QualType BuildPointerType(QualType T,
1243 SourceLocation Loc, DeclarationName Entity);
1244 QualType BuildReferenceType(QualType T, bool LValueRef,
1245 SourceLocation Loc, DeclarationName Entity);
1246 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1247 Expr *ArraySize, unsigned Quals,
1248 SourceRange Brackets, DeclarationName Entity);
1249 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1250 SourceLocation AttrLoc);
1252 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1254 /// \brief Build a function type.
1256 /// This routine checks the function type according to C++ rules and
1257 /// under the assumption that the result type and parameter types have
1258 /// just been instantiated from a template. It therefore duplicates
1259 /// some of the behavior of GetTypeForDeclarator, but in a much
1260 /// simpler form that is only suitable for this narrow use case.
1262 /// \param T The return type of the function.
1264 /// \param ParamTypes The parameter types of the function. This array
1265 /// will be modified to account for adjustments to the types of the
1266 /// function parameters.
1268 /// \param Loc The location of the entity whose type involves this
1269 /// function type or, if there is no such entity, the location of the
1270 /// type that will have function type.
1272 /// \param Entity The name of the entity that involves the function
1275 /// \param EPI Extra information about the function type. Usually this will
1276 /// be taken from an existing function with the same prototype.
1278 /// \returns A suitable function type, if there are no errors. The
1279 /// unqualified type will always be a FunctionProtoType.
1280 /// Otherwise, returns a NULL type.
1281 QualType BuildFunctionType(QualType T,
1282 MutableArrayRef<QualType> ParamTypes,
1283 SourceLocation Loc, DeclarationName Entity,
1284 const FunctionProtoType::ExtProtoInfo &EPI);
1286 QualType BuildMemberPointerType(QualType T, QualType Class,
1288 DeclarationName Entity);
1289 QualType BuildBlockPointerType(QualType T,
1290 SourceLocation Loc, DeclarationName Entity);
1291 QualType BuildParenType(QualType T);
1292 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1293 QualType BuildPipeType(QualType T,
1294 SourceLocation Loc);
1296 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1297 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1298 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1299 TypeSourceInfo *ReturnTypeInfo);
1301 /// \brief Package the given type and TSI into a ParsedType.
1302 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1303 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1304 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1305 static QualType GetTypeFromParser(ParsedType Ty,
1306 TypeSourceInfo **TInfo = nullptr);
1307 CanThrowResult canThrow(const Expr *E);
1308 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1309 const FunctionProtoType *FPT);
1310 void UpdateExceptionSpec(FunctionDecl *FD,
1311 const FunctionProtoType::ExceptionSpecInfo &ESI);
1312 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1313 bool CheckDistantExceptionSpec(QualType T);
1314 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1315 bool CheckEquivalentExceptionSpec(
1316 const FunctionProtoType *Old, SourceLocation OldLoc,
1317 const FunctionProtoType *New, SourceLocation NewLoc);
1318 bool CheckEquivalentExceptionSpec(
1319 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1320 const FunctionProtoType *Old, SourceLocation OldLoc,
1321 const FunctionProtoType *New, SourceLocation NewLoc,
1322 bool *MissingExceptionSpecification = nullptr,
1323 bool *MissingEmptyExceptionSpecification = nullptr,
1324 bool AllowNoexceptAllMatchWithNoSpec = false,
1325 bool IsOperatorNew = false);
1326 bool CheckExceptionSpecSubset(
1327 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1328 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1329 const FunctionProtoType *Subset, SourceLocation SubLoc);
1330 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1331 const FunctionProtoType *Target, SourceLocation TargetLoc,
1332 const FunctionProtoType *Source, SourceLocation SourceLoc);
1334 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1336 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1337 /// in an Objective-C message declaration. Return the appropriate type.
1338 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1340 /// \brief Abstract class used to diagnose incomplete types.
1341 struct TypeDiagnoser {
1344 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1345 virtual ~TypeDiagnoser() {}
1348 static int getPrintable(int I) { return I; }
1349 static unsigned getPrintable(unsigned I) { return I; }
1350 static bool getPrintable(bool B) { return B; }
1351 static const char * getPrintable(const char *S) { return S; }
1352 static StringRef getPrintable(StringRef S) { return S; }
1353 static const std::string &getPrintable(const std::string &S) { return S; }
1354 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1357 static DeclarationName getPrintable(DeclarationName N) { return N; }
1358 static QualType getPrintable(QualType T) { return T; }
1359 static SourceRange getPrintable(SourceRange R) { return R; }
1360 static SourceRange getPrintable(SourceLocation L) { return L; }
1361 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1362 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1364 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1366 std::tuple<const Ts &...> Args;
1368 template <std::size_t... Is>
1369 void emit(const SemaDiagnosticBuilder &DB,
1370 llvm::index_sequence<Is...>) const {
1371 // Apply all tuple elements to the builder in order.
1372 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1377 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1378 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1379 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1382 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1383 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1384 emit(DB, llvm::index_sequence_for<Ts...>());
1390 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1391 TypeDiagnoser *Diagnoser);
1393 VisibleModuleSet VisibleModules;
1394 llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
1396 Module *CachedFakeTopLevelModule;
1399 /// \brief Get the module owning an entity.
1400 Module *getOwningModule(Decl *Entity);
1402 /// \brief Make a merged definition of an existing hidden definition \p ND
1403 /// visible at the specified location.
1404 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1406 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1408 /// Determine whether a declaration is visible to name lookup.
1409 bool isVisible(const NamedDecl *D) {
1410 return !D->isHidden() || isVisibleSlow(D);
1413 /// Determine whether any declaration of an entity is visible.
1415 hasVisibleDeclaration(const NamedDecl *D,
1416 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1417 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1419 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1420 llvm::SmallVectorImpl<Module *> *Modules);
1422 bool hasVisibleMergedDefinition(NamedDecl *Def);
1424 /// Determine if \p D has a visible definition. If not, suggest a declaration
1425 /// that should be made visible to expose the definition.
1426 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1427 bool OnlyNeedComplete = false);
1428 bool hasVisibleDefinition(const NamedDecl *D) {
1430 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1433 /// Determine if the template parameter \p D has a visible default argument.
1435 hasVisibleDefaultArgument(const NamedDecl *D,
1436 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1438 /// Determine if there is a visible declaration of \p D that is a member
1439 /// specialization declaration (as opposed to an instantiated declaration).
1440 bool hasVisibleMemberSpecialization(
1441 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1443 /// Determine if \p A and \p B are equivalent internal linkage declarations
1444 /// from different modules, and thus an ambiguity error can be downgraded to
1445 /// an extension warning.
1446 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1447 const NamedDecl *B);
1448 void diagnoseEquivalentInternalLinkageDeclarations(
1449 SourceLocation Loc, const NamedDecl *D,
1450 ArrayRef<const NamedDecl *> Equiv);
1452 bool isCompleteType(SourceLocation Loc, QualType T) {
1453 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1455 bool RequireCompleteType(SourceLocation Loc, QualType T,
1456 TypeDiagnoser &Diagnoser);
1457 bool RequireCompleteType(SourceLocation Loc, QualType T,
1460 template <typename... Ts>
1461 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1462 const Ts &...Args) {
1463 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1464 return RequireCompleteType(Loc, T, Diagnoser);
1467 void completeExprArrayBound(Expr *E);
1468 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1469 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1471 template <typename... Ts>
1472 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1473 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1474 return RequireCompleteExprType(E, Diagnoser);
1477 bool RequireLiteralType(SourceLocation Loc, QualType T,
1478 TypeDiagnoser &Diagnoser);
1479 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1481 template <typename... Ts>
1482 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1483 const Ts &...Args) {
1484 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1485 return RequireLiteralType(Loc, T, Diagnoser);
1488 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1489 const CXXScopeSpec &SS, QualType T);
1491 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1492 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1493 /// context, such as when building a type for decltype(auto).
1494 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1495 bool AsUnevaluated = true);
1496 QualType BuildUnaryTransformType(QualType BaseType,
1497 UnaryTransformType::UTTKind UKind,
1498 SourceLocation Loc);
1500 //===--------------------------------------------------------------------===//
1501 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1504 struct SkipBodyInfo {
1505 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1507 NamedDecl *Previous;
1510 /// List of decls defined in a function prototype. This contains EnumConstants
1511 /// that incorrectly end up in translation unit scope because there is no
1512 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1513 /// them into the FunctionDecl.
1514 std::vector<NamedDecl*> DeclsInPrototypeScope;
1516 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1518 void DiagnoseUseOfUnimplementedSelectors();
1520 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1522 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1523 Scope *S, CXXScopeSpec *SS = nullptr,
1524 bool isClassName = false, bool HasTrailingDot = false,
1525 ParsedType ObjectType = nullptr,
1526 bool IsCtorOrDtorName = false,
1527 bool WantNontrivialTypeSourceInfo = false,
1528 IdentifierInfo **CorrectedII = nullptr);
1529 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1530 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1531 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1532 SourceLocation IILoc,
1535 ParsedType &SuggestedType,
1536 bool AllowClassTemplates = false);
1538 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1539 /// type name has failed in a dependent context. In these situations, we
1540 /// automatically form a DependentTypeName that will retry lookup in a related
1541 /// scope during instantiation.
1542 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1543 SourceLocation NameLoc,
1544 bool IsTemplateTypeArg);
1546 /// \brief Describes the result of the name lookup and resolution performed
1547 /// by \c ClassifyName().
1548 enum NameClassificationKind {
1554 NC_NestedNameSpecifier,
1560 class NameClassification {
1561 NameClassificationKind Kind;
1563 TemplateName Template;
1565 const IdentifierInfo *Keyword;
1567 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1570 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1572 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1574 NameClassification(const IdentifierInfo *Keyword)
1575 : Kind(NC_Keyword), Keyword(Keyword) { }
1577 static NameClassification Error() {
1578 return NameClassification(NC_Error);
1581 static NameClassification Unknown() {
1582 return NameClassification(NC_Unknown);
1585 static NameClassification NestedNameSpecifier() {
1586 return NameClassification(NC_NestedNameSpecifier);
1589 static NameClassification TypeTemplate(TemplateName Name) {
1590 NameClassification Result(NC_TypeTemplate);
1591 Result.Template = Name;
1595 static NameClassification VarTemplate(TemplateName Name) {
1596 NameClassification Result(NC_VarTemplate);
1597 Result.Template = Name;
1601 static NameClassification FunctionTemplate(TemplateName Name) {
1602 NameClassification Result(NC_FunctionTemplate);
1603 Result.Template = Name;
1607 NameClassificationKind getKind() const { return Kind; }
1609 ParsedType getType() const {
1610 assert(Kind == NC_Type);
1614 ExprResult getExpression() const {
1615 assert(Kind == NC_Expression);
1619 TemplateName getTemplateName() const {
1620 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1621 Kind == NC_VarTemplate);
1625 TemplateNameKind getTemplateNameKind() const {
1627 case NC_TypeTemplate:
1628 return TNK_Type_template;
1629 case NC_FunctionTemplate:
1630 return TNK_Function_template;
1631 case NC_VarTemplate:
1632 return TNK_Var_template;
1634 llvm_unreachable("unsupported name classification.");
1639 /// \brief Perform name lookup on the given name, classifying it based on
1640 /// the results of name lookup and the following token.
1642 /// This routine is used by the parser to resolve identifiers and help direct
1643 /// parsing. When the identifier cannot be found, this routine will attempt
1644 /// to correct the typo and classify based on the resulting name.
1646 /// \param S The scope in which we're performing name lookup.
1648 /// \param SS The nested-name-specifier that precedes the name.
1650 /// \param Name The identifier. If typo correction finds an alternative name,
1651 /// this pointer parameter will be updated accordingly.
1653 /// \param NameLoc The location of the identifier.
1655 /// \param NextToken The token following the identifier. Used to help
1656 /// disambiguate the name.
1658 /// \param IsAddressOfOperand True if this name is the operand of a unary
1659 /// address of ('&') expression, assuming it is classified as an
1662 /// \param CCC The correction callback, if typo correction is desired.
1664 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1665 SourceLocation NameLoc, const Token &NextToken,
1666 bool IsAddressOfOperand,
1667 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1669 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1671 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1672 MultiTemplateParamsArg TemplateParameterLists);
1673 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1674 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1675 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1676 DeclarationName Name,
1677 SourceLocation Loc);
1679 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1680 SourceLocation FallbackLoc,
1681 SourceLocation ConstQualLoc = SourceLocation(),
1682 SourceLocation VolatileQualLoc = SourceLocation(),
1683 SourceLocation RestrictQualLoc = SourceLocation(),
1684 SourceLocation AtomicQualLoc = SourceLocation(),
1685 SourceLocation UnalignedQualLoc = SourceLocation());
1687 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1688 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1689 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1690 void CheckShadow(Scope *S, VarDecl *D);
1692 /// Warn if 'E', which is an expression that is about to be modified, refers
1693 /// to a shadowing declaration.
1694 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1697 /// Map of current shadowing declarations to shadowed declarations. Warn if
1698 /// it looks like the user is trying to modify the shadowing declaration.
1699 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1702 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1703 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1704 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1705 TypedefNameDecl *NewTD);
1706 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1707 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1708 TypeSourceInfo *TInfo,
1709 LookupResult &Previous);
1710 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1711 LookupResult &Previous, bool &Redeclaration);
1712 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1713 TypeSourceInfo *TInfo,
1714 LookupResult &Previous,
1715 MultiTemplateParamsArg TemplateParamLists,
1717 // Returns true if the variable declaration is a redeclaration
1718 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1719 void CheckVariableDeclarationType(VarDecl *NewVD);
1720 void CheckCompleteVariableDeclaration(VarDecl *var);
1721 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1723 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1724 TypeSourceInfo *TInfo,
1725 LookupResult &Previous,
1726 MultiTemplateParamsArg TemplateParamLists,
1728 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1730 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1731 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1733 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1734 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1735 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1736 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1737 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1738 // Returns true if the function declaration is a redeclaration
1739 bool CheckFunctionDeclaration(Scope *S,
1740 FunctionDecl *NewFD, LookupResult &Previous,
1741 bool IsExplicitSpecialization);
1742 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1743 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1744 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1745 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1748 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1749 SourceLocation NameLoc, IdentifierInfo *Name,
1750 QualType T, TypeSourceInfo *TSInfo,
1752 void ActOnParamDefaultArgument(Decl *param,
1753 SourceLocation EqualLoc,
1755 void ActOnParamUnparsedDefaultArgument(Decl *param,
1756 SourceLocation EqualLoc,
1757 SourceLocation ArgLoc);
1758 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1759 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1760 SourceLocation EqualLoc);
1762 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1763 bool TypeMayContainAuto);
1764 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1765 void ActOnInitializerError(Decl *Dcl);
1766 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1767 void ActOnCXXForRangeDecl(Decl *D);
1768 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1769 IdentifierInfo *Ident,
1770 ParsedAttributes &Attrs,
1771 SourceLocation AttrEnd);
1772 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1773 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1774 void FinalizeDeclaration(Decl *D);
1775 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1776 ArrayRef<Decl *> Group);
1777 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1778 bool TypeMayContainAuto = true);
1780 /// Should be called on all declarations that might have attached
1781 /// documentation comments.
1782 void ActOnDocumentableDecl(Decl *D);
1783 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1785 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1786 SourceLocation LocAfterDecls);
1787 void CheckForFunctionRedefinition(
1788 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1789 SkipBodyInfo *SkipBody = nullptr);
1790 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1791 MultiTemplateParamsArg TemplateParamLists,
1792 SkipBodyInfo *SkipBody = nullptr);
1793 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1794 SkipBodyInfo *SkipBody = nullptr);
1795 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1796 bool isObjCMethodDecl(Decl *D) {
1797 return D && isa<ObjCMethodDecl>(D);
1800 /// \brief Determine whether we can delay parsing the body of a function or
1801 /// function template until it is used, assuming we don't care about emitting
1802 /// code for that function.
1804 /// This will be \c false if we may need the body of the function in the
1805 /// middle of parsing an expression (where it's impractical to switch to
1806 /// parsing a different function), for instance, if it's constexpr in C++11
1807 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1808 bool canDelayFunctionBody(const Declarator &D);
1810 /// \brief Determine whether we can skip parsing the body of a function
1811 /// definition, assuming we don't care about analyzing its body or emitting
1812 /// code for that function.
1814 /// This will be \c false only if we may need the body of the function in
1815 /// order to parse the rest of the program (for instance, if it is
1816 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1817 bool canSkipFunctionBody(Decl *D);
1819 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1820 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1821 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1822 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1823 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1825 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1826 /// attribute for which parsing is delayed.
1827 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1829 /// \brief Diagnose any unused parameters in the given sequence of
1830 /// ParmVarDecl pointers.
1831 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1833 /// \brief Diagnose whether the size of parameters or return value of a
1834 /// function or obj-c method definition is pass-by-value and larger than a
1835 /// specified threshold.
1837 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1838 QualType ReturnTy, NamedDecl *D);
1840 void DiagnoseInvalidJumps(Stmt *Body);
1841 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1842 SourceLocation AsmLoc,
1843 SourceLocation RParenLoc);
1845 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1846 Decl *ActOnEmptyDeclaration(Scope *S,
1847 AttributeList *AttrList,
1848 SourceLocation SemiLoc);
1850 /// \brief The parser has processed a module import declaration.
1852 /// \param AtLoc The location of the '@' symbol, if any.
1854 /// \param ImportLoc The location of the 'import' keyword.
1856 /// \param Path The module access path.
1857 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1860 /// \brief The parser has processed a module import translated from a
1861 /// #include or similar preprocessing directive.
1862 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1864 /// \brief The parsed has entered a submodule.
1865 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1866 /// \brief The parser has left a submodule.
1867 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1869 /// \brief Check if module import may be found in the current context,
1870 /// emit error if not.
1871 void diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc);
1873 /// \brief Create an implicit import of the given module at the given
1874 /// source location, for error recovery, if possible.
1876 /// This routine is typically used when an entity found by name lookup
1877 /// is actually hidden within a module that we know about but the user
1878 /// has forgotten to import.
1879 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1882 /// Kinds of missing import. Note, the values of these enumerators correspond
1883 /// to %select values in diagnostics.
1884 enum class MissingImportKind {
1888 ExplicitSpecialization,
1889 PartialSpecialization
1892 /// \brief Diagnose that the specified declaration needs to be visible but
1893 /// isn't, and suggest a module import that would resolve the problem.
1894 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1895 MissingImportKind MIK, bool Recover = true);
1896 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1897 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1898 MissingImportKind MIK, bool Recover);
1900 /// \brief We've found a use of a templated declaration that would trigger an
1901 /// implicit instantiation. Check that any relevant explicit specializations
1902 /// and partial specializations are visible, and diagnose if not.
1903 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1905 /// \brief We've found a use of a template specialization that would select a
1906 /// partial specialization. Check that the partial specialization is visible,
1907 /// and diagnose if not.
1908 void checkPartialSpecializationVisibility(SourceLocation Loc,
1911 /// \brief Retrieve a suitable printing policy.
1912 PrintingPolicy getPrintingPolicy() const {
1913 return getPrintingPolicy(Context, PP);
1916 /// \brief Retrieve a suitable printing policy.
1917 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1918 const Preprocessor &PP);
1921 void ActOnPopScope(SourceLocation Loc, Scope *S);
1922 void ActOnTranslationUnitScope(Scope *S);
1924 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1925 RecordDecl *&AnonRecord);
1926 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1927 MultiTemplateParamsArg TemplateParams,
1928 bool IsExplicitInstantiation,
1929 RecordDecl *&AnonRecord);
1931 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1934 const PrintingPolicy &Policy);
1936 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1937 RecordDecl *Record);
1939 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1940 TagTypeKind NewTag, bool isDefinition,
1941 SourceLocation NewTagLoc,
1942 const IdentifierInfo *Name);
1945 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1946 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1947 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1948 TUK_Friend // Friend declaration: 'friend struct foo;'
1951 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1952 SourceLocation KWLoc, CXXScopeSpec &SS,
1953 IdentifierInfo *Name, SourceLocation NameLoc,
1954 AttributeList *Attr, AccessSpecifier AS,
1955 SourceLocation ModulePrivateLoc,
1956 MultiTemplateParamsArg TemplateParameterLists,
1957 bool &OwnedDecl, bool &IsDependent,
1958 SourceLocation ScopedEnumKWLoc,
1959 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1960 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
1962 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1963 unsigned TagSpec, SourceLocation TagLoc,
1965 IdentifierInfo *Name, SourceLocation NameLoc,
1966 AttributeList *Attr,
1967 MultiTemplateParamsArg TempParamLists);
1969 TypeResult ActOnDependentTag(Scope *S,
1972 const CXXScopeSpec &SS,
1973 IdentifierInfo *Name,
1974 SourceLocation TagLoc,
1975 SourceLocation NameLoc);
1977 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1978 IdentifierInfo *ClassName,
1979 SmallVectorImpl<Decl *> &Decls);
1980 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1981 Declarator &D, Expr *BitfieldWidth);
1983 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1984 Declarator &D, Expr *BitfieldWidth,
1985 InClassInitStyle InitStyle,
1986 AccessSpecifier AS);
1987 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1988 SourceLocation DeclStart,
1989 Declarator &D, Expr *BitfieldWidth,
1990 InClassInitStyle InitStyle,
1992 AttributeList *MSPropertyAttr);
1994 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1995 TypeSourceInfo *TInfo,
1996 RecordDecl *Record, SourceLocation Loc,
1997 bool Mutable, Expr *BitfieldWidth,
1998 InClassInitStyle InitStyle,
1999 SourceLocation TSSL,
2000 AccessSpecifier AS, NamedDecl *PrevDecl,
2001 Declarator *D = nullptr);
2003 bool CheckNontrivialField(FieldDecl *FD);
2004 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2005 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2006 bool Diagnose = false);
2007 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2008 void ActOnLastBitfield(SourceLocation DeclStart,
2009 SmallVectorImpl<Decl *> &AllIvarDecls);
2010 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2011 Declarator &D, Expr *BitfieldWidth,
2012 tok::ObjCKeywordKind visibility);
2014 // This is used for both record definitions and ObjC interface declarations.
2015 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2016 ArrayRef<Decl *> Fields,
2017 SourceLocation LBrac, SourceLocation RBrac,
2018 AttributeList *AttrList);
2020 /// ActOnTagStartDefinition - Invoked when we have entered the
2021 /// scope of a tag's definition (e.g., for an enumeration, class,
2022 /// struct, or union).
2023 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2025 typedef void *SkippedDefinitionContext;
2027 /// \brief Invoked when we enter a tag definition that we're skipping.
2028 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2030 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2032 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2033 /// C++ record definition's base-specifiers clause and are starting its
2034 /// member declarations.
2035 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2036 SourceLocation FinalLoc,
2037 bool IsFinalSpelledSealed,
2038 SourceLocation LBraceLoc);
2040 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2041 /// the definition of a tag (enumeration, class, struct, or union).
2042 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2043 SourceRange BraceRange);
2045 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2047 void ActOnObjCContainerFinishDefinition();
2049 /// \brief Invoked when we must temporarily exit the objective-c container
2050 /// scope for parsing/looking-up C constructs.
2052 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2053 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2054 void ActOnObjCReenterContainerContext(DeclContext *DC);
2056 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2057 /// error parsing the definition of a tag.
2058 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2060 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2061 EnumConstantDecl *LastEnumConst,
2062 SourceLocation IdLoc,
2065 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2066 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2067 QualType EnumUnderlyingTy,
2068 bool EnumUnderlyingIsImplicit,
2069 const EnumDecl *Prev);
2071 /// Determine whether the body of an anonymous enumeration should be skipped.
2072 /// \param II The name of the first enumerator.
2073 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2074 SourceLocation IILoc);
2076 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2077 SourceLocation IdLoc, IdentifierInfo *Id,
2078 AttributeList *Attrs,
2079 SourceLocation EqualLoc, Expr *Val);
2080 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2082 ArrayRef<Decl *> Elements,
2083 Scope *S, AttributeList *Attr);
2085 DeclContext *getContainingDC(DeclContext *DC);
2087 /// Set the current declaration context until it gets popped.
2088 void PushDeclContext(Scope *S, DeclContext *DC);
2089 void PopDeclContext();
2091 /// EnterDeclaratorContext - Used when we must lookup names in the context
2092 /// of a declarator's nested name specifier.
2093 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2094 void ExitDeclaratorContext(Scope *S);
2096 /// Push the parameters of D, which must be a function, into scope.
2097 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2098 void ActOnExitFunctionContext();
2100 DeclContext *getFunctionLevelDeclContext();
2102 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2103 /// to the function decl for the function being parsed. If we're currently
2104 /// in a 'block', this returns the containing context.
2105 FunctionDecl *getCurFunctionDecl();
2107 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2108 /// the method decl for the method being parsed. If we're currently
2109 /// in a 'block', this returns the containing context.
2110 ObjCMethodDecl *getCurMethodDecl();
2112 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2113 /// or C function we're in, otherwise return null. If we're currently
2114 /// in a 'block', this returns the containing context.
2115 NamedDecl *getCurFunctionOrMethodDecl();
2117 /// Add this decl to the scope shadowed decl chains.
2118 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2120 /// \brief Make the given externally-produced declaration visible at the
2121 /// top level scope.
2123 /// \param D The externally-produced declaration to push.
2125 /// \param Name The name of the externally-produced declaration.
2126 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2128 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2129 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2130 /// true if 'D' belongs to the given declaration context.
2132 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2133 /// enclosing namespace set of the context, rather than contained
2134 /// directly within it.
2135 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2136 bool AllowInlineNamespace = false);
2138 /// Finds the scope corresponding to the given decl context, if it
2139 /// happens to be an enclosing scope. Otherwise return NULL.
2140 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2142 /// Subroutines of ActOnDeclarator().
2143 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2144 TypeSourceInfo *TInfo);
2145 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2147 /// \brief Describes the kind of merge to perform for availability
2148 /// attributes (including "deprecated", "unavailable", and "availability").
2149 enum AvailabilityMergeKind {
2150 /// \brief Don't merge availability attributes at all.
2152 /// \brief Merge availability attributes for a redeclaration, which requires
2155 /// \brief Merge availability attributes for an override, which requires
2156 /// an exact match or a weakening of constraints.
2158 /// \brief Merge availability attributes for an implementation of
2159 /// a protocol requirement.
2160 AMK_ProtocolImplementation,
2163 /// Attribute merging methods. Return true if a new attribute was added.
2164 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2165 IdentifierInfo *Platform,
2167 VersionTuple Introduced,
2168 VersionTuple Deprecated,
2169 VersionTuple Obsoleted,
2172 bool IsStrict, StringRef Replacement,
2173 AvailabilityMergeKind AMK,
2174 unsigned AttrSpellingListIndex);
2175 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2176 TypeVisibilityAttr::VisibilityType Vis,
2177 unsigned AttrSpellingListIndex);
2178 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2179 VisibilityAttr::VisibilityType Vis,
2180 unsigned AttrSpellingListIndex);
2181 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2182 unsigned AttrSpellingListIndex);
2183 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2184 unsigned AttrSpellingListIndex);
2186 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2187 unsigned AttrSpellingListIndex,
2188 MSInheritanceAttr::Spelling SemanticSpelling);
2189 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2190 IdentifierInfo *Format, int FormatIdx,
2191 int FirstArg, unsigned AttrSpellingListIndex);
2192 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2193 unsigned AttrSpellingListIndex);
2194 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2195 IdentifierInfo *Ident,
2196 unsigned AttrSpellingListIndex);
2197 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2198 unsigned AttrSpellingListIndex);
2199 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2200 unsigned AttrSpellingListIndex);
2201 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2202 IdentifierInfo *Ident,
2203 unsigned AttrSpellingListIndex);
2204 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2205 unsigned AttrSpellingListIndex);
2207 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2208 AvailabilityMergeKind AMK = AMK_Redeclaration);
2209 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2210 LookupResult &OldDecls);
2211 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2212 bool MergeTypeWithOld);
2213 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2214 Scope *S, bool MergeTypeWithOld);
2215 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2216 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2217 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2218 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2219 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2221 // AssignmentAction - This is used by all the assignment diagnostic functions
2222 // to represent what is actually causing the operation
2223 enum AssignmentAction {
2231 AA_Passing_CFAudited
2234 /// C++ Overloading.
2236 /// This is a legitimate overload: the existing declarations are
2237 /// functions or function templates with different signatures.
2240 /// This is not an overload because the signature exactly matches
2241 /// an existing declaration.
2244 /// This is not an overload because the lookup results contain a
2248 OverloadKind CheckOverload(Scope *S,
2250 const LookupResult &OldDecls,
2251 NamedDecl *&OldDecl,
2252 bool IsForUsingDecl);
2253 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2254 bool ConsiderCudaAttrs = true);
2256 /// \brief Checks availability of the function depending on the current
2257 /// function context.Inside an unavailable function,unavailability is ignored.
2259 /// \returns true if \p FD is unavailable and current context is inside
2260 /// an available function, false otherwise.
2261 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2263 ImplicitConversionSequence
2264 TryImplicitConversion(Expr *From, QualType ToType,
2265 bool SuppressUserConversions,
2267 bool InOverloadResolution,
2269 bool AllowObjCWritebackConversion);
2271 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2272 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2273 bool IsComplexPromotion(QualType FromType, QualType ToType);
2274 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2275 bool InOverloadResolution,
2276 QualType& ConvertedType, bool &IncompatibleObjC);
2277 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2278 QualType& ConvertedType, bool &IncompatibleObjC);
2279 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2280 QualType &ConvertedType);
2281 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2282 QualType& ConvertedType);
2283 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2284 const FunctionProtoType *NewType,
2285 unsigned *ArgPos = nullptr);
2286 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2287 QualType FromType, QualType ToType);
2289 void maybeExtendBlockObject(ExprResult &E);
2290 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2291 bool CheckPointerConversion(Expr *From, QualType ToType,
2293 CXXCastPath& BasePath,
2294 bool IgnoreBaseAccess,
2295 bool Diagnose = true);
2296 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2297 bool InOverloadResolution,
2298 QualType &ConvertedType);
2299 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2301 CXXCastPath &BasePath,
2302 bool IgnoreBaseAccess);
2303 bool IsQualificationConversion(QualType FromType, QualType ToType,
2304 bool CStyle, bool &ObjCLifetimeConversion);
2305 bool IsNoReturnConversion(QualType FromType, QualType ToType,
2306 QualType &ResultTy);
2307 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2308 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2310 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2311 const VarDecl *NRVOCandidate,
2312 QualType ResultType,
2314 bool AllowNRVO = true);
2316 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2318 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2319 SourceLocation EqualLoc,
2321 bool TopLevelOfInitList = false,
2322 bool AllowExplicit = false);
2323 ExprResult PerformObjectArgumentInitialization(Expr *From,
2324 NestedNameSpecifier *Qualifier,
2325 NamedDecl *FoundDecl,
2326 CXXMethodDecl *Method);
2328 ExprResult PerformContextuallyConvertToBool(Expr *From);
2329 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2331 /// Contexts in which a converted constant expression is required.
2333 CCEK_CaseValue, ///< Expression in a case label.
2334 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2335 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2336 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2337 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2339 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2340 llvm::APSInt &Value, CCEKind CCE);
2341 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2342 APValue &Value, CCEKind CCE);
2344 /// \brief Abstract base class used to perform a contextual implicit
2345 /// conversion from an expression to any type passing a filter.
2346 class ContextualImplicitConverter {
2349 bool SuppressConversion;
2351 ContextualImplicitConverter(bool Suppress = false,
2352 bool SuppressConversion = false)
2353 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2355 /// \brief Determine whether the specified type is a valid destination type
2356 /// for this conversion.
2357 virtual bool match(QualType T) = 0;
2359 /// \brief Emits a diagnostic complaining that the expression does not have
2360 /// integral or enumeration type.
2361 virtual SemaDiagnosticBuilder
2362 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2364 /// \brief Emits a diagnostic when the expression has incomplete class type.
2365 virtual SemaDiagnosticBuilder
2366 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2368 /// \brief Emits a diagnostic when the only matching conversion function
2370 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2371 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2373 /// \brief Emits a note for the explicit conversion function.
2374 virtual SemaDiagnosticBuilder
2375 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2377 /// \brief Emits a diagnostic when there are multiple possible conversion
2379 virtual SemaDiagnosticBuilder
2380 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2382 /// \brief Emits a note for one of the candidate conversions.
2383 virtual SemaDiagnosticBuilder
2384 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2386 /// \brief Emits a diagnostic when we picked a conversion function
2387 /// (for cases when we are not allowed to pick a conversion function).
2388 virtual SemaDiagnosticBuilder diagnoseConversion(
2389 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2391 virtual ~ContextualImplicitConverter() {}
2394 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2395 bool AllowScopedEnumerations;
2398 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2399 bool Suppress, bool SuppressConversion)
2400 : ContextualImplicitConverter(Suppress, SuppressConversion),
2401 AllowScopedEnumerations(AllowScopedEnumerations) {}
2403 /// Match an integral or (possibly scoped) enumeration type.
2404 bool match(QualType T) override;
2406 SemaDiagnosticBuilder
2407 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2408 return diagnoseNotInt(S, Loc, T);
2411 /// \brief Emits a diagnostic complaining that the expression does not have
2412 /// integral or enumeration type.
2413 virtual SemaDiagnosticBuilder
2414 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2417 /// Perform a contextual implicit conversion.
2418 ExprResult PerformContextualImplicitConversion(
2419 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2422 enum ObjCSubscriptKind {
2427 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2429 // Note that LK_String is intentionally after the other literals, as
2430 // this is used for diagnostics logic.
2431 enum ObjCLiteralKind {
2440 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2442 ExprResult PerformObjectMemberConversion(Expr *From,
2443 NestedNameSpecifier *Qualifier,
2444 NamedDecl *FoundDecl,
2447 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2448 // TODO: make this is a typesafe union.
2449 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2450 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2452 void AddOverloadCandidate(FunctionDecl *Function,
2453 DeclAccessPair FoundDecl,
2454 ArrayRef<Expr *> Args,
2455 OverloadCandidateSet& CandidateSet,
2456 bool SuppressUserConversions = false,
2457 bool PartialOverloading = false,
2458 bool AllowExplicit = false);
2459 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2460 ArrayRef<Expr *> Args,
2461 OverloadCandidateSet &CandidateSet,
2462 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2463 bool SuppressUserConversions = false,
2464 bool PartialOverloading = false);
2465 void AddMethodCandidate(DeclAccessPair FoundDecl,
2466 QualType ObjectType,
2467 Expr::Classification ObjectClassification,
2468 ArrayRef<Expr *> Args,
2469 OverloadCandidateSet& CandidateSet,
2470 bool SuppressUserConversion = false);
2471 void AddMethodCandidate(CXXMethodDecl *Method,
2472 DeclAccessPair FoundDecl,
2473 CXXRecordDecl *ActingContext, QualType ObjectType,
2474 Expr::Classification ObjectClassification,
2475 ArrayRef<Expr *> Args,
2476 OverloadCandidateSet& CandidateSet,
2477 bool SuppressUserConversions = false,
2478 bool PartialOverloading = false);
2479 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2480 DeclAccessPair FoundDecl,
2481 CXXRecordDecl *ActingContext,
2482 TemplateArgumentListInfo *ExplicitTemplateArgs,
2483 QualType ObjectType,
2484 Expr::Classification ObjectClassification,
2485 ArrayRef<Expr *> Args,
2486 OverloadCandidateSet& CandidateSet,
2487 bool SuppressUserConversions = false,
2488 bool PartialOverloading = false);
2489 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2490 DeclAccessPair FoundDecl,
2491 TemplateArgumentListInfo *ExplicitTemplateArgs,
2492 ArrayRef<Expr *> Args,
2493 OverloadCandidateSet& CandidateSet,
2494 bool SuppressUserConversions = false,
2495 bool PartialOverloading = false);
2496 void AddConversionCandidate(CXXConversionDecl *Conversion,
2497 DeclAccessPair FoundDecl,
2498 CXXRecordDecl *ActingContext,
2499 Expr *From, QualType ToType,
2500 OverloadCandidateSet& CandidateSet,
2501 bool AllowObjCConversionOnExplicit);
2502 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2503 DeclAccessPair FoundDecl,
2504 CXXRecordDecl *ActingContext,
2505 Expr *From, QualType ToType,
2506 OverloadCandidateSet &CandidateSet,
2507 bool AllowObjCConversionOnExplicit);
2508 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2509 DeclAccessPair FoundDecl,
2510 CXXRecordDecl *ActingContext,
2511 const FunctionProtoType *Proto,
2512 Expr *Object, ArrayRef<Expr *> Args,
2513 OverloadCandidateSet& CandidateSet);
2514 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2515 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2516 OverloadCandidateSet& CandidateSet,
2517 SourceRange OpRange = SourceRange());
2518 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2519 ArrayRef<Expr *> Args,
2520 OverloadCandidateSet& CandidateSet,
2521 bool IsAssignmentOperator = false,
2522 unsigned NumContextualBoolArguments = 0);
2523 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2524 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2525 OverloadCandidateSet& CandidateSet);
2526 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2528 ArrayRef<Expr *> Args,
2529 TemplateArgumentListInfo *ExplicitTemplateArgs,
2530 OverloadCandidateSet& CandidateSet,
2531 bool PartialOverloading = false);
2533 // Emit as a 'note' the specific overload candidate
2534 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2535 QualType DestType = QualType(),
2536 bool TakingAddress = false);
2538 // Emit as a series of 'note's all template and non-templates identified by
2539 // the expression Expr
2540 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2541 bool TakingAddress = false);
2543 /// Check the enable_if expressions on the given function. Returns the first
2544 /// failing attribute, or NULL if they were all successful.
2545 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2546 bool MissingImplicitThis = false);
2548 /// Returns whether the given function's address can be taken or not,
2549 /// optionally emitting a diagnostic if the address can't be taken.
2551 /// Returns false if taking the address of the function is illegal.
2552 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2553 bool Complain = false,
2554 SourceLocation Loc = SourceLocation());
2556 // [PossiblyAFunctionType] --> [Return]
2557 // NonFunctionType --> NonFunctionType
2559 // R (*)(A) --> R (A)
2560 // R (&)(A) --> R (A)
2561 // R (S::*)(A) --> R (A)
2562 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2565 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2566 QualType TargetType,
2568 DeclAccessPair &Found,
2569 bool *pHadMultipleCandidates = nullptr);
2572 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2573 DeclAccessPair &FoundResult);
2575 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2578 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2579 bool Complain = false,
2580 DeclAccessPair *Found = nullptr);
2582 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2583 ExprResult &SrcExpr,
2584 bool DoFunctionPointerConverion = false,
2585 bool Complain = false,
2586 SourceRange OpRangeForComplaining = SourceRange(),
2587 QualType DestTypeForComplaining = QualType(),
2588 unsigned DiagIDForComplaining = 0);
2591 Expr *FixOverloadedFunctionReference(Expr *E,
2592 DeclAccessPair FoundDecl,
2594 ExprResult FixOverloadedFunctionReference(ExprResult,
2595 DeclAccessPair FoundDecl,
2598 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2599 ArrayRef<Expr *> Args,
2600 OverloadCandidateSet &CandidateSet,
2601 bool PartialOverloading = false);
2603 // An enum used to represent the different possible results of building a
2604 // range-based for loop.
2605 enum ForRangeStatus {
2607 FRS_NoViableFunction,
2608 FRS_DiagnosticIssued
2611 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2612 SourceLocation RangeLoc,
2613 const DeclarationNameInfo &NameInfo,
2614 LookupResult &MemberLookup,
2615 OverloadCandidateSet *CandidateSet,
2616 Expr *Range, ExprResult *CallExpr);
2618 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2619 UnresolvedLookupExpr *ULE,
2620 SourceLocation LParenLoc,
2622 SourceLocation RParenLoc,
2624 bool AllowTypoCorrection=true,
2625 bool CalleesAddressIsTaken=false);
2627 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2628 MultiExprArg Args, SourceLocation RParenLoc,
2629 OverloadCandidateSet *CandidateSet,
2630 ExprResult *Result);
2632 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2633 UnaryOperatorKind Opc,
2634 const UnresolvedSetImpl &Fns,
2637 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2638 BinaryOperatorKind Opc,
2639 const UnresolvedSetImpl &Fns,
2640 Expr *LHS, Expr *RHS);
2642 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2643 SourceLocation RLoc,
2644 Expr *Base,Expr *Idx);
2647 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2648 SourceLocation LParenLoc,
2650 SourceLocation RParenLoc);
2652 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2654 SourceLocation RParenLoc);
2656 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2657 SourceLocation OpLoc,
2658 bool *NoArrowOperatorFound = nullptr);
2660 /// CheckCallReturnType - Checks that a call expression's return type is
2661 /// complete. Returns true on failure. The location passed in is the location
2662 /// that best represents the call.
2663 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2664 CallExpr *CE, FunctionDecl *FD);
2666 /// Helpers for dealing with blocks and functions.
2667 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2668 bool CheckParameterNames);
2669 void CheckCXXDefaultArguments(FunctionDecl *FD);
2670 void CheckExtraCXXDefaultArguments(Declarator &D);
2671 Scope *getNonFieldDeclScope(Scope *S);
2673 /// \name Name lookup
2675 /// These routines provide name lookup that is used during semantic
2676 /// analysis to resolve the various kinds of names (identifiers,
2677 /// overloaded operator names, constructor names, etc.) into zero or
2678 /// more declarations within a particular scope. The major entry
2679 /// points are LookupName, which performs unqualified name lookup,
2680 /// and LookupQualifiedName, which performs qualified name lookup.
2682 /// All name lookup is performed based on some specific criteria,
2683 /// which specify what names will be visible to name lookup and how
2684 /// far name lookup should work. These criteria are important both
2685 /// for capturing language semantics (certain lookups will ignore
2686 /// certain names, for example) and for performance, since name
2687 /// lookup is often a bottleneck in the compilation of C++. Name
2688 /// lookup criteria is specified via the LookupCriteria enumeration.
2690 /// The results of name lookup can vary based on the kind of name
2691 /// lookup performed, the current language, and the translation
2692 /// unit. In C, for example, name lookup will either return nothing
2693 /// (no entity found) or a single declaration. In C++, name lookup
2694 /// can additionally refer to a set of overloaded functions or
2695 /// result in an ambiguity. All of the possible results of name
2696 /// lookup are captured by the LookupResult class, which provides
2697 /// the ability to distinguish among them.
2700 /// @brief Describes the kind of name lookup to perform.
2701 enum LookupNameKind {
2702 /// Ordinary name lookup, which finds ordinary names (functions,
2703 /// variables, typedefs, etc.) in C and most kinds of names
2704 /// (functions, variables, members, types, etc.) in C++.
2705 LookupOrdinaryName = 0,
2706 /// Tag name lookup, which finds the names of enums, classes,
2707 /// structs, and unions.
2709 /// Label name lookup.
2711 /// Member name lookup, which finds the names of
2712 /// class/struct/union members.
2714 /// Look up of an operator name (e.g., operator+) for use with
2715 /// operator overloading. This lookup is similar to ordinary name
2716 /// lookup, but will ignore any declarations that are class members.
2718 /// Look up of a name that precedes the '::' scope resolution
2719 /// operator in C++. This lookup completely ignores operator, object,
2720 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2721 LookupNestedNameSpecifierName,
2722 /// Look up a namespace name within a C++ using directive or
2723 /// namespace alias definition, ignoring non-namespace names (C++
2724 /// [basic.lookup.udir]p1).
2725 LookupNamespaceName,
2726 /// Look up all declarations in a scope with the given name,
2727 /// including resolved using declarations. This is appropriate
2728 /// for checking redeclarations for a using declaration.
2729 LookupUsingDeclName,
2730 /// Look up an ordinary name that is going to be redeclared as a
2731 /// name with linkage. This lookup ignores any declarations that
2732 /// are outside of the current scope unless they have linkage. See
2733 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2734 LookupRedeclarationWithLinkage,
2735 /// Look up a friend of a local class. This lookup does not look
2736 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2737 LookupLocalFriendName,
2738 /// Look up the name of an Objective-C protocol.
2739 LookupObjCProtocolName,
2740 /// Look up implicit 'self' parameter of an objective-c method.
2741 LookupObjCImplicitSelfParam,
2742 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2743 LookupOMPReductionName,
2744 /// \brief Look up any declaration with any name.
2748 /// \brief Specifies whether (or how) name lookup is being performed for a
2749 /// redeclaration (vs. a reference).
2750 enum RedeclarationKind {
2751 /// \brief The lookup is a reference to this name that is not for the
2752 /// purpose of redeclaring the name.
2753 NotForRedeclaration = 0,
2754 /// \brief The lookup results will be used for redeclaration of a name,
2755 /// if an entity by that name already exists.
2759 /// \brief The possible outcomes of name lookup for a literal operator.
2760 enum LiteralOperatorLookupResult {
2761 /// \brief The lookup resulted in an error.
2763 /// \brief The lookup found a single 'cooked' literal operator, which
2764 /// expects a normal literal to be built and passed to it.
2766 /// \brief The lookup found a single 'raw' literal operator, which expects
2767 /// a string literal containing the spelling of the literal token.
2769 /// \brief The lookup found an overload set of literal operator templates,
2770 /// which expect the characters of the spelling of the literal token to be
2771 /// passed as a non-type template argument pack.
2773 /// \brief The lookup found an overload set of literal operator templates,
2774 /// which expect the character type and characters of the spelling of the
2775 /// string literal token to be passed as template arguments.
2779 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2780 CXXSpecialMember SM,
2787 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2788 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2789 TypoRecoveryCallback;
2792 bool CppLookupName(LookupResult &R, Scope *S);
2794 struct TypoExprState {
2795 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2796 TypoDiagnosticGenerator DiagHandler;
2797 TypoRecoveryCallback RecoveryHandler;
2799 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2800 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2803 /// \brief The set of unhandled TypoExprs and their associated state.
2804 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2806 /// \brief Creates a new TypoExpr AST node.
2807 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2808 TypoDiagnosticGenerator TDG,
2809 TypoRecoveryCallback TRC);
2811 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2813 // The boolean value will be true to indicate that the namespace was loaded
2814 // from an AST/PCH file, or false otherwise.
2815 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2817 /// \brief Whether we have already loaded known namespaces from an extenal
2819 bool LoadedExternalKnownNamespaces;
2821 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2822 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2823 /// should be skipped entirely.
2824 std::unique_ptr<TypoCorrectionConsumer>
2825 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2826 Sema::LookupNameKind LookupKind, Scope *S,
2828 std::unique_ptr<CorrectionCandidateCallback> CCC,
2829 DeclContext *MemberContext, bool EnteringContext,
2830 const ObjCObjectPointerType *OPT,
2831 bool ErrorRecovery);
2834 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2836 /// \brief Clears the state of the given TypoExpr.
2837 void clearDelayedTypo(TypoExpr *TE);
2839 /// \brief Look up a name, looking for a single declaration. Return
2840 /// null if the results were absent, ambiguous, or overloaded.
2842 /// It is preferable to use the elaborated form and explicitly handle
2843 /// ambiguity and overloaded.
2844 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2846 LookupNameKind NameKind,
2847 RedeclarationKind Redecl
2848 = NotForRedeclaration);
2849 bool LookupName(LookupResult &R, Scope *S,
2850 bool AllowBuiltinCreation = false);
2851 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2852 bool InUnqualifiedLookup = false);
2853 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2855 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2856 bool AllowBuiltinCreation = false,
2857 bool EnteringContext = false);
2858 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2859 RedeclarationKind Redecl
2860 = NotForRedeclaration);
2861 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2863 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2864 QualType T1, QualType T2,
2865 UnresolvedSetImpl &Functions);
2866 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2867 DeclAccessPair Operator,
2868 QualType T1, QualType T2);
2870 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2871 SourceLocation GnuLabelLoc = SourceLocation());
2873 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2874 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2875 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2877 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2878 bool RValueThis, unsigned ThisQuals);
2879 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2881 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2882 bool RValueThis, unsigned ThisQuals);
2883 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2885 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2886 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2887 ArrayRef<QualType> ArgTys,
2890 bool AllowStringTemplate);
2891 bool isKnownName(StringRef name);
2893 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2894 ArrayRef<Expr *> Args, ADLResult &Functions);
2896 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2897 VisibleDeclConsumer &Consumer,
2898 bool IncludeGlobalScope = true);
2899 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2900 VisibleDeclConsumer &Consumer,
2901 bool IncludeGlobalScope = true);
2903 enum CorrectTypoKind {
2904 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2905 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2908 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2909 Sema::LookupNameKind LookupKind,
2910 Scope *S, CXXScopeSpec *SS,
2911 std::unique_ptr<CorrectionCandidateCallback> CCC,
2912 CorrectTypoKind Mode,
2913 DeclContext *MemberContext = nullptr,
2914 bool EnteringContext = false,
2915 const ObjCObjectPointerType *OPT = nullptr,
2916 bool RecordFailure = true);
2918 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2919 Sema::LookupNameKind LookupKind, Scope *S,
2921 std::unique_ptr<CorrectionCandidateCallback> CCC,
2922 TypoDiagnosticGenerator TDG,
2923 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2924 DeclContext *MemberContext = nullptr,
2925 bool EnteringContext = false,
2926 const ObjCObjectPointerType *OPT = nullptr);
2928 /// \brief Process any TypoExprs in the given Expr and its children,
2929 /// generating diagnostics as appropriate and returning a new Expr if there
2930 /// were typos that were all successfully corrected and ExprError if one or
2931 /// more typos could not be corrected.
2933 /// \param E The Expr to check for TypoExprs.
2935 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2938 /// \param Filter A function applied to a newly rebuilt Expr to determine if
2939 /// it is an acceptable/usable result from a single combination of typo
2940 /// corrections. As long as the filter returns ExprError, different
2941 /// combinations of corrections will be tried until all are exhausted.
2943 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
2944 llvm::function_ref<ExprResult(Expr *)> Filter =
2945 [](Expr *E) -> ExprResult { return E; });
2948 CorrectDelayedTyposInExpr(Expr *E,
2949 llvm::function_ref<ExprResult(Expr *)> Filter) {
2950 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
2954 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
2955 llvm::function_ref<ExprResult(Expr *)> Filter =
2956 [](Expr *E) -> ExprResult { return E; }) {
2957 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2961 CorrectDelayedTyposInExpr(ExprResult ER,
2962 llvm::function_ref<ExprResult(Expr *)> Filter) {
2963 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
2966 void diagnoseTypo(const TypoCorrection &Correction,
2967 const PartialDiagnostic &TypoDiag,
2968 bool ErrorRecovery = true);
2970 void diagnoseTypo(const TypoCorrection &Correction,
2971 const PartialDiagnostic &TypoDiag,
2972 const PartialDiagnostic &PrevNote,
2973 bool ErrorRecovery = true);
2975 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2976 ArrayRef<Expr *> Args,
2977 AssociatedNamespaceSet &AssociatedNamespaces,
2978 AssociatedClassSet &AssociatedClasses);
2980 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2981 bool ConsiderLinkage, bool AllowInlineNamespace);
2983 void DiagnoseAmbiguousLookup(LookupResult &Result);
2986 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2987 SourceLocation IdLoc,
2988 bool TypoCorrection = false);
2989 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2990 Scope *S, bool ForRedeclaration,
2991 SourceLocation Loc);
2992 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2994 void AddKnownFunctionAttributes(FunctionDecl *FD);
2996 // More parsing and symbol table subroutines.
2998 void ProcessPragmaWeak(Scope *S, Decl *D);
2999 // Decl attributes - this routine is the top level dispatcher.
3000 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3001 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3002 bool IncludeCXX11Attributes = true);
3003 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3004 const AttributeList *AttrList);
3006 void checkUnusedDeclAttributes(Declarator &D);
3008 /// Determine if type T is a valid subject for a nonnull and similar
3009 /// attributes. By default, we look through references (the behavior used by
3010 /// nonnull), but if the second parameter is true, then we treat a reference
3012 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3014 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3015 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3016 const FunctionDecl *FD = nullptr);
3017 bool CheckNoReturnAttr(const AttributeList &attr);
3018 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3019 unsigned ArgNum, StringRef &Str,
3020 SourceLocation *ArgLocation = nullptr);
3021 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3022 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3023 bool checkMSInheritanceAttrOnDefinition(
3024 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3025 MSInheritanceAttr::Spelling SemanticSpelling);
3027 void CheckAlignasUnderalignment(Decl *D);
3029 /// Adjust the calling convention of a method to be the ABI default if it
3030 /// wasn't specified explicitly. This handles method types formed from
3031 /// function type typedefs and typename template arguments.
3032 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3033 SourceLocation Loc);
3035 // Check if there is an explicit attribute, but only look through parens.
3036 // The intent is to look for an attribute on the current declarator, but not
3037 // one that came from a typedef.
3038 bool hasExplicitCallingConv(QualType &T);
3040 /// Get the outermost AttributedType node that sets a calling convention.
3041 /// Valid types should not have multiple attributes with different CCs.
3042 const AttributedType *getCallingConvAttributedType(QualType T) const;
3044 /// Check whether a nullability type specifier can be added to the given
3047 /// \param type The type to which the nullability specifier will be
3048 /// added. On success, this type will be updated appropriately.
3050 /// \param nullability The nullability specifier to add.
3052 /// \param nullabilityLoc The location of the nullability specifier.
3054 /// \param isContextSensitive Whether this nullability specifier was
3055 /// written as a context-sensitive keyword (in an Objective-C
3056 /// method) or an Objective-C property attribute, rather than as an
3057 /// underscored type specifier.
3059 /// \returns true if nullability cannot be applied, false otherwise.
3060 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3061 SourceLocation nullabilityLoc,
3062 bool isContextSensitive);
3064 /// \brief Stmt attributes - this routine is the top level dispatcher.
3065 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3068 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3069 ObjCMethodDecl *MethodDecl,
3070 bool IsProtocolMethodDecl);
3072 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3073 ObjCMethodDecl *Overridden,
3074 bool IsProtocolMethodDecl);
3076 /// WarnExactTypedMethods - This routine issues a warning if method
3077 /// implementation declaration matches exactly that of its declaration.
3078 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3079 ObjCMethodDecl *MethodDecl,
3080 bool IsProtocolMethodDecl);
3082 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3083 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
3085 /// CheckImplementationIvars - This routine checks if the instance variables
3086 /// listed in the implelementation match those listed in the interface.
3087 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3088 ObjCIvarDecl **Fields, unsigned nIvars,
3089 SourceLocation Loc);
3091 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3092 /// remains unimplemented in the class or category \@implementation.
3093 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3094 ObjCContainerDecl* IDecl,
3095 bool IncompleteImpl = false);
3097 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3098 /// which must be implemented by this implementation.
3099 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3100 ObjCContainerDecl *CDecl,
3101 bool SynthesizeProperties);
3103 /// Diagnose any null-resettable synthesized setters.
3104 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3106 /// DefaultSynthesizeProperties - This routine default synthesizes all
3107 /// properties which must be synthesized in the class's \@implementation.
3108 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3109 ObjCInterfaceDecl *IDecl);
3110 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3112 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3113 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3114 /// declared in class 'IFace'.
3115 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3116 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3118 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3119 /// backs the property is not used in the property's accessor.
3120 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3121 const ObjCImplementationDecl *ImplD);
3123 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3124 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3125 /// It also returns ivar's property on success.
3126 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3127 const ObjCPropertyDecl *&PDecl) const;
3129 /// Called by ActOnProperty to handle \@property declarations in
3130 /// class extensions.
3131 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3132 SourceLocation AtLoc,
3133 SourceLocation LParenLoc,
3134 FieldDeclarator &FD,
3137 const bool isReadWrite,
3138 unsigned &Attributes,
3139 const unsigned AttributesAsWritten,
3141 TypeSourceInfo *TSI,
3142 tok::ObjCKeywordKind MethodImplKind);
3144 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3145 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3146 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3147 ObjCContainerDecl *CDecl,
3148 SourceLocation AtLoc,
3149 SourceLocation LParenLoc,
3150 FieldDeclarator &FD,
3153 const bool isReadWrite,
3154 const unsigned Attributes,
3155 const unsigned AttributesAsWritten,
3157 TypeSourceInfo *TSI,
3158 tok::ObjCKeywordKind MethodImplKind,
3159 DeclContext *lexicalDC = nullptr);
3161 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3162 /// warning) when atomic property has one but not the other user-declared
3163 /// setter or getter.
3164 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3165 ObjCInterfaceDecl* IDecl);
3167 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3169 void DiagnoseMissingDesignatedInitOverrides(
3170 const ObjCImplementationDecl *ImplD,
3171 const ObjCInterfaceDecl *IFD);
3173 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3175 enum MethodMatchStrategy {
3180 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3181 /// true, or false, accordingly.
3182 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3183 const ObjCMethodDecl *PrevMethod,
3184 MethodMatchStrategy strategy = MMS_strict);
3186 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3187 /// or protocol against those declared in their implementations.
3188 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3189 const SelectorSet &ClsMap,
3190 SelectorSet &InsMapSeen,
3191 SelectorSet &ClsMapSeen,
3192 ObjCImplDecl* IMPDecl,
3193 ObjCContainerDecl* IDecl,
3194 bool &IncompleteImpl,
3195 bool ImmediateClass,
3196 bool WarnCategoryMethodImpl=false);
3198 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3199 /// category matches with those implemented in its primary class and
3200 /// warns each time an exact match is found.
3201 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3203 /// \brief Add the given method to the list of globally-known methods.
3204 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3207 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3208 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3209 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3211 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3212 /// optionally warns if there are multiple signatures.
3213 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3214 bool receiverIdOrClass,
3218 /// \brief - Returns instance or factory methods in global method pool for
3219 /// given selector. It checks the desired kind first, if none is found, and
3220 /// parameter checkTheOther is set, it then checks the other kind. If no such
3221 /// method or only one method is found, function returns false; otherwise, it
3224 CollectMultipleMethodsInGlobalPool(Selector Sel,
3225 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3226 bool InstanceFirst, bool CheckTheOther,
3227 const ObjCObjectType *TypeBound = nullptr);
3230 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3231 SourceRange R, bool receiverIdOrClass,
3232 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3235 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3236 Selector Sel, SourceRange R,
3237 bool receiverIdOrClass);
3240 /// \brief - Returns a selector which best matches given argument list or
3241 /// nullptr if none could be found
3242 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3244 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3247 /// \brief Record the typo correction failure and return an empty correction.
3248 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3249 bool RecordFailure = true) {
3251 TypoCorrectionFailures[Typo].insert(TypoLoc);
3252 return TypoCorrection();
3256 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3257 /// unit are added to a global pool. This allows us to efficiently associate
3258 /// a selector with a method declaraation for purposes of typechecking
3259 /// messages sent to "id" (where the class of the object is unknown).
3260 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3261 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3264 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3265 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3266 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3269 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3271 void AddAnyMethodToGlobalPool(Decl *D);
3273 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3274 /// there are multiple signatures.
3275 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3276 bool receiverIdOrClass=false) {
3277 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3281 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3282 /// there are multiple signatures.
3283 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3284 bool receiverIdOrClass=false) {
3285 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3289 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3290 QualType ObjectType=QualType());
3291 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3293 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3295 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3297 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3298 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3300 //===--------------------------------------------------------------------===//
3301 // Statement Parsing Callbacks: SemaStmt.cpp.
3305 FullExprArg() : E(nullptr) { }
3306 FullExprArg(Sema &actions) : E(nullptr) { }
3308 ExprResult release() {
3312 Expr *get() const { return E; }
3314 Expr *operator->() {
3319 // FIXME: No need to make the entire Sema class a friend when it's just
3320 // Sema::MakeFullExpr that needs access to the constructor below.
3323 explicit FullExprArg(Expr *expr) : E(expr) {}
3328 FullExprArg MakeFullExpr(Expr *Arg) {
3329 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3331 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3332 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3334 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3336 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3337 /*DiscardedValue*/ true);
3338 return FullExprArg(FE.get());
3341 StmtResult ActOnExprStmt(ExprResult Arg);
3342 StmtResult ActOnExprStmtError();
3344 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3345 bool HasLeadingEmptyMacro = false);
3347 void ActOnStartOfCompoundStmt();
3348 void ActOnFinishOfCompoundStmt();
3349 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3350 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3352 /// \brief A RAII object to enter scope of a compound statement.
3353 class CompoundScopeRAII {
3355 CompoundScopeRAII(Sema &S): S(S) {
3356 S.ActOnStartOfCompoundStmt();
3359 ~CompoundScopeRAII() {
3360 S.ActOnFinishOfCompoundStmt();
3367 /// An RAII helper that pops function a function scope on exit.
3368 struct FunctionScopeRAII {
3371 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3372 ~FunctionScopeRAII() {
3374 S.PopFunctionScopeInfo();
3376 void disable() { Active = false; }
3379 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3380 SourceLocation StartLoc,
3381 SourceLocation EndLoc);
3382 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3383 StmtResult ActOnForEachLValueExpr(Expr *E);
3384 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3385 SourceLocation DotDotDotLoc, Expr *RHSVal,
3386 SourceLocation ColonLoc);
3387 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3389 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3390 SourceLocation ColonLoc,
3391 Stmt *SubStmt, Scope *CurScope);
3392 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3393 SourceLocation ColonLoc, Stmt *SubStmt);
3395 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3396 ArrayRef<const Attr*> Attrs,
3399 class ConditionResult;
3400 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3402 ConditionResult Cond, Stmt *ThenVal,
3403 SourceLocation ElseLoc, Stmt *ElseVal);
3404 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3406 ConditionResult Cond, Stmt *ThenVal,
3407 SourceLocation ElseLoc, Stmt *ElseVal);
3408 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3410 ConditionResult Cond);
3411 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3412 Stmt *Switch, Stmt *Body);
3413 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3415 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3416 SourceLocation WhileLoc, SourceLocation CondLParen,
3417 Expr *Cond, SourceLocation CondRParen);
3419 StmtResult ActOnForStmt(SourceLocation ForLoc,
3420 SourceLocation LParenLoc,
3422 ConditionResult Second,
3424 SourceLocation RParenLoc,
3426 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3428 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3429 Stmt *First, Expr *collection,
3430 SourceLocation RParenLoc);
3431 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3433 enum BuildForRangeKind {
3434 /// Initial building of a for-range statement.
3436 /// Instantiation or recovery rebuild of a for-range statement. Don't
3437 /// attempt any typo-correction.
3439 /// Determining whether a for-range statement could be built. Avoid any
3440 /// unnecessary or irreversible actions.
3444 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3445 SourceLocation CoawaitLoc,
3447 SourceLocation ColonLoc, Expr *Collection,
3448 SourceLocation RParenLoc,
3449 BuildForRangeKind Kind);
3450 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3451 SourceLocation CoawaitLoc,
3452 SourceLocation ColonLoc,
3453 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3454 Expr *Cond, Expr *Inc,
3456 SourceLocation RParenLoc,
3457 BuildForRangeKind Kind);
3458 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3460 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3461 SourceLocation LabelLoc,
3462 LabelDecl *TheDecl);
3463 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3464 SourceLocation StarLoc,
3466 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3467 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3469 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3470 CapturedRegionKind Kind, unsigned NumParams);
3471 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3472 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3473 CapturedRegionKind Kind,
3474 ArrayRef<CapturedParamNameType> Params);
3475 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3476 void ActOnCapturedRegionError();
3477 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3479 unsigned NumParams);
3480 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3481 bool AllowParamOrMoveConstructible);
3482 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3483 bool AllowParamOrMoveConstructible);
3485 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3487 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3488 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3490 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3491 bool IsVolatile, unsigned NumOutputs,
3492 unsigned NumInputs, IdentifierInfo **Names,
3493 MultiExprArg Constraints, MultiExprArg Exprs,
3494 Expr *AsmString, MultiExprArg Clobbers,
3495 SourceLocation RParenLoc);
3497 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3498 SourceLocation TemplateKWLoc,
3500 llvm::InlineAsmIdentifierInfo &Info,
3501 bool IsUnevaluatedContext);
3502 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3503 unsigned &Offset, SourceLocation AsmLoc);
3504 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3505 llvm::InlineAsmIdentifierInfo &Info,
3506 SourceLocation AsmLoc);
3507 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3508 ArrayRef<Token> AsmToks,
3509 StringRef AsmString,
3510 unsigned NumOutputs, unsigned NumInputs,
3511 ArrayRef<StringRef> Constraints,
3512 ArrayRef<StringRef> Clobbers,
3513 ArrayRef<Expr*> Exprs,
3514 SourceLocation EndLoc);
3515 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3516 SourceLocation Location,
3519 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3520 SourceLocation StartLoc,
3521 SourceLocation IdLoc, IdentifierInfo *Id,
3522 bool Invalid = false);
3524 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3526 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3527 Decl *Parm, Stmt *Body);
3529 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3531 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3532 MultiStmtArg Catch, Stmt *Finally);
3534 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3535 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3537 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3539 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3543 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3545 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3546 SourceLocation StartLoc,
3547 SourceLocation IdLoc,
3548 IdentifierInfo *Id);
3550 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3552 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3553 Decl *ExDecl, Stmt *HandlerBlock);
3554 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3555 ArrayRef<Stmt *> Handlers);
3557 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3558 SourceLocation TryLoc, Stmt *TryBlock,
3560 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3563 void ActOnStartSEHFinallyBlock();
3564 void ActOnAbortSEHFinallyBlock();
3565 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3566 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3568 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3570 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3572 /// \brief If it's a file scoped decl that must warn if not used, keep track
3574 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3576 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3577 /// whose result is unused, warn.
3578 void DiagnoseUnusedExprResult(const Stmt *S);
3579 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3580 void DiagnoseUnusedDecl(const NamedDecl *ND);
3582 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3583 /// statement as a \p Body, and it is located on the same line.
3585 /// This helps prevent bugs due to typos, such as:
3588 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3592 /// Warn if a for/while loop statement \p S, which is followed by
3593 /// \p PossibleBody, has a suspicious null statement as a body.
3594 void DiagnoseEmptyLoopBody(const Stmt *S,
3595 const Stmt *PossibleBody);
3597 /// Warn if a value is moved to itself.
3598 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3599 SourceLocation OpLoc);
3601 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3603 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3604 SourceLocation Loc);
3606 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3607 return DelayedDiagnostics.push(pool);
3609 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3611 typedef ProcessingContextState ParsingClassState;
3612 ParsingClassState PushParsingClass() {
3613 return DelayedDiagnostics.pushUndelayed();
3615 void PopParsingClass(ParsingClassState state) {
3616 DelayedDiagnostics.popUndelayed(state);
3619 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3621 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
3623 void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3624 NamedDecl *D, StringRef Message,
3626 const ObjCInterfaceDecl *UnknownObjCClass,
3627 const ObjCPropertyDecl *ObjCProperty,
3628 bool ObjCPropertyAccess);
3630 bool makeUnavailableInSystemHeader(SourceLocation loc,
3631 UnavailableAttr::ImplicitReason reason);
3633 //===--------------------------------------------------------------------===//
3634 // Expression Parsing Callbacks: SemaExpr.cpp.
3636 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3637 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3638 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3639 bool ObjCPropertyAccess=false);
3640 void NoteDeletedFunction(FunctionDecl *FD);
3641 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3642 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3643 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3644 ObjCMethodDecl *Getter,
3645 SourceLocation Loc);
3646 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3647 ArrayRef<Expr *> Args);
3649 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3650 Decl *LambdaContextDecl = nullptr,
3651 bool IsDecltype = false);
3652 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3653 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3654 ReuseLambdaContextDecl_t,
3655 bool IsDecltype = false);
3656 void PopExpressionEvaluationContext();
3658 void DiscardCleanupsInEvaluationContext();
3660 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3661 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3663 ExprResult ActOnConstantExpression(ExprResult Res);
3665 // Functions for marking a declaration referenced. These functions also
3666 // contain the relevant logic for marking if a reference to a function or
3667 // variable is an odr-use (in the C++11 sense). There are separate variants
3668 // for expressions referring to a decl; these exist because odr-use marking
3669 // needs to be delayed for some constant variables when we build one of the
3670 // named expressions.
3672 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3673 // should usually be true. This only needs to be set to false if the lack of
3674 // odr-use cannot be determined from the current context (for instance,
3675 // because the name denotes a virtual function and was written without an
3676 // explicit nested-name-specifier).
3677 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3678 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3679 bool MightBeOdrUse = true);
3680 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3681 void MarkDeclRefReferenced(DeclRefExpr *E);
3682 void MarkMemberReferenced(MemberExpr *E);
3684 void UpdateMarkingForLValueToRValue(Expr *E);
3685 void CleanupVarDeclMarking();
3687 enum TryCaptureKind {
3688 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3691 /// \brief Try to capture the given variable.
3693 /// \param Var The variable to capture.
3695 /// \param Loc The location at which the capture occurs.
3697 /// \param Kind The kind of capture, which may be implicit (for either a
3698 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3700 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3701 /// an explicit lambda capture.
3703 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3704 /// captures or diagnose errors. If false, this routine merely check whether
3705 /// the capture can occur without performing the capture itself or complaining
3706 /// if the variable cannot be captured.
3708 /// \param CaptureType Will be set to the type of the field used to capture
3709 /// this variable in the innermost block or lambda. Only valid when the
3710 /// variable can be captured.
3712 /// \param DeclRefType Will be set to the type of a reference to the capture
3713 /// from within the current scope. Only valid when the variable can be
3716 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3717 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3718 /// This is useful when enclosing lambdas must speculatively capture
3719 /// variables that may or may not be used in certain specializations of
3720 /// a nested generic lambda.
3722 /// \returns true if an error occurred (i.e., the variable cannot be
3723 /// captured) and false if the capture succeeded.
3724 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3725 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3726 QualType &CaptureType,
3727 QualType &DeclRefType,
3728 const unsigned *const FunctionScopeIndexToStopAt);
3730 /// \brief Try to capture the given variable.
3731 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3732 TryCaptureKind Kind = TryCapture_Implicit,
3733 SourceLocation EllipsisLoc = SourceLocation());
3735 /// \brief Checks if the variable must be captured.
3736 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3738 /// \brief Given a variable, determine the type that a reference to that
3739 /// variable will have in the given scope.
3740 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3742 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3743 void MarkDeclarationsReferencedInExpr(Expr *E,
3744 bool SkipLocalVariables = false);
3746 /// \brief Try to recover by turning the given expression into a
3747 /// call. Returns true if recovery was attempted or an error was
3748 /// emitted; this may also leave the ExprResult invalid.
3749 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3750 bool ForceComplain = false,
3751 bool (*IsPlausibleResult)(QualType) = nullptr);
3753 /// \brief Figure out if an expression could be turned into a call.
3754 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3755 UnresolvedSetImpl &NonTemplateOverloads);
3757 /// \brief Conditionally issue a diagnostic based on the current
3758 /// evaluation context.
3760 /// \param Statement If Statement is non-null, delay reporting the
3761 /// diagnostic until the function body is parsed, and then do a basic
3762 /// reachability analysis to determine if the statement is reachable.
3763 /// If it is unreachable, the diagnostic will not be emitted.
3764 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3765 const PartialDiagnostic &PD);
3767 // Primary Expressions.
3768 SourceRange getExprRange(Expr *E) const;
3770 ExprResult ActOnIdExpression(
3771 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3772 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3773 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3774 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3776 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3777 TemplateArgumentListInfo &Buffer,
3778 DeclarationNameInfo &NameInfo,
3779 const TemplateArgumentListInfo *&TemplateArgs);
3782 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3783 std::unique_ptr<CorrectionCandidateCallback> CCC,
3784 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3785 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3787 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3789 bool AllowBuiltinCreation=false);
3791 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3792 SourceLocation TemplateKWLoc,
3793 const DeclarationNameInfo &NameInfo,
3794 bool isAddressOfOperand,
3795 const TemplateArgumentListInfo *TemplateArgs);
3797 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3800 const CXXScopeSpec *SS = nullptr);
3802 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3803 const DeclarationNameInfo &NameInfo,
3804 const CXXScopeSpec *SS = nullptr,
3805 NamedDecl *FoundD = nullptr,
3806 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3808 BuildAnonymousStructUnionMemberReference(
3809 const CXXScopeSpec &SS,
3810 SourceLocation nameLoc,
3811 IndirectFieldDecl *indirectField,
3812 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3813 Expr *baseObjectExpr = nullptr,
3814 SourceLocation opLoc = SourceLocation());
3816 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3817 SourceLocation TemplateKWLoc,
3819 const TemplateArgumentListInfo *TemplateArgs,
3821 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3822 SourceLocation TemplateKWLoc,
3824 const TemplateArgumentListInfo *TemplateArgs,
3825 bool IsDefiniteInstance,
3827 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3828 const LookupResult &R,
3829 bool HasTrailingLParen);
3832 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3833 const DeclarationNameInfo &NameInfo,
3834 bool IsAddressOfOperand, const Scope *S,
3835 TypeSourceInfo **RecoveryTSI = nullptr);
3837 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3838 SourceLocation TemplateKWLoc,
3839 const DeclarationNameInfo &NameInfo,
3840 const TemplateArgumentListInfo *TemplateArgs);
3842 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3845 bool AcceptInvalidDecl = false);
3846 ExprResult BuildDeclarationNameExpr(
3847 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3848 NamedDecl *FoundD = nullptr,
3849 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3850 bool AcceptInvalidDecl = false);
3852 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3853 DeclarationNameInfo &SuffixInfo,
3854 ArrayRef<Expr *> Args,
3855 SourceLocation LitEndLoc,
3856 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3858 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3859 PredefinedExpr::IdentType IT);
3860 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3861 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3863 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3865 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3866 ExprResult ActOnCharacterConstant(const Token &Tok,
3867 Scope *UDLScope = nullptr);
3868 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3869 ExprResult ActOnParenListExpr(SourceLocation L,
3873 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3874 /// fragments (e.g. "foo" "bar" L"baz").
3875 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3876 Scope *UDLScope = nullptr);
3878 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3879 SourceLocation DefaultLoc,
3880 SourceLocation RParenLoc,
3881 Expr *ControllingExpr,
3882 ArrayRef<ParsedType> ArgTypes,
3883 ArrayRef<Expr *> ArgExprs);
3884 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3885 SourceLocation DefaultLoc,
3886 SourceLocation RParenLoc,
3887 Expr *ControllingExpr,
3888 ArrayRef<TypeSourceInfo *> Types,
3889 ArrayRef<Expr *> Exprs);
3891 // Binary/Unary Operators. 'Tok' is the token for the operator.
3892 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3894 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3895 UnaryOperatorKind Opc, Expr *Input);
3896 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3897 tok::TokenKind Op, Expr *Input);
3899 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3901 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3902 SourceLocation OpLoc,
3903 UnaryExprOrTypeTrait ExprKind,
3905 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3906 UnaryExprOrTypeTrait ExprKind);
3908 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3909 UnaryExprOrTypeTrait ExprKind,
3910 bool IsType, void *TyOrEx,
3911 SourceRange ArgRange);
3913 ExprResult CheckPlaceholderExpr(Expr *E);
3914 bool CheckVecStepExpr(Expr *E);
3916 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3917 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3918 SourceRange ExprRange,
3919 UnaryExprOrTypeTrait ExprKind);
3920 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3921 SourceLocation OpLoc,
3922 IdentifierInfo &Name,
3923 SourceLocation NameLoc,
3924 SourceLocation RParenLoc);
3925 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3926 tok::TokenKind Kind, Expr *Input);
3928 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3929 Expr *Idx, SourceLocation RLoc);
3930 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3931 Expr *Idx, SourceLocation RLoc);
3932 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3933 Expr *LowerBound, SourceLocation ColonLoc,
3934 Expr *Length, SourceLocation RBLoc);
3936 // This struct is for use by ActOnMemberAccess to allow
3937 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3938 // changing the access operator from a '.' to a '->' (to see if that is the
3939 // change needed to fix an error about an unknown member, e.g. when the class
3940 // defines a custom operator->).
3941 struct ActOnMemberAccessExtraArgs {
3947 ExprResult BuildMemberReferenceExpr(
3948 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3949 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3950 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3951 const TemplateArgumentListInfo *TemplateArgs,
3953 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3956 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3957 bool IsArrow, const CXXScopeSpec &SS,
3958 SourceLocation TemplateKWLoc,
3959 NamedDecl *FirstQualifierInScope, LookupResult &R,
3960 const TemplateArgumentListInfo *TemplateArgs,
3962 bool SuppressQualifierCheck = false,
3963 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3965 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3967 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3968 const CXXScopeSpec &SS,
3969 const LookupResult &R);
3971 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3972 bool IsArrow, SourceLocation OpLoc,
3973 const CXXScopeSpec &SS,
3974 SourceLocation TemplateKWLoc,
3975 NamedDecl *FirstQualifierInScope,
3976 const DeclarationNameInfo &NameInfo,
3977 const TemplateArgumentListInfo *TemplateArgs);
3979 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3980 SourceLocation OpLoc,
3981 tok::TokenKind OpKind,
3983 SourceLocation TemplateKWLoc,
3984 UnqualifiedId &Member,
3987 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3988 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3989 FunctionDecl *FDecl,
3990 const FunctionProtoType *Proto,
3991 ArrayRef<Expr *> Args,
3992 SourceLocation RParenLoc,
3993 bool ExecConfig = false);
3994 void CheckStaticArrayArgument(SourceLocation CallLoc,
3996 const Expr *ArgExpr);
3998 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3999 /// This provides the location of the left/right parens and a list of comma
4001 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4002 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4003 Expr *ExecConfig = nullptr,
4004 bool IsExecConfig = false);
4005 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4006 SourceLocation LParenLoc,
4007 ArrayRef<Expr *> Arg,
4008 SourceLocation RParenLoc,
4009 Expr *Config = nullptr,
4010 bool IsExecConfig = false);
4012 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4013 MultiExprArg ExecConfig,
4014 SourceLocation GGGLoc);
4016 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4017 Declarator &D, ParsedType &Ty,
4018 SourceLocation RParenLoc, Expr *CastExpr);
4019 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4021 SourceLocation RParenLoc,
4023 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4025 /// \brief Build an altivec or OpenCL literal.
4026 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4027 SourceLocation RParenLoc, Expr *E,
4028 TypeSourceInfo *TInfo);
4030 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4032 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4034 SourceLocation RParenLoc,
4037 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4038 TypeSourceInfo *TInfo,
4039 SourceLocation RParenLoc,
4042 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4043 MultiExprArg InitArgList,
4044 SourceLocation RBraceLoc);
4046 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4052 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4055 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4056 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4057 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4058 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4059 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4060 Expr *LHSExpr, Expr *RHSExpr);
4062 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4064 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4065 /// in the case of a the GNU conditional expr extension.
4066 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4067 SourceLocation ColonLoc,
4068 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4070 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4071 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4072 LabelDecl *TheDecl);
4074 void ActOnStartStmtExpr();
4075 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4076 SourceLocation RPLoc); // "({..})"
4077 void ActOnStmtExprError();
4079 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4080 struct OffsetOfComponent {
4081 SourceLocation LocStart, LocEnd;
4082 bool isBrackets; // true if [expr], false if .ident
4084 IdentifierInfo *IdentInfo;
4089 /// __builtin_offsetof(type, a.b[123][456].c)
4090 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4091 TypeSourceInfo *TInfo,
4092 ArrayRef<OffsetOfComponent> Components,
4093 SourceLocation RParenLoc);
4094 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4095 SourceLocation BuiltinLoc,
4096 SourceLocation TypeLoc,
4097 ParsedType ParsedArgTy,
4098 ArrayRef<OffsetOfComponent> Components,
4099 SourceLocation RParenLoc);
4101 // __builtin_choose_expr(constExpr, expr1, expr2)
4102 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4103 Expr *CondExpr, Expr *LHSExpr,
4104 Expr *RHSExpr, SourceLocation RPLoc);
4106 // __builtin_va_arg(expr, type)
4107 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4108 SourceLocation RPLoc);
4109 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4110 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4113 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4115 bool CheckCaseExpression(Expr *E);
4117 /// \brief Describes the result of an "if-exists" condition check.
4118 enum IfExistsResult {
4119 /// \brief The symbol exists.
4122 /// \brief The symbol does not exist.
4125 /// \brief The name is a dependent name, so the results will differ
4126 /// from one instantiation to the next.
4129 /// \brief An error occurred.
4134 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4135 const DeclarationNameInfo &TargetNameInfo);
4138 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4139 bool IsIfExists, CXXScopeSpec &SS,
4140 UnqualifiedId &Name);
4142 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4144 NestedNameSpecifierLoc QualifierLoc,
4145 DeclarationNameInfo NameInfo,
4147 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4149 CXXScopeSpec &SS, UnqualifiedId &Name,
4152 //===------------------------- "Block" Extension ------------------------===//
4154 /// ActOnBlockStart - This callback is invoked when a block literal is
4156 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4158 /// ActOnBlockArguments - This callback allows processing of block arguments.
4159 /// If there are no arguments, this is still invoked.
4160 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4163 /// ActOnBlockError - If there is an error parsing a block, this callback
4164 /// is invoked to pop the information about the block from the action impl.
4165 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4167 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4168 /// literal was successfully completed. ^(int x){...}
4169 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4172 //===---------------------------- Clang Extensions ----------------------===//
4174 /// __builtin_convertvector(...)
4175 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4176 SourceLocation BuiltinLoc,
4177 SourceLocation RParenLoc);
4179 //===---------------------------- OpenCL Features -----------------------===//
4181 /// __builtin_astype(...)
4182 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4183 SourceLocation BuiltinLoc,
4184 SourceLocation RParenLoc);
4186 //===---------------------------- C++ Features --------------------------===//
4188 // Act on C++ namespaces
4189 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4190 SourceLocation NamespaceLoc,
4191 SourceLocation IdentLoc,
4192 IdentifierInfo *Ident,
4193 SourceLocation LBrace,
4194 AttributeList *AttrList,
4195 UsingDirectiveDecl * &UsingDecl);
4196 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4198 NamespaceDecl *getStdNamespace() const;
4199 NamespaceDecl *getOrCreateStdNamespace();
4201 CXXRecordDecl *getStdBadAlloc() const;
4203 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4204 /// it is and Element is not NULL, assigns the element type to Element.
4205 bool isStdInitializerList(QualType Ty, QualType *Element);
4207 /// \brief Looks for the std::initializer_list template and instantiates it
4208 /// with Element, or emits an error if it's not found.
4210 /// \returns The instantiated template, or null on error.
4211 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4213 /// \brief Determine whether Ctor is an initializer-list constructor, as
4214 /// defined in [dcl.init.list]p2.
4215 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4217 Decl *ActOnUsingDirective(Scope *CurScope,
4218 SourceLocation UsingLoc,
4219 SourceLocation NamespcLoc,
4221 SourceLocation IdentLoc,
4222 IdentifierInfo *NamespcName,
4223 AttributeList *AttrList);
4225 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4227 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4228 SourceLocation NamespaceLoc,
4229 SourceLocation AliasLoc,
4230 IdentifierInfo *Alias,
4232 SourceLocation IdentLoc,
4233 IdentifierInfo *Ident);
4235 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4236 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4237 const LookupResult &PreviousDecls,
4238 UsingShadowDecl *&PrevShadow);
4239 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4241 UsingShadowDecl *PrevDecl);
4243 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4244 bool HasTypenameKeyword,
4245 const CXXScopeSpec &SS,
4246 SourceLocation NameLoc,
4247 const LookupResult &Previous);
4248 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4249 const CXXScopeSpec &SS,
4250 const DeclarationNameInfo &NameInfo,
4251 SourceLocation NameLoc);
4253 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4254 SourceLocation UsingLoc,
4256 DeclarationNameInfo NameInfo,
4257 AttributeList *AttrList,
4258 bool IsInstantiation,
4259 bool HasTypenameKeyword,
4260 SourceLocation TypenameLoc);
4262 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4264 /// Given a derived-class using shadow declaration for a constructor and the
4265 /// correspnding base class constructor, find or create the implicit
4266 /// synthesized derived class constructor to use for this initialization.
4267 CXXConstructorDecl *
4268 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4269 ConstructorUsingShadowDecl *DerivedShadow);
4271 Decl *ActOnUsingDeclaration(Scope *CurScope,
4273 bool HasUsingKeyword,
4274 SourceLocation UsingLoc,
4276 UnqualifiedId &Name,
4277 AttributeList *AttrList,
4278 bool HasTypenameKeyword,
4279 SourceLocation TypenameLoc);
4280 Decl *ActOnAliasDeclaration(Scope *CurScope,
4282 MultiTemplateParamsArg TemplateParams,
4283 SourceLocation UsingLoc,
4284 UnqualifiedId &Name,
4285 AttributeList *AttrList,
4287 Decl *DeclFromDeclSpec);
4289 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4290 /// including handling of its default argument expressions.
4292 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4294 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4295 NamedDecl *FoundDecl,
4296 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4297 bool HadMultipleCandidates, bool IsListInitialization,
4298 bool IsStdInitListInitialization,
4299 bool RequiresZeroInit, unsigned ConstructKind,
4300 SourceRange ParenRange);
4302 /// Build a CXXConstructExpr whose constructor has already been resolved if
4303 /// it denotes an inherited constructor.
4305 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4306 CXXConstructorDecl *Constructor, bool Elidable,
4308 bool HadMultipleCandidates, bool IsListInitialization,
4309 bool IsStdInitListInitialization,
4310 bool RequiresZeroInit, unsigned ConstructKind,
4311 SourceRange ParenRange);
4313 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4314 // the constructor can be elidable?
4316 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4317 NamedDecl *FoundDecl,
4318 CXXConstructorDecl *Constructor, bool Elidable,
4319 MultiExprArg Exprs, bool HadMultipleCandidates,
4320 bool IsListInitialization,
4321 bool IsStdInitListInitialization, bool RequiresZeroInit,
4322 unsigned ConstructKind, SourceRange ParenRange);
4324 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4326 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4327 /// the default expr if needed.
4328 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4330 ParmVarDecl *Param);
4332 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4333 /// constructed variable.
4334 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4336 /// \brief Helper class that collects exception specifications for
4337 /// implicitly-declared special member functions.
4338 class ImplicitExceptionSpecification {
4339 // Pointer to allow copying
4341 // We order exception specifications thus:
4342 // noexcept is the most restrictive, but is only used in C++11.
4343 // throw() comes next.
4344 // Then a throw(collected exceptions)
4345 // Finally no specification, which is expressed as noexcept(false).
4346 // throw(...) is used instead if any called function uses it.
4347 ExceptionSpecificationType ComputedEST;
4348 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4349 SmallVector<QualType, 4> Exceptions;
4351 void ClearExceptions() {
4352 ExceptionsSeen.clear();
4357 explicit ImplicitExceptionSpecification(Sema &Self)
4358 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4359 if (!Self.getLangOpts().CPlusPlus11)
4360 ComputedEST = EST_DynamicNone;
4363 /// \brief Get the computed exception specification type.
4364 ExceptionSpecificationType getExceptionSpecType() const {
4365 assert(ComputedEST != EST_ComputedNoexcept &&
4366 "noexcept(expr) should not be a possible result");
4370 /// \brief The number of exceptions in the exception specification.
4371 unsigned size() const { return Exceptions.size(); }
4373 /// \brief The set of exceptions in the exception specification.
4374 const QualType *data() const { return Exceptions.data(); }
4376 /// \brief Integrate another called method into the collected data.
4377 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4379 /// \brief Integrate an invoked expression into the collected data.
4380 void CalledExpr(Expr *E);
4382 /// \brief Overwrite an EPI's exception specification with this
4383 /// computed exception specification.
4384 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4385 FunctionProtoType::ExceptionSpecInfo ESI;
4386 ESI.Type = getExceptionSpecType();
4387 if (ESI.Type == EST_Dynamic) {
4388 ESI.Exceptions = Exceptions;
4389 } else if (ESI.Type == EST_None) {
4390 /// C++11 [except.spec]p14:
4391 /// The exception-specification is noexcept(false) if the set of
4392 /// potential exceptions of the special member function contains "any"
4393 ESI.Type = EST_ComputedNoexcept;
4394 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4395 tok::kw_false).get();
4401 /// \brief Determine what sort of exception specification a defaulted
4402 /// copy constructor of a class will have.
4403 ImplicitExceptionSpecification
4404 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4407 /// \brief Determine what sort of exception specification a defaulted
4408 /// default constructor of a class will have, and whether the parameter
4410 ImplicitExceptionSpecification
4411 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4413 /// \brief Determine what sort of exception specification a defautled
4414 /// copy assignment operator of a class will have, and whether the
4415 /// parameter will be const.
4416 ImplicitExceptionSpecification
4417 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4419 /// \brief Determine what sort of exception specification a defaulted move
4420 /// constructor of a class will have.
4421 ImplicitExceptionSpecification
4422 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4424 /// \brief Determine what sort of exception specification a defaulted move
4425 /// assignment operator of a class will have.
4426 ImplicitExceptionSpecification
4427 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4429 /// \brief Determine what sort of exception specification a defaulted
4430 /// destructor of a class will have.
4431 ImplicitExceptionSpecification
4432 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4434 /// \brief Determine what sort of exception specification an inheriting
4435 /// constructor of a class will have.
4436 ImplicitExceptionSpecification
4437 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4438 CXXConstructorDecl *CD);
4440 /// \brief Evaluate the implicit exception specification for a defaulted
4441 /// special member function.
4442 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4444 /// \brief Check the given exception-specification and update the
4445 /// exception specification information with the results.
4446 void checkExceptionSpecification(bool IsTopLevel,
4447 ExceptionSpecificationType EST,
4448 ArrayRef<ParsedType> DynamicExceptions,
4449 ArrayRef<SourceRange> DynamicExceptionRanges,
4451 SmallVectorImpl<QualType> &Exceptions,
4452 FunctionProtoType::ExceptionSpecInfo &ESI);
4454 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4455 /// parse an exception specification to work around a libstdc++ bug.
4456 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4458 /// \brief Add an exception-specification to the given member function
4459 /// (or member function template). The exception-specification was parsed
4460 /// after the method itself was declared.
4461 void actOnDelayedExceptionSpecification(Decl *Method,
4462 ExceptionSpecificationType EST,
4463 SourceRange SpecificationRange,
4464 ArrayRef<ParsedType> DynamicExceptions,
4465 ArrayRef<SourceRange> DynamicExceptionRanges,
4466 Expr *NoexceptExpr);
4468 class InheritedConstructorInfo;
4470 /// \brief Determine if a special member function should have a deleted
4471 /// definition when it is defaulted.
4472 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4473 InheritedConstructorInfo *ICI = nullptr,
4474 bool Diagnose = false);
4476 /// \brief Declare the implicit default constructor for the given class.
4478 /// \param ClassDecl The class declaration into which the implicit
4479 /// default constructor will be added.
4481 /// \returns The implicitly-declared default constructor.
4482 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4483 CXXRecordDecl *ClassDecl);
4485 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4486 /// defining this constructor as the default constructor.
4487 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4488 CXXConstructorDecl *Constructor);
4490 /// \brief Declare the implicit destructor for the given class.
4492 /// \param ClassDecl The class declaration into which the implicit
4493 /// destructor will be added.
4495 /// \returns The implicitly-declared destructor.
4496 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4498 /// DefineImplicitDestructor - Checks for feasibility of
4499 /// defining this destructor as the default destructor.
4500 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4501 CXXDestructorDecl *Destructor);
4503 /// \brief Build an exception spec for destructors that don't have one.
4505 /// C++11 says that user-defined destructors with no exception spec get one
4506 /// that looks as if the destructor was implicitly declared.
4507 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4508 CXXDestructorDecl *Destructor);
4510 /// \brief Define the specified inheriting constructor.
4511 void DefineInheritingConstructor(SourceLocation UseLoc,
4512 CXXConstructorDecl *Constructor);
4514 /// \brief Declare the implicit copy constructor for the given class.
4516 /// \param ClassDecl The class declaration into which the implicit
4517 /// copy constructor will be added.
4519 /// \returns The implicitly-declared copy constructor.
4520 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4522 /// DefineImplicitCopyConstructor - Checks for feasibility of
4523 /// defining this constructor as the copy constructor.
4524 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4525 CXXConstructorDecl *Constructor);
4527 /// \brief Declare the implicit move constructor for the given class.
4529 /// \param ClassDecl The Class declaration into which the implicit
4530 /// move constructor will be added.
4532 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4534 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4536 /// DefineImplicitMoveConstructor - Checks for feasibility of
4537 /// defining this constructor as the move constructor.
4538 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4539 CXXConstructorDecl *Constructor);
4541 /// \brief Declare the implicit copy assignment operator for the given class.
4543 /// \param ClassDecl The class declaration into which the implicit
4544 /// copy assignment operator will be added.
4546 /// \returns The implicitly-declared copy assignment operator.
4547 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4549 /// \brief Defines an implicitly-declared copy assignment operator.
4550 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4551 CXXMethodDecl *MethodDecl);
4553 /// \brief Declare the implicit move assignment operator for the given class.
4555 /// \param ClassDecl The Class declaration into which the implicit
4556 /// move assignment operator will be added.
4558 /// \returns The implicitly-declared move assignment operator, or NULL if it
4559 /// wasn't declared.
4560 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4562 /// \brief Defines an implicitly-declared move assignment operator.
4563 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4564 CXXMethodDecl *MethodDecl);
4566 /// \brief Force the declaration of any implicitly-declared members of this
4568 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4570 /// \brief Check a completed declaration of an implicit special member.
4571 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4573 /// \brief Determine whether the given function is an implicitly-deleted
4574 /// special member function.
4575 bool isImplicitlyDeleted(FunctionDecl *FD);
4577 /// \brief Check whether 'this' shows up in the type of a static member
4578 /// function after the (naturally empty) cv-qualifier-seq would be.
4580 /// \returns true if an error occurred.
4581 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4583 /// \brief Whether this' shows up in the exception specification of a static
4584 /// member function.
4585 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4587 /// \brief Check whether 'this' shows up in the attributes of the given
4588 /// static member function.
4590 /// \returns true if an error occurred.
4591 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4593 /// MaybeBindToTemporary - If the passed in expression has a record type with
4594 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4595 /// it simply returns the passed in expression.
4596 ExprResult MaybeBindToTemporary(Expr *E);
4598 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4599 MultiExprArg ArgsPtr,
4601 SmallVectorImpl<Expr*> &ConvertedArgs,
4602 bool AllowExplicit = false,
4603 bool IsListInitialization = false);
4605 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4606 SourceLocation NameLoc,
4607 IdentifierInfo &Name);
4609 ParsedType getDestructorName(SourceLocation TildeLoc,
4610 IdentifierInfo &II, SourceLocation NameLoc,
4611 Scope *S, CXXScopeSpec &SS,
4612 ParsedType ObjectType,
4613 bool EnteringContext);
4615 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4617 // Checks that reinterpret casts don't have undefined behavior.
4618 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4619 bool IsDereference, SourceRange Range);
4621 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4622 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4623 tok::TokenKind Kind,
4624 SourceLocation LAngleBracketLoc,
4626 SourceLocation RAngleBracketLoc,
4627 SourceLocation LParenLoc,
4629 SourceLocation RParenLoc);
4631 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4632 tok::TokenKind Kind,
4635 SourceRange AngleBrackets,
4636 SourceRange Parens);
4638 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4639 SourceLocation TypeidLoc,
4640 TypeSourceInfo *Operand,
4641 SourceLocation RParenLoc);
4642 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4643 SourceLocation TypeidLoc,
4645 SourceLocation RParenLoc);
4647 /// ActOnCXXTypeid - Parse typeid( something ).
4648 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4649 SourceLocation LParenLoc, bool isType,
4651 SourceLocation RParenLoc);
4653 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4654 SourceLocation TypeidLoc,
4655 TypeSourceInfo *Operand,
4656 SourceLocation RParenLoc);
4657 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4658 SourceLocation TypeidLoc,
4660 SourceLocation RParenLoc);
4662 /// ActOnCXXUuidof - Parse __uuidof( something ).
4663 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4664 SourceLocation LParenLoc, bool isType,
4666 SourceLocation RParenLoc);
4668 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4669 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4670 tok::TokenKind Operator,
4671 SourceLocation EllipsisLoc, Expr *RHS,
4672 SourceLocation RParenLoc);
4673 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4674 BinaryOperatorKind Operator,
4675 SourceLocation EllipsisLoc, Expr *RHS,
4676 SourceLocation RParenLoc);
4677 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4678 BinaryOperatorKind Operator);
4680 //// ActOnCXXThis - Parse 'this' pointer.
4681 ExprResult ActOnCXXThis(SourceLocation loc);
4683 /// \brief Try to retrieve the type of the 'this' pointer.
4685 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4686 QualType getCurrentThisType();
4688 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4689 /// current context not being a non-static member function. In such cases,
4690 /// this provides the type used for 'this'.
4691 QualType CXXThisTypeOverride;
4693 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4694 /// to be used, with the given qualifiers on the current class type.
4695 class CXXThisScopeRAII {
4697 QualType OldCXXThisTypeOverride;
4701 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4702 /// using the given declaration (which is either a class template or a
4703 /// class) along with the given qualifiers.
4704 /// along with the qualifiers placed on '*this'.
4705 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4706 bool Enabled = true);
4708 ~CXXThisScopeRAII();
4711 /// \brief Make sure the value of 'this' is actually available in the current
4712 /// context, if it is a potentially evaluated context.
4714 /// \param Loc The location at which the capture of 'this' occurs.
4716 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4719 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4720 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4721 /// This is useful when enclosing lambdas must speculatively capture
4722 /// 'this' that may or may not be used in certain specializations of
4723 /// a nested generic lambda (depending on whether the name resolves to
4724 /// a non-static member function or a static function).
4725 /// \return returns 'true' if failed, 'false' if success.
4726 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4727 bool BuildAndDiagnose = true,
4728 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4729 bool ByCopy = false);
4731 /// \brief Determine whether the given type is the type of *this that is used
4732 /// outside of the body of a member function for a type that is currently
4734 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4736 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4737 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4740 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4741 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4744 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4745 SourceLocation AtLoc, SourceLocation RParen);
4747 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4748 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4750 //// ActOnCXXThrow - Parse throw expressions.
4751 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4752 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4753 bool IsThrownVarInScope);
4754 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4756 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4757 /// Can be interpreted either as function-style casting ("int(x)")
4758 /// or class type construction ("ClassType(x,y,z)")
4759 /// or creation of a value-initialized type ("int()").
4760 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4761 SourceLocation LParenLoc,
4763 SourceLocation RParenLoc);
4765 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4766 SourceLocation LParenLoc,
4768 SourceLocation RParenLoc);
4770 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4771 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4772 SourceLocation PlacementLParen,
4773 MultiExprArg PlacementArgs,
4774 SourceLocation PlacementRParen,
4775 SourceRange TypeIdParens, Declarator &D,
4777 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4778 SourceLocation PlacementLParen,
4779 MultiExprArg PlacementArgs,
4780 SourceLocation PlacementRParen,
4781 SourceRange TypeIdParens,
4783 TypeSourceInfo *AllocTypeInfo,
4785 SourceRange DirectInitRange,
4787 bool TypeMayContainAuto = true);
4789 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4791 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4792 bool UseGlobal, QualType AllocType, bool IsArray,
4793 MultiExprArg PlaceArgs,
4794 FunctionDecl *&OperatorNew,
4795 FunctionDecl *&OperatorDelete);
4796 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4797 DeclarationName Name, MultiExprArg Args,
4799 bool AllowMissing, FunctionDecl *&Operator,
4800 bool Diagnose = true);
4801 void DeclareGlobalNewDelete();
4802 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4804 QualType Param2 = QualType());
4806 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4807 DeclarationName Name, FunctionDecl* &Operator,
4808 bool Diagnose = true);
4809 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4810 bool CanProvideSize,
4811 DeclarationName Name);
4813 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4814 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4815 bool UseGlobal, bool ArrayForm,
4817 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4818 bool IsDelete, bool CallCanBeVirtual,
4819 bool WarnOnNonAbstractTypes,
4820 SourceLocation DtorLoc);
4822 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4823 Expr *Operand, SourceLocation RParen);
4824 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4825 SourceLocation RParen);
4827 /// \brief Parsed one of the type trait support pseudo-functions.
4828 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4829 ArrayRef<ParsedType> Args,
4830 SourceLocation RParenLoc);
4831 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4832 ArrayRef<TypeSourceInfo *> Args,
4833 SourceLocation RParenLoc);
4835 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4836 /// pseudo-functions.
4837 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4838 SourceLocation KWLoc,
4841 SourceLocation RParen);
4843 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4844 SourceLocation KWLoc,
4845 TypeSourceInfo *TSInfo,
4847 SourceLocation RParen);
4849 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4850 /// pseudo-functions.
4851 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4852 SourceLocation KWLoc,
4854 SourceLocation RParen);
4856 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4857 SourceLocation KWLoc,
4859 SourceLocation RParen);
4861 ExprResult ActOnStartCXXMemberReference(Scope *S,
4863 SourceLocation OpLoc,
4864 tok::TokenKind OpKind,
4865 ParsedType &ObjectType,
4866 bool &MayBePseudoDestructor);
4868 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4869 SourceLocation OpLoc,
4870 tok::TokenKind OpKind,
4871 const CXXScopeSpec &SS,
4872 TypeSourceInfo *ScopeType,
4873 SourceLocation CCLoc,
4874 SourceLocation TildeLoc,
4875 PseudoDestructorTypeStorage DestroyedType);
4877 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4878 SourceLocation OpLoc,
4879 tok::TokenKind OpKind,
4881 UnqualifiedId &FirstTypeName,
4882 SourceLocation CCLoc,
4883 SourceLocation TildeLoc,
4884 UnqualifiedId &SecondTypeName);
4886 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4887 SourceLocation OpLoc,
4888 tok::TokenKind OpKind,
4889 SourceLocation TildeLoc,
4890 const DeclSpec& DS);
4892 /// MaybeCreateExprWithCleanups - If the current full-expression
4893 /// requires any cleanups, surround it with a ExprWithCleanups node.
4894 /// Otherwise, just returns the passed-in expression.
4895 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4896 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4897 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4899 MaterializeTemporaryExpr *
4900 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
4901 bool BoundToLvalueReference);
4903 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4904 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4905 : SourceLocation());
4907 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4908 bool DiscardedValue = false,
4909 bool IsConstexpr = false,
4910 bool IsLambdaInitCaptureInitializer = false);
4911 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4913 // Marks SS invalid if it represents an incomplete type.
4914 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4916 DeclContext *computeDeclContext(QualType T);
4917 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4918 bool EnteringContext = false);
4919 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4920 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4922 /// \brief The parser has parsed a global nested-name-specifier '::'.
4924 /// \param CCLoc The location of the '::'.
4926 /// \param SS The nested-name-specifier, which will be updated in-place
4927 /// to reflect the parsed nested-name-specifier.
4929 /// \returns true if an error occurred, false otherwise.
4930 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4932 /// \brief The parser has parsed a '__super' nested-name-specifier.
4934 /// \param SuperLoc The location of the '__super' keyword.
4936 /// \param ColonColonLoc The location of the '::'.
4938 /// \param SS The nested-name-specifier, which will be updated in-place
4939 /// to reflect the parsed nested-name-specifier.
4941 /// \returns true if an error occurred, false otherwise.
4942 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4943 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4945 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
4946 bool *CanCorrect = nullptr);
4947 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4949 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4950 SourceLocation IdLoc,
4952 ParsedType ObjectType);
4954 bool BuildCXXNestedNameSpecifier(Scope *S,
4955 IdentifierInfo &Identifier,
4956 SourceLocation IdentifierLoc,
4957 SourceLocation CCLoc,
4958 QualType ObjectType,
4959 bool EnteringContext,
4961 NamedDecl *ScopeLookupResult,
4962 bool ErrorRecoveryLookup,
4963 bool *IsCorrectedToColon = nullptr);
4965 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4967 /// \param S The scope in which this nested-name-specifier occurs.
4969 /// \param Identifier The identifier preceding the '::'.
4971 /// \param IdentifierLoc The location of the identifier.
4973 /// \param CCLoc The location of the '::'.
4975 /// \param ObjectType The type of the object, if we're parsing
4976 /// nested-name-specifier in a member access expression.
4978 /// \param EnteringContext Whether we're entering the context nominated by
4979 /// this nested-name-specifier.
4981 /// \param SS The nested-name-specifier, which is both an input
4982 /// parameter (the nested-name-specifier before this type) and an
4983 /// output parameter (containing the full nested-name-specifier,
4984 /// including this new type).
4986 /// \param ErrorRecoveryLookup If true, then this method is called to improve
4987 /// error recovery. In this case do not emit error message.
4989 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4990 /// are allowed. The bool value pointed by this parameter is set to 'true'
4991 /// if the identifier is treated as if it was followed by ':', not '::'.
4993 /// \returns true if an error occurred, false otherwise.
4994 bool ActOnCXXNestedNameSpecifier(Scope *S,
4995 IdentifierInfo &Identifier,
4996 SourceLocation IdentifierLoc,
4997 SourceLocation CCLoc,
4998 ParsedType ObjectType,
4999 bool EnteringContext,
5001 bool ErrorRecoveryLookup = false,
5002 bool *IsCorrectedToColon = nullptr);
5004 ExprResult ActOnDecltypeExpression(Expr *E);
5006 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5008 SourceLocation ColonColonLoc);
5010 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5011 IdentifierInfo &Identifier,
5012 SourceLocation IdentifierLoc,
5013 SourceLocation ColonLoc,
5014 ParsedType ObjectType,
5015 bool EnteringContext);
5017 /// \brief The parser has parsed a nested-name-specifier
5018 /// 'template[opt] template-name < template-args >::'.
5020 /// \param S The scope in which this nested-name-specifier occurs.
5022 /// \param SS The nested-name-specifier, which is both an input
5023 /// parameter (the nested-name-specifier before this type) and an
5024 /// output parameter (containing the full nested-name-specifier,
5025 /// including this new type).
5027 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5028 /// \param TemplateName the template name.
5029 /// \param TemplateNameLoc The location of the template name.
5030 /// \param LAngleLoc The location of the opening angle bracket ('<').
5031 /// \param TemplateArgs The template arguments.
5032 /// \param RAngleLoc The location of the closing angle bracket ('>').
5033 /// \param CCLoc The location of the '::'.
5035 /// \param EnteringContext Whether we're entering the context of the
5036 /// nested-name-specifier.
5039 /// \returns true if an error occurred, false otherwise.
5040 bool ActOnCXXNestedNameSpecifier(Scope *S,
5042 SourceLocation TemplateKWLoc,
5043 TemplateTy TemplateName,
5044 SourceLocation TemplateNameLoc,
5045 SourceLocation LAngleLoc,
5046 ASTTemplateArgsPtr TemplateArgs,
5047 SourceLocation RAngleLoc,
5048 SourceLocation CCLoc,
5049 bool EnteringContext);
5051 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5052 /// that the parser can use later to reconstruct the given
5053 /// nested-name-specifier.
5055 /// \param SS A nested-name-specifier.
5057 /// \returns A pointer containing all of the information in the
5058 /// nested-name-specifier \p SS.
5059 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5061 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5062 /// the nested-name-specifier structure.
5064 /// \param Annotation The annotation pointer, produced by
5065 /// \c SaveNestedNameSpecifierAnnotation().
5067 /// \param AnnotationRange The source range corresponding to the annotation.
5069 /// \param SS The nested-name-specifier that will be updated with the contents
5070 /// of the annotation pointer.
5071 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5072 SourceRange AnnotationRange,
5075 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5077 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5078 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5079 /// After this method is called, according to [C++ 3.4.3p3], names should be
5080 /// looked up in the declarator-id's scope, until the declarator is parsed and
5081 /// ActOnCXXExitDeclaratorScope is called.
5082 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5083 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5085 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5086 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5087 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5088 /// Used to indicate that names should revert to being looked up in the
5090 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5092 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5093 /// initializer for the declaration 'Dcl'.
5094 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5095 /// static data member of class X, names should be looked up in the scope of
5097 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5099 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5100 /// initializer for the declaration 'Dcl'.
5101 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5103 /// \brief Create a new lambda closure type.
5104 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5105 TypeSourceInfo *Info,
5106 bool KnownDependent,
5107 LambdaCaptureDefault CaptureDefault);
5109 /// \brief Start the definition of a lambda expression.
5110 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5111 SourceRange IntroducerRange,
5112 TypeSourceInfo *MethodType,
5113 SourceLocation EndLoc,
5114 ArrayRef<ParmVarDecl *> Params);
5116 /// \brief Endow the lambda scope info with the relevant properties.
5117 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5118 CXXMethodDecl *CallOperator,
5119 SourceRange IntroducerRange,
5120 LambdaCaptureDefault CaptureDefault,
5121 SourceLocation CaptureDefaultLoc,
5122 bool ExplicitParams,
5123 bool ExplicitResultType,
5126 /// \brief Perform initialization analysis of the init-capture and perform
5127 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5128 /// not being used to initialize a reference.
5129 ParsedType actOnLambdaInitCaptureInitialization(
5130 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5131 LambdaCaptureInitKind InitKind, Expr *&Init) {
5132 return ParsedType::make(buildLambdaInitCaptureInitialization(
5133 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5135 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5137 bool DirectInit, Expr *&Init);
5139 /// \brief Create a dummy variable within the declcontext of the lambda's
5140 /// call operator, for name lookup purposes for a lambda init capture.
5142 /// CodeGen handles emission of lambda captures, ignoring these dummy
5143 /// variables appropriately.
5144 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5145 QualType InitCaptureType,
5147 unsigned InitStyle, Expr *Init);
5149 /// \brief Build the implicit field for an init-capture.
5150 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5152 /// \brief Note that we have finished the explicit captures for the
5154 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5156 /// \brief Introduce the lambda parameters into scope.
5157 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5159 /// \brief Deduce a block or lambda's return type based on the return
5160 /// statements present in the body.
5161 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5163 /// ActOnStartOfLambdaDefinition - This is called just before we start
5164 /// parsing the body of a lambda; it analyzes the explicit captures and
5165 /// arguments, and sets up various data-structures for the body of the
5167 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5168 Declarator &ParamInfo, Scope *CurScope);
5170 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5171 /// is invoked to pop the information about the lambda.
5172 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5173 bool IsInstantiation = false);
5175 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5176 /// was successfully completed.
5177 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5180 /// \brief Complete a lambda-expression having processed and attached the
5182 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5183 sema::LambdaScopeInfo *LSI);
5185 /// \brief Define the "body" of the conversion from a lambda object to a
5186 /// function pointer.
5188 /// This routine doesn't actually define a sensible body; rather, it fills
5189 /// in the initialization expression needed to copy the lambda object into
5190 /// the block, and IR generation actually generates the real body of the
5191 /// block pointer conversion.
5192 void DefineImplicitLambdaToFunctionPointerConversion(
5193 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5195 /// \brief Define the "body" of the conversion from a lambda object to a
5198 /// This routine doesn't actually define a sensible body; rather, it fills
5199 /// in the initialization expression needed to copy the lambda object into
5200 /// the block, and IR generation actually generates the real body of the
5201 /// block pointer conversion.
5202 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5203 CXXConversionDecl *Conv);
5205 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5206 SourceLocation ConvLocation,
5207 CXXConversionDecl *Conv,
5210 // ParseObjCStringLiteral - Parse Objective-C string literals.
5211 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5212 ArrayRef<Expr *> Strings);
5214 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5216 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5217 /// numeric literal expression. Type of the expression will be "NSNumber *"
5218 /// or "id" if NSNumber is unavailable.
5219 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5220 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5222 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5224 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5225 /// '@' prefixed parenthesized expression. The type of the expression will
5226 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5227 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5228 /// "const char *" or C structure with attribute 'objc_boxable'.
5229 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5231 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5233 ObjCMethodDecl *getterMethod,
5234 ObjCMethodDecl *setterMethod);
5236 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5237 MutableArrayRef<ObjCDictionaryElement> Elements);
5239 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5240 TypeSourceInfo *EncodedTypeInfo,
5241 SourceLocation RParenLoc);
5242 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5243 CXXConversionDecl *Method,
5244 bool HadMultipleCandidates);
5246 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5247 SourceLocation EncodeLoc,
5248 SourceLocation LParenLoc,
5250 SourceLocation RParenLoc);
5252 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5253 ExprResult ParseObjCSelectorExpression(Selector Sel,
5254 SourceLocation AtLoc,
5255 SourceLocation SelLoc,
5256 SourceLocation LParenLoc,
5257 SourceLocation RParenLoc,
5258 bool WarnMultipleSelectors);
5260 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5261 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5262 SourceLocation AtLoc,
5263 SourceLocation ProtoLoc,
5264 SourceLocation LParenLoc,
5265 SourceLocation ProtoIdLoc,
5266 SourceLocation RParenLoc);
5268 //===--------------------------------------------------------------------===//
5271 Decl *ActOnStartLinkageSpecification(Scope *S,
5272 SourceLocation ExternLoc,
5274 SourceLocation LBraceLoc);
5275 Decl *ActOnFinishLinkageSpecification(Scope *S,
5277 SourceLocation RBraceLoc);
5280 //===--------------------------------------------------------------------===//
5283 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5284 const CXXScopeSpec *SS = nullptr);
5285 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5287 bool ActOnAccessSpecifier(AccessSpecifier Access,
5288 SourceLocation ASLoc,
5289 SourceLocation ColonLoc,
5290 AttributeList *Attrs = nullptr);
5292 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5294 MultiTemplateParamsArg TemplateParameterLists,
5295 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5296 InClassInitStyle InitStyle);
5298 void ActOnStartCXXInClassMemberInitializer();
5299 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5300 SourceLocation EqualLoc,
5303 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5306 IdentifierInfo *MemberOrBase,
5307 ParsedType TemplateTypeTy,
5309 SourceLocation IdLoc,
5310 SourceLocation LParenLoc,
5311 ArrayRef<Expr *> Args,
5312 SourceLocation RParenLoc,
5313 SourceLocation EllipsisLoc);
5315 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5318 IdentifierInfo *MemberOrBase,
5319 ParsedType TemplateTypeTy,
5321 SourceLocation IdLoc,
5323 SourceLocation EllipsisLoc);
5325 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5328 IdentifierInfo *MemberOrBase,
5329 ParsedType TemplateTypeTy,
5331 SourceLocation IdLoc,
5333 SourceLocation EllipsisLoc);
5335 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5337 SourceLocation IdLoc);
5339 MemInitResult BuildBaseInitializer(QualType BaseType,
5340 TypeSourceInfo *BaseTInfo,
5342 CXXRecordDecl *ClassDecl,
5343 SourceLocation EllipsisLoc);
5345 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5347 CXXRecordDecl *ClassDecl);
5349 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5350 CXXCtorInitializer *Initializer);
5352 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5353 ArrayRef<CXXCtorInitializer *> Initializers = None);
5355 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5358 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5359 /// mark all the non-trivial destructors of its members and bases as
5361 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5362 CXXRecordDecl *Record);
5364 /// \brief The list of classes whose vtables have been used within
5365 /// this translation unit, and the source locations at which the
5366 /// first use occurred.
5367 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5369 /// \brief The list of vtables that are required but have not yet been
5371 SmallVector<VTableUse, 16> VTableUses;
5373 /// \brief The set of classes whose vtables have been used within
5374 /// this translation unit, and a bit that will be true if the vtable is
5375 /// required to be emitted (otherwise, it should be emitted only if needed
5376 /// by code generation).
5377 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5379 /// \brief Load any externally-stored vtable uses.
5380 void LoadExternalVTableUses();
5382 /// \brief Note that the vtable for the given class was used at the
5384 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5385 bool DefinitionRequired = false);
5387 /// \brief Mark the exception specifications of all virtual member functions
5388 /// in the given class as needed.
5389 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5390 const CXXRecordDecl *RD);
5392 /// MarkVirtualMembersReferenced - Will mark all members of the given
5393 /// CXXRecordDecl referenced.
5394 void MarkVirtualMembersReferenced(SourceLocation Loc,
5395 const CXXRecordDecl *RD);
5397 /// \brief Define all of the vtables that have been used in this
5398 /// translation unit and reference any virtual members used by those
5401 /// \returns true if any work was done, false otherwise.
5402 bool DefineUsedVTables();
5404 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5406 void ActOnMemInitializers(Decl *ConstructorDecl,
5407 SourceLocation ColonLoc,
5408 ArrayRef<CXXCtorInitializer*> MemInits,
5411 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5412 /// ensure that referenceDLLExportedClassMethods is called some point later
5413 /// when all outer classes of Class are complete.
5414 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5416 void referenceDLLExportedClassMethods();
5418 void propagateDLLAttrToBaseClassTemplate(
5419 CXXRecordDecl *Class, Attr *ClassAttr,
5420 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5421 SourceLocation BaseLoc);
5423 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5424 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5426 SourceLocation LBrac,
5427 SourceLocation RBrac,
5428 AttributeList *AttrList);
5429 void ActOnFinishCXXMemberDecls();
5430 void ActOnFinishCXXNonNestedClass(Decl *D);
5432 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5433 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5434 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5435 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5436 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5437 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5438 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5439 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5440 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5441 CachedTokens &Toks);
5442 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5443 bool IsInsideALocalClassWithinATemplateFunction();
5445 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5447 Expr *AssertMessageExpr,
5448 SourceLocation RParenLoc);
5449 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5451 StringLiteral *AssertMessageExpr,
5452 SourceLocation RParenLoc,
5455 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5456 SourceLocation FriendLoc,
5457 TypeSourceInfo *TSInfo);
5458 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5459 MultiTemplateParamsArg TemplateParams);
5460 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5461 MultiTemplateParamsArg TemplateParams);
5463 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5465 void CheckConstructor(CXXConstructorDecl *Constructor);
5466 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5468 bool CheckDestructor(CXXDestructorDecl *Destructor);
5469 void CheckConversionDeclarator(Declarator &D, QualType &R,
5471 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5473 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5474 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5475 const FunctionProtoType *T);
5476 void CheckDelayedMemberExceptionSpecs();
5478 //===--------------------------------------------------------------------===//
5479 // C++ Derived Classes
5482 /// ActOnBaseSpecifier - Parsed a base specifier
5483 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5484 SourceRange SpecifierRange,
5485 bool Virtual, AccessSpecifier Access,
5486 TypeSourceInfo *TInfo,
5487 SourceLocation EllipsisLoc);
5489 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5490 SourceRange SpecifierRange,
5491 ParsedAttributes &Attrs,
5492 bool Virtual, AccessSpecifier Access,
5493 ParsedType basetype,
5494 SourceLocation BaseLoc,
5495 SourceLocation EllipsisLoc);
5497 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5498 MutableArrayRef<CXXBaseSpecifier *> Bases);
5499 void ActOnBaseSpecifiers(Decl *ClassDecl,
5500 MutableArrayRef<CXXBaseSpecifier *> Bases);
5502 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5503 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5504 CXXBasePaths &Paths);
5506 // FIXME: I don't like this name.
5507 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5509 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5510 SourceLocation Loc, SourceRange Range,
5511 CXXCastPath *BasePath = nullptr,
5512 bool IgnoreAccess = false);
5513 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5514 unsigned InaccessibleBaseID,
5515 unsigned AmbigiousBaseConvID,
5516 SourceLocation Loc, SourceRange Range,
5517 DeclarationName Name,
5518 CXXCastPath *BasePath,
5519 bool IgnoreAccess = false);
5521 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5523 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5524 const CXXMethodDecl *Old);
5526 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5527 /// covariant, according to C++ [class.virtual]p5.
5528 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5529 const CXXMethodDecl *Old);
5531 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5532 /// spec is a subset of base spec.
5533 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5534 const CXXMethodDecl *Old);
5536 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5538 /// CheckOverrideControl - Check C++11 override control semantics.
5539 void CheckOverrideControl(NamedDecl *D);
5541 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5542 /// not used in the declaration of an overriding method.
5543 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5545 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5546 /// overrides a virtual member function marked 'final', according to
5547 /// C++11 [class.virtual]p4.
5548 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5549 const CXXMethodDecl *Old);
5552 //===--------------------------------------------------------------------===//
5553 // C++ Access Control
5563 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5564 NamedDecl *PrevMemberDecl,
5565 AccessSpecifier LexicalAS);
5567 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5568 DeclAccessPair FoundDecl);
5569 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5570 DeclAccessPair FoundDecl);
5571 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5572 SourceRange PlacementRange,
5573 CXXRecordDecl *NamingClass,
5574 DeclAccessPair FoundDecl,
5575 bool Diagnose = true);
5576 AccessResult CheckConstructorAccess(SourceLocation Loc,
5577 CXXConstructorDecl *D,
5578 DeclAccessPair FoundDecl,
5579 const InitializedEntity &Entity,
5580 bool IsCopyBindingRefToTemp = false);
5581 AccessResult CheckConstructorAccess(SourceLocation Loc,
5582 CXXConstructorDecl *D,
5583 DeclAccessPair FoundDecl,
5584 const InitializedEntity &Entity,
5585 const PartialDiagnostic &PDiag);
5586 AccessResult CheckDestructorAccess(SourceLocation Loc,
5587 CXXDestructorDecl *Dtor,
5588 const PartialDiagnostic &PDiag,
5589 QualType objectType = QualType());
5590 AccessResult CheckFriendAccess(NamedDecl *D);
5591 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5592 CXXRecordDecl *NamingClass,
5593 DeclAccessPair Found);
5594 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5597 DeclAccessPair FoundDecl);
5598 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5599 DeclAccessPair FoundDecl);
5600 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5601 QualType Base, QualType Derived,
5602 const CXXBasePath &Path,
5604 bool ForceCheck = false,
5605 bool ForceUnprivileged = false);
5606 void CheckLookupAccess(const LookupResult &R);
5607 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5608 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5609 AccessSpecifier access,
5610 QualType objectType);
5612 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5613 const MultiLevelTemplateArgumentList &TemplateArgs);
5614 void PerformDependentDiagnostics(const DeclContext *Pattern,
5615 const MultiLevelTemplateArgumentList &TemplateArgs);
5617 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5619 /// \brief When true, access checking violations are treated as SFINAE
5620 /// failures rather than hard errors.
5621 bool AccessCheckingSFINAE;
5623 enum AbstractDiagSelID {
5627 AbstractVariableType,
5630 AbstractSynthesizedIvarType,
5634 bool isAbstractType(SourceLocation Loc, QualType T);
5635 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5636 TypeDiagnoser &Diagnoser);
5637 template <typename... Ts>
5638 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5639 const Ts &...Args) {
5640 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5641 return RequireNonAbstractType(Loc, T, Diagnoser);
5644 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5646 //===--------------------------------------------------------------------===//
5647 // C++ Overloaded Operators [C++ 13.5]
5650 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5652 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5654 //===--------------------------------------------------------------------===//
5655 // C++ Templates [C++ 14]
5657 void FilterAcceptableTemplateNames(LookupResult &R,
5658 bool AllowFunctionTemplates = true);
5659 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5660 bool AllowFunctionTemplates = true);
5662 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5663 QualType ObjectType, bool EnteringContext,
5664 bool &MemberOfUnknownSpecialization);
5666 TemplateNameKind isTemplateName(Scope *S,
5668 bool hasTemplateKeyword,
5669 UnqualifiedId &Name,
5670 ParsedType ObjectType,
5671 bool EnteringContext,
5672 TemplateTy &Template,
5673 bool &MemberOfUnknownSpecialization);
5675 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5676 SourceLocation IILoc,
5678 const CXXScopeSpec *SS,
5679 TemplateTy &SuggestedTemplate,
5680 TemplateNameKind &SuggestedKind);
5682 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5683 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5685 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5686 SourceLocation EllipsisLoc,
5687 SourceLocation KeyLoc,
5688 IdentifierInfo *ParamName,
5689 SourceLocation ParamNameLoc,
5690 unsigned Depth, unsigned Position,
5691 SourceLocation EqualLoc,
5692 ParsedType DefaultArg);
5694 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5695 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5698 SourceLocation EqualLoc,
5700 Decl *ActOnTemplateTemplateParameter(Scope *S,
5701 SourceLocation TmpLoc,
5702 TemplateParameterList *Params,
5703 SourceLocation EllipsisLoc,
5704 IdentifierInfo *ParamName,
5705 SourceLocation ParamNameLoc,
5708 SourceLocation EqualLoc,
5709 ParsedTemplateArgument DefaultArg);
5711 TemplateParameterList *
5712 ActOnTemplateParameterList(unsigned Depth,
5713 SourceLocation ExportLoc,
5714 SourceLocation TemplateLoc,
5715 SourceLocation LAngleLoc,
5716 ArrayRef<Decl *> Params,
5717 SourceLocation RAngleLoc,
5718 Expr *RequiresClause);
5720 /// \brief The context in which we are checking a template parameter list.
5721 enum TemplateParamListContext {
5724 TPC_FunctionTemplate,
5725 TPC_ClassTemplateMember,
5726 TPC_FriendClassTemplate,
5727 TPC_FriendFunctionTemplate,
5728 TPC_FriendFunctionTemplateDefinition,
5729 TPC_TypeAliasTemplate
5732 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5733 TemplateParameterList *OldParams,
5734 TemplateParamListContext TPC);
5735 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5736 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5737 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5738 ArrayRef<TemplateParameterList *> ParamLists,
5739 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5741 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5742 SourceLocation KWLoc, CXXScopeSpec &SS,
5743 IdentifierInfo *Name, SourceLocation NameLoc,
5744 AttributeList *Attr,
5745 TemplateParameterList *TemplateParams,
5747 SourceLocation ModulePrivateLoc,
5748 SourceLocation FriendLoc,
5749 unsigned NumOuterTemplateParamLists,
5750 TemplateParameterList **OuterTemplateParamLists,
5751 SkipBodyInfo *SkipBody = nullptr);
5753 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5754 TemplateArgumentListInfo &Out);
5756 void NoteAllFoundTemplates(TemplateName Name);
5758 QualType CheckTemplateIdType(TemplateName Template,
5759 SourceLocation TemplateLoc,
5760 TemplateArgumentListInfo &TemplateArgs);
5763 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5764 TemplateTy Template, SourceLocation TemplateLoc,
5765 SourceLocation LAngleLoc,
5766 ASTTemplateArgsPtr TemplateArgs,
5767 SourceLocation RAngleLoc,
5768 bool IsCtorOrDtorName = false);
5770 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5771 /// such as \c class T::template apply<U>.
5772 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5773 TypeSpecifierType TagSpec,
5774 SourceLocation TagLoc,
5776 SourceLocation TemplateKWLoc,
5777 TemplateTy TemplateD,
5778 SourceLocation TemplateLoc,
5779 SourceLocation LAngleLoc,
5780 ASTTemplateArgsPtr TemplateArgsIn,
5781 SourceLocation RAngleLoc);
5783 DeclResult ActOnVarTemplateSpecialization(
5784 Scope *S, Declarator &D, TypeSourceInfo *DI,
5785 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5786 StorageClass SC, bool IsPartialSpecialization);
5788 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5789 SourceLocation TemplateLoc,
5790 SourceLocation TemplateNameLoc,
5791 const TemplateArgumentListInfo &TemplateArgs);
5793 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5794 const DeclarationNameInfo &NameInfo,
5795 VarTemplateDecl *Template,
5796 SourceLocation TemplateLoc,
5797 const TemplateArgumentListInfo *TemplateArgs);
5799 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5800 SourceLocation TemplateKWLoc,
5803 const TemplateArgumentListInfo *TemplateArgs);
5805 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5806 SourceLocation TemplateKWLoc,
5807 const DeclarationNameInfo &NameInfo,
5808 const TemplateArgumentListInfo *TemplateArgs);
5810 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5812 SourceLocation TemplateKWLoc,
5813 UnqualifiedId &Name,
5814 ParsedType ObjectType,
5815 bool EnteringContext,
5816 TemplateTy &Template);
5819 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5820 SourceLocation KWLoc,
5821 SourceLocation ModulePrivateLoc,
5822 TemplateIdAnnotation &TemplateId,
5823 AttributeList *Attr,
5824 MultiTemplateParamsArg TemplateParameterLists,
5825 SkipBodyInfo *SkipBody = nullptr);
5827 Decl *ActOnTemplateDeclarator(Scope *S,
5828 MultiTemplateParamsArg TemplateParameterLists,
5832 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5833 TemplateSpecializationKind NewTSK,
5834 NamedDecl *PrevDecl,
5835 TemplateSpecializationKind PrevTSK,
5836 SourceLocation PrevPtOfInstantiation,
5839 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5840 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5841 LookupResult &Previous);
5843 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5844 TemplateArgumentListInfo *ExplicitTemplateArgs,
5845 LookupResult &Previous);
5846 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5849 ActOnExplicitInstantiation(Scope *S,
5850 SourceLocation ExternLoc,
5851 SourceLocation TemplateLoc,
5853 SourceLocation KWLoc,
5854 const CXXScopeSpec &SS,
5855 TemplateTy Template,
5856 SourceLocation TemplateNameLoc,
5857 SourceLocation LAngleLoc,
5858 ASTTemplateArgsPtr TemplateArgs,
5859 SourceLocation RAngleLoc,
5860 AttributeList *Attr);
5863 ActOnExplicitInstantiation(Scope *S,
5864 SourceLocation ExternLoc,
5865 SourceLocation TemplateLoc,
5867 SourceLocation KWLoc,
5869 IdentifierInfo *Name,
5870 SourceLocation NameLoc,
5871 AttributeList *Attr);
5873 DeclResult ActOnExplicitInstantiation(Scope *S,
5874 SourceLocation ExternLoc,
5875 SourceLocation TemplateLoc,
5879 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5880 SourceLocation TemplateLoc,
5881 SourceLocation RAngleLoc,
5883 SmallVectorImpl<TemplateArgument>
5885 bool &HasDefaultArg);
5887 /// \brief Specifies the context in which a particular template
5888 /// argument is being checked.
5889 enum CheckTemplateArgumentKind {
5890 /// \brief The template argument was specified in the code or was
5891 /// instantiated with some deduced template arguments.
5894 /// \brief The template argument was deduced via template argument
5898 /// \brief The template argument was deduced from an array bound
5899 /// via template argument deduction.
5900 CTAK_DeducedFromArrayBound
5903 bool CheckTemplateArgument(NamedDecl *Param,
5904 TemplateArgumentLoc &Arg,
5905 NamedDecl *Template,
5906 SourceLocation TemplateLoc,
5907 SourceLocation RAngleLoc,
5908 unsigned ArgumentPackIndex,
5909 SmallVectorImpl<TemplateArgument> &Converted,
5910 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5912 /// \brief Check that the given template arguments can be be provided to
5913 /// the given template, converting the arguments along the way.
5915 /// \param Template The template to which the template arguments are being
5918 /// \param TemplateLoc The location of the template name in the source.
5920 /// \param TemplateArgs The list of template arguments. If the template is
5921 /// a template template parameter, this function may extend the set of
5922 /// template arguments to also include substituted, defaulted template
5925 /// \param PartialTemplateArgs True if the list of template arguments is
5926 /// intentionally partial, e.g., because we're checking just the initial
5927 /// set of template arguments.
5929 /// \param Converted Will receive the converted, canonicalized template
5932 /// \returns true if an error occurred, false otherwise.
5933 bool CheckTemplateArgumentList(TemplateDecl *Template,
5934 SourceLocation TemplateLoc,
5935 TemplateArgumentListInfo &TemplateArgs,
5936 bool PartialTemplateArgs,
5937 SmallVectorImpl<TemplateArgument> &Converted);
5939 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5940 TemplateArgumentLoc &Arg,
5941 SmallVectorImpl<TemplateArgument> &Converted);
5943 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5944 TypeSourceInfo *Arg);
5945 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5946 QualType InstantiatedParamType, Expr *Arg,
5947 TemplateArgument &Converted,
5948 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5949 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5950 TemplateArgumentLoc &Arg,
5951 unsigned ArgumentPackIndex);
5954 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5956 SourceLocation Loc);
5958 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5959 SourceLocation Loc);
5961 /// \brief Enumeration describing how template parameter lists are compared
5963 enum TemplateParameterListEqualKind {
5964 /// \brief We are matching the template parameter lists of two templates
5965 /// that might be redeclarations.
5968 /// template<typename T> struct X;
5969 /// template<typename T> struct X;
5973 /// \brief We are matching the template parameter lists of two template
5974 /// template parameters as part of matching the template parameter lists
5975 /// of two templates that might be redeclarations.
5978 /// template<template<int I> class TT> struct X;
5979 /// template<template<int Value> class Other> struct X;
5981 TPL_TemplateTemplateParmMatch,
5983 /// \brief We are matching the template parameter lists of a template
5984 /// template argument against the template parameter lists of a template
5985 /// template parameter.
5988 /// template<template<int Value> class Metafun> struct X;
5989 /// template<int Value> struct integer_c;
5990 /// X<integer_c> xic;
5992 TPL_TemplateTemplateArgumentMatch
5995 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5996 TemplateParameterList *Old,
5998 TemplateParameterListEqualKind Kind,
5999 SourceLocation TemplateArgLoc
6000 = SourceLocation());
6002 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6004 /// \brief Called when the parser has parsed a C++ typename
6005 /// specifier, e.g., "typename T::type".
6007 /// \param S The scope in which this typename type occurs.
6008 /// \param TypenameLoc the location of the 'typename' keyword
6009 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6010 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6011 /// \param IdLoc the location of the identifier.
6013 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6014 const CXXScopeSpec &SS, const IdentifierInfo &II,
6015 SourceLocation IdLoc);
6017 /// \brief Called when the parser has parsed a C++ typename
6018 /// specifier that ends in a template-id, e.g.,
6019 /// "typename MetaFun::template apply<T1, T2>".
6021 /// \param S The scope in which this typename type occurs.
6022 /// \param TypenameLoc the location of the 'typename' keyword
6023 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6024 /// \param TemplateLoc the location of the 'template' keyword, if any.
6025 /// \param TemplateName The template name.
6026 /// \param TemplateNameLoc The location of the template name.
6027 /// \param LAngleLoc The location of the opening angle bracket ('<').
6028 /// \param TemplateArgs The template arguments.
6029 /// \param RAngleLoc The location of the closing angle bracket ('>').
6031 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6032 const CXXScopeSpec &SS,
6033 SourceLocation TemplateLoc,
6034 TemplateTy TemplateName,
6035 SourceLocation TemplateNameLoc,
6036 SourceLocation LAngleLoc,
6037 ASTTemplateArgsPtr TemplateArgs,
6038 SourceLocation RAngleLoc);
6040 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6041 SourceLocation KeywordLoc,
6042 NestedNameSpecifierLoc QualifierLoc,
6043 const IdentifierInfo &II,
6044 SourceLocation IILoc);
6046 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6048 DeclarationName Name);
6049 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6051 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6052 bool RebuildTemplateParamsInCurrentInstantiation(
6053 TemplateParameterList *Params);
6056 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6057 const TemplateArgumentList &Args);
6060 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6061 const TemplateArgument *Args,
6064 //===--------------------------------------------------------------------===//
6065 // C++ Variadic Templates (C++0x [temp.variadic])
6066 //===--------------------------------------------------------------------===//
6068 /// Determine whether an unexpanded parameter pack might be permitted in this
6069 /// location. Useful for error recovery.
6070 bool isUnexpandedParameterPackPermitted();
6072 /// \brief The context in which an unexpanded parameter pack is
6073 /// being diagnosed.
6075 /// Note that the values of this enumeration line up with the first
6076 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6077 enum UnexpandedParameterPackContext {
6078 /// \brief An arbitrary expression.
6079 UPPC_Expression = 0,
6081 /// \brief The base type of a class type.
6084 /// \brief The type of an arbitrary declaration.
6085 UPPC_DeclarationType,
6087 /// \brief The type of a data member.
6088 UPPC_DataMemberType,
6090 /// \brief The size of a bit-field.
6093 /// \brief The expression in a static assertion.
6094 UPPC_StaticAssertExpression,
6096 /// \brief The fixed underlying type of an enumeration.
6097 UPPC_FixedUnderlyingType,
6099 /// \brief The enumerator value.
6100 UPPC_EnumeratorValue,
6102 /// \brief A using declaration.
6103 UPPC_UsingDeclaration,
6105 /// \brief A friend declaration.
6106 UPPC_FriendDeclaration,
6108 /// \brief A declaration qualifier.
6109 UPPC_DeclarationQualifier,
6111 /// \brief An initializer.
6114 /// \brief A default argument.
6115 UPPC_DefaultArgument,
6117 /// \brief The type of a non-type template parameter.
6118 UPPC_NonTypeTemplateParameterType,
6120 /// \brief The type of an exception.
6123 /// \brief Partial specialization.
6124 UPPC_PartialSpecialization,
6126 /// \brief Microsoft __if_exists.
6129 /// \brief Microsoft __if_not_exists.
6132 /// \brief Lambda expression.
6135 /// \brief Block expression,
6139 /// \brief Diagnose unexpanded parameter packs.
6141 /// \param Loc The location at which we should emit the diagnostic.
6143 /// \param UPPC The context in which we are diagnosing unexpanded
6144 /// parameter packs.
6146 /// \param Unexpanded the set of unexpanded parameter packs.
6148 /// \returns true if an error occurred, false otherwise.
6149 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6150 UnexpandedParameterPackContext UPPC,
6151 ArrayRef<UnexpandedParameterPack> Unexpanded);
6153 /// \brief If the given type contains an unexpanded parameter pack,
6154 /// diagnose the error.
6156 /// \param Loc The source location where a diagnostc should be emitted.
6158 /// \param T The type that is being checked for unexpanded parameter
6161 /// \returns true if an error occurred, false otherwise.
6162 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6163 UnexpandedParameterPackContext UPPC);
6165 /// \brief If the given expression contains an unexpanded parameter
6166 /// pack, diagnose the error.
6168 /// \param E The expression that is being checked for unexpanded
6169 /// parameter packs.
6171 /// \returns true if an error occurred, false otherwise.
6172 bool DiagnoseUnexpandedParameterPack(Expr *E,
6173 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6175 /// \brief If the given nested-name-specifier contains an unexpanded
6176 /// parameter pack, diagnose the error.
6178 /// \param SS The nested-name-specifier that is being checked for
6179 /// unexpanded parameter packs.
6181 /// \returns true if an error occurred, false otherwise.
6182 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6183 UnexpandedParameterPackContext UPPC);
6185 /// \brief If the given name contains an unexpanded parameter pack,
6186 /// diagnose the error.
6188 /// \param NameInfo The name (with source location information) that
6189 /// is being checked for unexpanded parameter packs.
6191 /// \returns true if an error occurred, false otherwise.
6192 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6193 UnexpandedParameterPackContext UPPC);
6195 /// \brief If the given template name contains an unexpanded parameter pack,
6196 /// diagnose the error.
6198 /// \param Loc The location of the template name.
6200 /// \param Template The template name that is being checked for unexpanded
6201 /// parameter packs.
6203 /// \returns true if an error occurred, false otherwise.
6204 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6205 TemplateName Template,
6206 UnexpandedParameterPackContext UPPC);
6208 /// \brief If the given template argument contains an unexpanded parameter
6209 /// pack, diagnose the error.
6211 /// \param Arg The template argument that is being checked for unexpanded
6212 /// parameter packs.
6214 /// \returns true if an error occurred, false otherwise.
6215 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6216 UnexpandedParameterPackContext UPPC);
6218 /// \brief Collect the set of unexpanded parameter packs within the given
6219 /// template argument.
6221 /// \param Arg The template argument that will be traversed to find
6222 /// unexpanded parameter packs.
6223 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6224 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6226 /// \brief Collect the set of unexpanded parameter packs within the given
6227 /// template argument.
6229 /// \param Arg The template argument that will be traversed to find
6230 /// unexpanded parameter packs.
6231 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6232 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6234 /// \brief Collect the set of unexpanded parameter packs within the given
6237 /// \param T The type that will be traversed to find
6238 /// unexpanded parameter packs.
6239 void collectUnexpandedParameterPacks(QualType T,
6240 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6242 /// \brief Collect the set of unexpanded parameter packs within the given
6245 /// \param TL The type that will be traversed to find
6246 /// unexpanded parameter packs.
6247 void collectUnexpandedParameterPacks(TypeLoc TL,
6248 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6250 /// \brief Collect the set of unexpanded parameter packs within the given
6251 /// nested-name-specifier.
6253 /// \param SS The nested-name-specifier that will be traversed to find
6254 /// unexpanded parameter packs.
6255 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6256 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6258 /// \brief Collect the set of unexpanded parameter packs within the given
6261 /// \param NameInfo The name that will be traversed to find
6262 /// unexpanded parameter packs.
6263 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6264 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6266 /// \brief Invoked when parsing a template argument followed by an
6267 /// ellipsis, which creates a pack expansion.
6269 /// \param Arg The template argument preceding the ellipsis, which
6270 /// may already be invalid.
6272 /// \param EllipsisLoc The location of the ellipsis.
6273 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6274 SourceLocation EllipsisLoc);
6276 /// \brief Invoked when parsing a type followed by an ellipsis, which
6277 /// creates a pack expansion.
6279 /// \param Type The type preceding the ellipsis, which will become
6280 /// the pattern of the pack expansion.
6282 /// \param EllipsisLoc The location of the ellipsis.
6283 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6285 /// \brief Construct a pack expansion type from the pattern of the pack
6287 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6288 SourceLocation EllipsisLoc,
6289 Optional<unsigned> NumExpansions);
6291 /// \brief Construct a pack expansion type from the pattern of the pack
6293 QualType CheckPackExpansion(QualType Pattern,
6294 SourceRange PatternRange,
6295 SourceLocation EllipsisLoc,
6296 Optional<unsigned> NumExpansions);
6298 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6299 /// creates a pack expansion.
6301 /// \param Pattern The expression preceding the ellipsis, which will become
6302 /// the pattern of the pack expansion.
6304 /// \param EllipsisLoc The location of the ellipsis.
6305 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6307 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6308 /// creates a pack expansion.
6310 /// \param Pattern The expression preceding the ellipsis, which will become
6311 /// the pattern of the pack expansion.
6313 /// \param EllipsisLoc The location of the ellipsis.
6314 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6315 Optional<unsigned> NumExpansions);
6317 /// \brief Determine whether we could expand a pack expansion with the
6318 /// given set of parameter packs into separate arguments by repeatedly
6319 /// transforming the pattern.
6321 /// \param EllipsisLoc The location of the ellipsis that identifies the
6324 /// \param PatternRange The source range that covers the entire pattern of
6325 /// the pack expansion.
6327 /// \param Unexpanded The set of unexpanded parameter packs within the
6330 /// \param ShouldExpand Will be set to \c true if the transformer should
6331 /// expand the corresponding pack expansions into separate arguments. When
6332 /// set, \c NumExpansions must also be set.
6334 /// \param RetainExpansion Whether the caller should add an unexpanded
6335 /// pack expansion after all of the expanded arguments. This is used
6336 /// when extending explicitly-specified template argument packs per
6337 /// C++0x [temp.arg.explicit]p9.
6339 /// \param NumExpansions The number of separate arguments that will be in
6340 /// the expanded form of the corresponding pack expansion. This is both an
6341 /// input and an output parameter, which can be set by the caller if the
6342 /// number of expansions is known a priori (e.g., due to a prior substitution)
6343 /// and will be set by the callee when the number of expansions is known.
6344 /// The callee must set this value when \c ShouldExpand is \c true; it may
6345 /// set this value in other cases.
6347 /// \returns true if an error occurred (e.g., because the parameter packs
6348 /// are to be instantiated with arguments of different lengths), false
6349 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6351 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6352 SourceRange PatternRange,
6353 ArrayRef<UnexpandedParameterPack> Unexpanded,
6354 const MultiLevelTemplateArgumentList &TemplateArgs,
6356 bool &RetainExpansion,
6357 Optional<unsigned> &NumExpansions);
6359 /// \brief Determine the number of arguments in the given pack expansion
6362 /// This routine assumes that the number of arguments in the expansion is
6363 /// consistent across all of the unexpanded parameter packs in its pattern.
6365 /// Returns an empty Optional if the type can't be expanded.
6366 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6367 const MultiLevelTemplateArgumentList &TemplateArgs);
6369 /// \brief Determine whether the given declarator contains any unexpanded
6370 /// parameter packs.
6372 /// This routine is used by the parser to disambiguate function declarators
6373 /// with an ellipsis prior to the ')', e.g.,
6379 /// To determine whether we have an (unnamed) function parameter pack or
6380 /// a variadic function.
6382 /// \returns true if the declarator contains any unexpanded parameter packs,
6383 /// false otherwise.
6384 bool containsUnexpandedParameterPacks(Declarator &D);
6386 /// \brief Returns the pattern of the pack expansion for a template argument.
6388 /// \param OrigLoc The template argument to expand.
6390 /// \param Ellipsis Will be set to the location of the ellipsis.
6392 /// \param NumExpansions Will be set to the number of expansions that will
6393 /// be generated from this pack expansion, if known a priori.
6394 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6395 TemplateArgumentLoc OrigLoc,
6396 SourceLocation &Ellipsis,
6397 Optional<unsigned> &NumExpansions) const;
6399 //===--------------------------------------------------------------------===//
6400 // C++ Template Argument Deduction (C++ [temp.deduct])
6401 //===--------------------------------------------------------------------===//
6403 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6405 /// \brief Describes the result of template argument deduction.
6407 /// The TemplateDeductionResult enumeration describes the result of
6408 /// template argument deduction, as returned from
6409 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6410 /// structure provides additional information about the results of
6411 /// template argument deduction, e.g., the deduced template argument
6412 /// list (if successful) or the specific template parameters or
6413 /// deduced arguments that were involved in the failure.
6414 enum TemplateDeductionResult {
6415 /// \brief Template argument deduction was successful.
6417 /// \brief The declaration was invalid; do nothing.
6419 /// \brief Template argument deduction exceeded the maximum template
6420 /// instantiation depth (which has already been diagnosed).
6421 TDK_InstantiationDepth,
6422 /// \brief Template argument deduction did not deduce a value
6423 /// for every template parameter.
6425 /// \brief Template argument deduction produced inconsistent
6426 /// deduced values for the given template parameter.
6428 /// \brief Template argument deduction failed due to inconsistent
6429 /// cv-qualifiers on a template parameter type that would
6430 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6431 /// but were given a non-const "X".
6433 /// \brief Substitution of the deduced template argument values
6434 /// resulted in an error.
6435 TDK_SubstitutionFailure,
6436 /// \brief After substituting deduced template arguments, a dependent
6437 /// parameter type did not match the corresponding argument.
6438 TDK_DeducedMismatch,
6439 /// \brief A non-depnedent component of the parameter did not match the
6440 /// corresponding component of the argument.
6441 TDK_NonDeducedMismatch,
6442 /// \brief When performing template argument deduction for a function
6443 /// template, there were too many call arguments.
6444 TDK_TooManyArguments,
6445 /// \brief When performing template argument deduction for a function
6446 /// template, there were too few call arguments.
6447 TDK_TooFewArguments,
6448 /// \brief The explicitly-specified template arguments were not valid
6449 /// template arguments for the given template.
6450 TDK_InvalidExplicitArguments,
6451 /// \brief The arguments included an overloaded function name that could
6452 /// not be resolved to a suitable function.
6453 TDK_FailedOverloadResolution,
6454 /// \brief Deduction failed; that's all we know.
6455 TDK_MiscellaneousDeductionFailure
6458 TemplateDeductionResult
6459 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6460 const TemplateArgumentList &TemplateArgs,
6461 sema::TemplateDeductionInfo &Info);
6463 TemplateDeductionResult
6464 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6465 const TemplateArgumentList &TemplateArgs,
6466 sema::TemplateDeductionInfo &Info);
6468 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6469 FunctionTemplateDecl *FunctionTemplate,
6470 TemplateArgumentListInfo &ExplicitTemplateArgs,
6471 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6472 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6473 sema::TemplateDeductionInfo &Info);
6475 /// brief A function argument from which we performed template argument
6476 // deduction for a call.
6477 struct OriginalCallArg {
6478 OriginalCallArg(QualType OriginalParamType,
6480 QualType OriginalArgType)
6481 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6482 OriginalArgType(OriginalArgType) { }
6484 QualType OriginalParamType;
6486 QualType OriginalArgType;
6489 TemplateDeductionResult
6490 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6491 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6492 unsigned NumExplicitlySpecified,
6493 FunctionDecl *&Specialization,
6494 sema::TemplateDeductionInfo &Info,
6495 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6496 bool PartialOverloading = false);
6498 TemplateDeductionResult
6499 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6500 TemplateArgumentListInfo *ExplicitTemplateArgs,
6501 ArrayRef<Expr *> Args,
6502 FunctionDecl *&Specialization,
6503 sema::TemplateDeductionInfo &Info,
6504 bool PartialOverloading = false);
6506 TemplateDeductionResult
6507 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6508 TemplateArgumentListInfo *ExplicitTemplateArgs,
6509 QualType ArgFunctionType,
6510 FunctionDecl *&Specialization,
6511 sema::TemplateDeductionInfo &Info,
6512 bool InOverloadResolution = false);
6514 TemplateDeductionResult
6515 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6517 CXXConversionDecl *&Specialization,
6518 sema::TemplateDeductionInfo &Info);
6520 TemplateDeductionResult
6521 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6522 TemplateArgumentListInfo *ExplicitTemplateArgs,
6523 FunctionDecl *&Specialization,
6524 sema::TemplateDeductionInfo &Info,
6525 bool InOverloadResolution = false);
6527 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6528 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6529 /// \brief Substitute Replacement for auto in TypeWithAuto
6530 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6531 QualType Replacement);
6533 /// \brief Result type of DeduceAutoType.
6534 enum DeduceAutoResult {
6537 DAR_FailedAlreadyDiagnosed
6540 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6542 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6544 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6545 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6546 bool Diagnose = true);
6548 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6549 QualType Type, TypeSourceInfo *TSI,
6550 SourceRange Range, bool DirectInit,
6553 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6555 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6556 SourceLocation ReturnLoc,
6557 Expr *&RetExpr, AutoType *AT);
6559 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6560 FunctionTemplateDecl *FT2,
6562 TemplatePartialOrderingContext TPOC,
6563 unsigned NumCallArguments1,
6564 unsigned NumCallArguments2);
6565 UnresolvedSetIterator
6566 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6567 TemplateSpecCandidateSet &FailedCandidates,
6569 const PartialDiagnostic &NoneDiag,
6570 const PartialDiagnostic &AmbigDiag,
6571 const PartialDiagnostic &CandidateDiag,
6572 bool Complain = true, QualType TargetType = QualType());
6574 ClassTemplatePartialSpecializationDecl *
6575 getMoreSpecializedPartialSpecialization(
6576 ClassTemplatePartialSpecializationDecl *PS1,
6577 ClassTemplatePartialSpecializationDecl *PS2,
6578 SourceLocation Loc);
6580 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6581 VarTemplatePartialSpecializationDecl *PS1,
6582 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6584 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6587 llvm::SmallBitVector &Used);
6588 void MarkDeducedTemplateParameters(
6589 const FunctionTemplateDecl *FunctionTemplate,
6590 llvm::SmallBitVector &Deduced) {
6591 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6593 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6594 const FunctionTemplateDecl *FunctionTemplate,
6595 llvm::SmallBitVector &Deduced);
6597 //===--------------------------------------------------------------------===//
6598 // C++ Template Instantiation
6601 MultiLevelTemplateArgumentList
6602 getTemplateInstantiationArgs(NamedDecl *D,
6603 const TemplateArgumentList *Innermost = nullptr,
6604 bool RelativeToPrimary = false,
6605 const FunctionDecl *Pattern = nullptr);
6607 /// \brief A template instantiation that is currently in progress.
6608 struct ActiveTemplateInstantiation {
6609 /// \brief The kind of template instantiation we are performing
6610 enum InstantiationKind {
6611 /// We are instantiating a template declaration. The entity is
6612 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6613 TemplateInstantiation,
6615 /// We are instantiating a default argument for a template
6616 /// parameter. The Entity is the template, and
6617 /// TemplateArgs/NumTemplateArguments provides the template
6618 /// arguments as specified.
6619 /// FIXME: Use a TemplateArgumentList
6620 DefaultTemplateArgumentInstantiation,
6622 /// We are instantiating a default argument for a function.
6623 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6624 /// provides the template arguments as specified.
6625 DefaultFunctionArgumentInstantiation,
6627 /// We are substituting explicit template arguments provided for
6628 /// a function template. The entity is a FunctionTemplateDecl.
6629 ExplicitTemplateArgumentSubstitution,
6631 /// We are substituting template argument determined as part of
6632 /// template argument deduction for either a class template
6633 /// partial specialization or a function template. The
6634 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6635 /// a FunctionTemplateDecl.
6636 DeducedTemplateArgumentSubstitution,
6638 /// We are substituting prior template arguments into a new
6639 /// template parameter. The template parameter itself is either a
6640 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6641 PriorTemplateArgumentSubstitution,
6643 /// We are checking the validity of a default template argument that
6644 /// has been used when naming a template-id.
6645 DefaultTemplateArgumentChecking,
6647 /// We are instantiating the exception specification for a function
6648 /// template which was deferred until it was needed.
6649 ExceptionSpecInstantiation
6652 /// \brief The point of instantiation within the source code.
6653 SourceLocation PointOfInstantiation;
6655 /// \brief The template (or partial specialization) in which we are
6656 /// performing the instantiation, for substitutions of prior template
6658 NamedDecl *Template;
6660 /// \brief The entity that is being instantiated.
6663 /// \brief The list of template arguments we are substituting, if they
6664 /// are not part of the entity.
6665 const TemplateArgument *TemplateArgs;
6667 /// \brief The number of template arguments in TemplateArgs.
6668 unsigned NumTemplateArgs;
6670 ArrayRef<TemplateArgument> template_arguments() const {
6671 return {TemplateArgs, NumTemplateArgs};
6674 /// \brief The template deduction info object associated with the
6675 /// substitution or checking of explicit or deduced template arguments.
6676 sema::TemplateDeductionInfo *DeductionInfo;
6678 /// \brief The source range that covers the construct that cause
6679 /// the instantiation, e.g., the template-id that causes a class
6680 /// template instantiation.
6681 SourceRange InstantiationRange;
6683 ActiveTemplateInstantiation()
6684 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6685 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6687 /// \brief Determines whether this template is an actual instantiation
6688 /// that should be counted toward the maximum instantiation depth.
6689 bool isInstantiationRecord() const;
6691 friend bool operator==(const ActiveTemplateInstantiation &X,
6692 const ActiveTemplateInstantiation &Y) {
6693 if (X.Kind != Y.Kind)
6696 if (X.Entity != Y.Entity)
6700 case TemplateInstantiation:
6701 case ExceptionSpecInstantiation:
6704 case PriorTemplateArgumentSubstitution:
6705 case DefaultTemplateArgumentChecking:
6706 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6708 case DefaultTemplateArgumentInstantiation:
6709 case ExplicitTemplateArgumentSubstitution:
6710 case DeducedTemplateArgumentSubstitution:
6711 case DefaultFunctionArgumentInstantiation:
6712 return X.TemplateArgs == Y.TemplateArgs;
6716 llvm_unreachable("Invalid InstantiationKind!");
6719 friend bool operator!=(const ActiveTemplateInstantiation &X,
6720 const ActiveTemplateInstantiation &Y) {
6725 /// \brief List of active template instantiations.
6727 /// This vector is treated as a stack. As one template instantiation
6728 /// requires another template instantiation, additional
6729 /// instantiations are pushed onto the stack up to a
6730 /// user-configurable limit LangOptions::InstantiationDepth.
6731 SmallVector<ActiveTemplateInstantiation, 16>
6732 ActiveTemplateInstantiations;
6734 /// \brief Extra modules inspected when performing a lookup during a template
6735 /// instantiation. Computed lazily.
6736 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6738 /// \brief Cache of additional modules that should be used for name lookup
6739 /// within the current template instantiation. Computed lazily; use
6740 /// getLookupModules() to get a complete set.
6741 llvm::DenseSet<Module*> LookupModulesCache;
6743 /// \brief Get the set of additional modules that should be checked during
6744 /// name lookup. A module and its imports become visible when instanting a
6745 /// template defined within it.
6746 llvm::DenseSet<Module*> &getLookupModules();
6748 /// \brief Map from the most recent declaration of a namespace to the most
6749 /// recent visible declaration of that namespace.
6750 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
6752 /// \brief Whether we are in a SFINAE context that is not associated with
6753 /// template instantiation.
6755 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6756 /// of a template instantiation or template argument deduction.
6757 bool InNonInstantiationSFINAEContext;
6759 /// \brief The number of ActiveTemplateInstantiation entries in
6760 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6761 /// therefore, should not be counted as part of the instantiation depth.
6762 unsigned NonInstantiationEntries;
6764 /// \brief The last template from which a template instantiation
6765 /// error or warning was produced.
6767 /// This value is used to suppress printing of redundant template
6768 /// instantiation backtraces when there are multiple errors in the
6769 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6770 /// to implement it anywhere else.
6771 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6773 /// \brief The current index into pack expansion arguments that will be
6774 /// used for substitution of parameter packs.
6776 /// The pack expansion index will be -1 to indicate that parameter packs
6777 /// should be instantiated as themselves. Otherwise, the index specifies
6778 /// which argument within the parameter pack will be used for substitution.
6779 int ArgumentPackSubstitutionIndex;
6781 /// \brief RAII object used to change the argument pack substitution index
6782 /// within a \c Sema object.
6784 /// See \c ArgumentPackSubstitutionIndex for more information.
6785 class ArgumentPackSubstitutionIndexRAII {
6787 int OldSubstitutionIndex;
6790 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6791 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6792 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6795 ~ArgumentPackSubstitutionIndexRAII() {
6796 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6800 friend class ArgumentPackSubstitutionRAII;
6802 /// \brief For each declaration that involved template argument deduction, the
6803 /// set of diagnostics that were suppressed during that template argument
6806 /// FIXME: Serialize this structure to the AST file.
6807 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6808 SuppressedDiagnosticsMap;
6809 SuppressedDiagnosticsMap SuppressedDiagnostics;
6811 /// \brief A stack object to be created when performing template
6814 /// Construction of an object of type \c InstantiatingTemplate
6815 /// pushes the current instantiation onto the stack of active
6816 /// instantiations. If the size of this stack exceeds the maximum
6817 /// number of recursive template instantiations, construction
6818 /// produces an error and evaluates true.
6820 /// Destruction of this object will pop the named instantiation off
6822 struct InstantiatingTemplate {
6823 /// \brief Note that we are instantiating a class template,
6824 /// function template, variable template, alias template,
6825 /// or a member thereof.
6826 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6828 SourceRange InstantiationRange = SourceRange());
6830 struct ExceptionSpecification {};
6831 /// \brief Note that we are instantiating an exception specification
6832 /// of a function template.
6833 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6834 FunctionDecl *Entity, ExceptionSpecification,
6835 SourceRange InstantiationRange = SourceRange());
6837 /// \brief Note that we are instantiating a default argument in a
6839 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6840 TemplateDecl *Template,
6841 ArrayRef<TemplateArgument> TemplateArgs,
6842 SourceRange InstantiationRange = SourceRange());
6844 /// \brief Note that we are instantiating a default argument in a
6846 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6847 FunctionTemplateDecl *FunctionTemplate,
6848 ArrayRef<TemplateArgument> TemplateArgs,
6849 ActiveTemplateInstantiation::InstantiationKind Kind,
6850 sema::TemplateDeductionInfo &DeductionInfo,
6851 SourceRange InstantiationRange = SourceRange());
6853 /// \brief Note that we are instantiating as part of template
6854 /// argument deduction for a class template partial
6856 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6857 ClassTemplatePartialSpecializationDecl *PartialSpec,
6858 ArrayRef<TemplateArgument> TemplateArgs,
6859 sema::TemplateDeductionInfo &DeductionInfo,
6860 SourceRange InstantiationRange = SourceRange());
6862 /// \brief Note that we are instantiating as part of template
6863 /// argument deduction for a variable template partial
6865 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6866 VarTemplatePartialSpecializationDecl *PartialSpec,
6867 ArrayRef<TemplateArgument> TemplateArgs,
6868 sema::TemplateDeductionInfo &DeductionInfo,
6869 SourceRange InstantiationRange = SourceRange());
6871 /// \brief Note that we are instantiating a default argument for a function
6873 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6875 ArrayRef<TemplateArgument> TemplateArgs,
6876 SourceRange InstantiationRange = SourceRange());
6878 /// \brief Note that we are substituting prior template arguments into a
6879 /// non-type parameter.
6880 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6881 NamedDecl *Template,
6882 NonTypeTemplateParmDecl *Param,
6883 ArrayRef<TemplateArgument> TemplateArgs,
6884 SourceRange InstantiationRange);
6886 /// \brief Note that we are substituting prior template arguments into a
6887 /// template template parameter.
6888 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6889 NamedDecl *Template,
6890 TemplateTemplateParmDecl *Param,
6891 ArrayRef<TemplateArgument> TemplateArgs,
6892 SourceRange InstantiationRange);
6894 /// \brief Note that we are checking the default template argument
6895 /// against the template parameter for a given template-id.
6896 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6897 TemplateDecl *Template,
6899 ArrayRef<TemplateArgument> TemplateArgs,
6900 SourceRange InstantiationRange);
6903 /// \brief Note that we have finished instantiating this template.
6906 ~InstantiatingTemplate() { Clear(); }
6908 /// \brief Determines whether we have exceeded the maximum
6909 /// recursive template instantiations.
6910 bool isInvalid() const { return Invalid; }
6915 bool SavedInNonInstantiationSFINAEContext;
6916 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6917 SourceRange InstantiationRange);
6919 InstantiatingTemplate(
6920 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6921 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6922 Decl *Entity, NamedDecl *Template = nullptr,
6923 ArrayRef<TemplateArgument> TemplateArgs = None,
6924 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6926 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6928 InstantiatingTemplate&
6929 operator=(const InstantiatingTemplate&) = delete;
6932 void PrintInstantiationStack();
6934 /// \brief Determines whether we are currently in a context where
6935 /// template argument substitution failures are not considered
6938 /// \returns An empty \c Optional if we're not in a SFINAE context.
6939 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6940 /// template-deduction context object, which can be used to capture
6941 /// diagnostics that will be suppressed.
6942 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6944 /// \brief Determines whether we are currently in a context that
6945 /// is not evaluated as per C++ [expr] p5.
6946 bool isUnevaluatedContext() const {
6947 assert(!ExprEvalContexts.empty() &&
6948 "Must be in an expression evaluation context");
6949 return ExprEvalContexts.back().isUnevaluated();
6952 /// \brief RAII class used to determine whether SFINAE has
6953 /// trapped any errors that occur during template argument
6957 unsigned PrevSFINAEErrors;
6958 bool PrevInNonInstantiationSFINAEContext;
6959 bool PrevAccessCheckingSFINAE;
6962 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6963 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6964 PrevInNonInstantiationSFINAEContext(
6965 SemaRef.InNonInstantiationSFINAEContext),
6966 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6968 if (!SemaRef.isSFINAEContext())
6969 SemaRef.InNonInstantiationSFINAEContext = true;
6970 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6974 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6975 SemaRef.InNonInstantiationSFINAEContext
6976 = PrevInNonInstantiationSFINAEContext;
6977 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6980 /// \brief Determine whether any SFINAE errors have been trapped.
6981 bool hasErrorOccurred() const {
6982 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6986 /// \brief RAII class used to indicate that we are performing provisional
6987 /// semantic analysis to determine the validity of a construct, so
6988 /// typo-correction and diagnostics in the immediate context (not within
6989 /// implicitly-instantiated templates) should be suppressed.
6990 class TentativeAnalysisScope {
6992 // FIXME: Using a SFINAETrap for this is a hack.
6994 bool PrevDisableTypoCorrection;
6996 explicit TentativeAnalysisScope(Sema &SemaRef)
6997 : SemaRef(SemaRef), Trap(SemaRef, true),
6998 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6999 SemaRef.DisableTypoCorrection = true;
7001 ~TentativeAnalysisScope() {
7002 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7006 /// \brief The current instantiation scope used to store local
7008 LocalInstantiationScope *CurrentInstantiationScope;
7010 /// \brief Tracks whether we are in a context where typo correction is
7012 bool DisableTypoCorrection;
7014 /// \brief The number of typos corrected by CorrectTypo.
7015 unsigned TyposCorrected;
7017 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7018 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7020 /// \brief A cache containing identifiers for which typo correction failed and
7021 /// their locations, so that repeated attempts to correct an identifier in a
7022 /// given location are ignored if typo correction already failed for it.
7023 IdentifierSourceLocations TypoCorrectionFailures;
7025 /// \brief Worker object for performing CFG-based warnings.
7026 sema::AnalysisBasedWarnings AnalysisWarnings;
7027 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7029 /// \brief An entity for which implicit template instantiation is required.
7031 /// The source location associated with the declaration is the first place in
7032 /// the source code where the declaration was "used". It is not necessarily
7033 /// the point of instantiation (which will be either before or after the
7034 /// namespace-scope declaration that triggered this implicit instantiation),
7035 /// However, it is the location that diagnostics should generally refer to,
7036 /// because users will need to know what code triggered the instantiation.
7037 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7039 /// \brief The queue of implicit template instantiations that are required
7040 /// but have not yet been performed.
7041 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7043 class SavePendingInstantiationsAndVTableUsesRAII {
7045 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7046 : S(S), Enabled(Enabled) {
7047 if (!Enabled) return;
7049 SavedPendingInstantiations.swap(S.PendingInstantiations);
7050 SavedVTableUses.swap(S.VTableUses);
7053 ~SavePendingInstantiationsAndVTableUsesRAII() {
7054 if (!Enabled) return;
7056 // Restore the set of pending vtables.
7057 assert(S.VTableUses.empty() &&
7058 "VTableUses should be empty before it is discarded.");
7059 S.VTableUses.swap(SavedVTableUses);
7061 // Restore the set of pending implicit instantiations.
7062 assert(S.PendingInstantiations.empty() &&
7063 "PendingInstantiations should be empty before it is discarded.");
7064 S.PendingInstantiations.swap(SavedPendingInstantiations);
7069 SmallVector<VTableUse, 16> SavedVTableUses;
7070 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7074 /// \brief The queue of implicit template instantiations that are required
7075 /// and must be performed within the current local scope.
7077 /// This queue is only used for member functions of local classes in
7078 /// templates, which must be instantiated in the same scope as their
7079 /// enclosing function, so that they can reference function-local
7080 /// types, static variables, enumerators, etc.
7081 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7083 class SavePendingLocalImplicitInstantiationsRAII {
7085 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7086 SavedPendingLocalImplicitInstantiations.swap(
7087 S.PendingLocalImplicitInstantiations);
7090 ~SavePendingLocalImplicitInstantiationsRAII() {
7091 assert(S.PendingLocalImplicitInstantiations.empty() &&
7092 "there shouldn't be any pending local implicit instantiations");
7093 SavedPendingLocalImplicitInstantiations.swap(
7094 S.PendingLocalImplicitInstantiations);
7099 std::deque<PendingImplicitInstantiation>
7100 SavedPendingLocalImplicitInstantiations;
7103 /// A helper class for building up ExtParameterInfos.
7104 class ExtParameterInfoBuilder {
7105 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7106 bool HasInteresting = false;
7109 /// Set the ExtParameterInfo for the parameter at the given index,
7111 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7112 assert(Infos.size() <= index);
7113 Infos.resize(index);
7114 Infos.push_back(info);
7116 if (!HasInteresting)
7117 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7120 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7121 /// ExtParameterInfo array we've built up.
7122 const FunctionProtoType::ExtParameterInfo *
7123 getPointerOrNull(unsigned numParams) {
7124 if (!HasInteresting) return nullptr;
7125 Infos.resize(numParams);
7126 return Infos.data();
7130 void PerformPendingInstantiations(bool LocalOnly = false);
7132 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7133 const MultiLevelTemplateArgumentList &TemplateArgs,
7134 SourceLocation Loc, DeclarationName Entity);
7136 QualType SubstType(QualType T,
7137 const MultiLevelTemplateArgumentList &TemplateArgs,
7138 SourceLocation Loc, DeclarationName Entity);
7140 TypeSourceInfo *SubstType(TypeLoc TL,
7141 const MultiLevelTemplateArgumentList &TemplateArgs,
7142 SourceLocation Loc, DeclarationName Entity);
7144 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7145 const MultiLevelTemplateArgumentList &TemplateArgs,
7147 DeclarationName Entity,
7148 CXXRecordDecl *ThisContext,
7149 unsigned ThisTypeQuals);
7150 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7151 const MultiLevelTemplateArgumentList &Args);
7152 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7153 const MultiLevelTemplateArgumentList &TemplateArgs,
7154 int indexAdjustment,
7155 Optional<unsigned> NumExpansions,
7156 bool ExpectParameterPack);
7157 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7158 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7159 const MultiLevelTemplateArgumentList &TemplateArgs,
7160 SmallVectorImpl<QualType> &ParamTypes,
7161 SmallVectorImpl<ParmVarDecl *> *OutParams,
7162 ExtParameterInfoBuilder &ParamInfos);
7163 ExprResult SubstExpr(Expr *E,
7164 const MultiLevelTemplateArgumentList &TemplateArgs);
7166 /// \brief Substitute the given template arguments into a list of
7167 /// expressions, expanding pack expansions if required.
7169 /// \param Exprs The list of expressions to substitute into.
7171 /// \param IsCall Whether this is some form of call, in which case
7172 /// default arguments will be dropped.
7174 /// \param TemplateArgs The set of template arguments to substitute.
7176 /// \param Outputs Will receive all of the substituted arguments.
7178 /// \returns true if an error occurred, false otherwise.
7179 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7180 const MultiLevelTemplateArgumentList &TemplateArgs,
7181 SmallVectorImpl<Expr *> &Outputs);
7183 StmtResult SubstStmt(Stmt *S,
7184 const MultiLevelTemplateArgumentList &TemplateArgs);
7186 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7187 const MultiLevelTemplateArgumentList &TemplateArgs);
7189 ExprResult SubstInitializer(Expr *E,
7190 const MultiLevelTemplateArgumentList &TemplateArgs,
7191 bool CXXDirectInit);
7194 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7195 CXXRecordDecl *Pattern,
7196 const MultiLevelTemplateArgumentList &TemplateArgs);
7199 InstantiateClass(SourceLocation PointOfInstantiation,
7200 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7201 const MultiLevelTemplateArgumentList &TemplateArgs,
7202 TemplateSpecializationKind TSK,
7203 bool Complain = true);
7205 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7206 EnumDecl *Instantiation, EnumDecl *Pattern,
7207 const MultiLevelTemplateArgumentList &TemplateArgs,
7208 TemplateSpecializationKind TSK);
7210 bool InstantiateInClassInitializer(
7211 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7212 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7214 struct LateInstantiatedAttribute {
7215 const Attr *TmplAttr;
7216 LocalInstantiationScope *Scope;
7219 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7221 : TmplAttr(A), Scope(S), NewDecl(D)
7224 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7226 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7227 const Decl *Pattern, Decl *Inst,
7228 LateInstantiatedAttrVec *LateAttrs = nullptr,
7229 LocalInstantiationScope *OuterMostScope = nullptr);
7232 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7233 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7234 TemplateSpecializationKind TSK,
7235 bool Complain = true);
7237 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7238 CXXRecordDecl *Instantiation,
7239 const MultiLevelTemplateArgumentList &TemplateArgs,
7240 TemplateSpecializationKind TSK);
7242 void InstantiateClassTemplateSpecializationMembers(
7243 SourceLocation PointOfInstantiation,
7244 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7245 TemplateSpecializationKind TSK);
7247 NestedNameSpecifierLoc
7248 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7249 const MultiLevelTemplateArgumentList &TemplateArgs);
7252 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7253 const MultiLevelTemplateArgumentList &TemplateArgs);
7255 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7257 const MultiLevelTemplateArgumentList &TemplateArgs);
7258 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7259 TemplateArgumentListInfo &Result,
7260 const MultiLevelTemplateArgumentList &TemplateArgs);
7262 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7263 FunctionDecl *Function);
7264 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7265 FunctionDecl *Function,
7266 bool Recursive = false,
7267 bool DefinitionRequired = false,
7268 bool AtEndOfTU = false);
7269 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7270 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7271 const TemplateArgumentList &TemplateArgList,
7272 const TemplateArgumentListInfo &TemplateArgsInfo,
7273 SmallVectorImpl<TemplateArgument> &Converted,
7274 SourceLocation PointOfInstantiation, void *InsertPos,
7275 LateInstantiatedAttrVec *LateAttrs = nullptr,
7276 LocalInstantiationScope *StartingScope = nullptr);
7277 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7278 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7279 const MultiLevelTemplateArgumentList &TemplateArgs);
7281 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7282 const MultiLevelTemplateArgumentList &TemplateArgs,
7283 LateInstantiatedAttrVec *LateAttrs,
7285 LocalInstantiationScope *StartingScope,
7286 bool InstantiatingVarTemplate = false);
7287 void InstantiateVariableInitializer(
7288 VarDecl *Var, VarDecl *OldVar,
7289 const MultiLevelTemplateArgumentList &TemplateArgs);
7290 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7291 VarDecl *Var, bool Recursive = false,
7292 bool DefinitionRequired = false,
7293 bool AtEndOfTU = false);
7294 void InstantiateStaticDataMemberDefinition(
7295 SourceLocation PointOfInstantiation,
7297 bool Recursive = false,
7298 bool DefinitionRequired = false);
7300 void InstantiateMemInitializers(CXXConstructorDecl *New,
7301 const CXXConstructorDecl *Tmpl,
7302 const MultiLevelTemplateArgumentList &TemplateArgs);
7304 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7305 const MultiLevelTemplateArgumentList &TemplateArgs);
7306 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7307 const MultiLevelTemplateArgumentList &TemplateArgs);
7309 // Objective-C declarations.
7310 enum ObjCContainerKind {
7317 OCK_CategoryImplementation
7319 ObjCContainerKind getObjCContainerKind() const;
7321 DeclResult actOnObjCTypeParam(Scope *S,
7322 ObjCTypeParamVariance variance,
7323 SourceLocation varianceLoc,
7325 IdentifierInfo *paramName,
7326 SourceLocation paramLoc,
7327 SourceLocation colonLoc,
7328 ParsedType typeBound);
7330 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7331 ArrayRef<Decl *> typeParams,
7332 SourceLocation rAngleLoc);
7333 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7335 Decl *ActOnStartClassInterface(Scope *S,
7336 SourceLocation AtInterfaceLoc,
7337 IdentifierInfo *ClassName,
7338 SourceLocation ClassLoc,
7339 ObjCTypeParamList *typeParamList,
7340 IdentifierInfo *SuperName,
7341 SourceLocation SuperLoc,
7342 ArrayRef<ParsedType> SuperTypeArgs,
7343 SourceRange SuperTypeArgsRange,
7344 Decl * const *ProtoRefs,
7345 unsigned NumProtoRefs,
7346 const SourceLocation *ProtoLocs,
7347 SourceLocation EndProtoLoc,
7348 AttributeList *AttrList);
7350 void ActOnSuperClassOfClassInterface(Scope *S,
7351 SourceLocation AtInterfaceLoc,
7352 ObjCInterfaceDecl *IDecl,
7353 IdentifierInfo *ClassName,
7354 SourceLocation ClassLoc,
7355 IdentifierInfo *SuperName,
7356 SourceLocation SuperLoc,
7357 ArrayRef<ParsedType> SuperTypeArgs,
7358 SourceRange SuperTypeArgsRange);
7360 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7361 IdentifierInfo *SuperName,
7362 SourceLocation SuperLoc);
7364 Decl *ActOnCompatibilityAlias(
7365 SourceLocation AtCompatibilityAliasLoc,
7366 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7367 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7369 bool CheckForwardProtocolDeclarationForCircularDependency(
7370 IdentifierInfo *PName,
7371 SourceLocation &PLoc, SourceLocation PrevLoc,
7372 const ObjCList<ObjCProtocolDecl> &PList);
7374 Decl *ActOnStartProtocolInterface(
7375 SourceLocation AtProtoInterfaceLoc,
7376 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7377 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7378 const SourceLocation *ProtoLocs,
7379 SourceLocation EndProtoLoc,
7380 AttributeList *AttrList);
7382 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7383 IdentifierInfo *ClassName,
7384 SourceLocation ClassLoc,
7385 ObjCTypeParamList *typeParamList,
7386 IdentifierInfo *CategoryName,
7387 SourceLocation CategoryLoc,
7388 Decl * const *ProtoRefs,
7389 unsigned NumProtoRefs,
7390 const SourceLocation *ProtoLocs,
7391 SourceLocation EndProtoLoc);
7393 Decl *ActOnStartClassImplementation(
7394 SourceLocation AtClassImplLoc,
7395 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7396 IdentifierInfo *SuperClassname,
7397 SourceLocation SuperClassLoc);
7399 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7400 IdentifierInfo *ClassName,
7401 SourceLocation ClassLoc,
7402 IdentifierInfo *CatName,
7403 SourceLocation CatLoc);
7405 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7406 ArrayRef<Decl *> Decls);
7408 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7409 IdentifierInfo **IdentList,
7410 SourceLocation *IdentLocs,
7411 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7414 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7415 ArrayRef<IdentifierLocPair> IdentList,
7416 AttributeList *attrList);
7418 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7419 ArrayRef<IdentifierLocPair> ProtocolId,
7420 SmallVectorImpl<Decl *> &Protocols);
7422 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7423 SourceLocation ProtocolLoc,
7424 IdentifierInfo *TypeArgId,
7425 SourceLocation TypeArgLoc,
7426 bool SelectProtocolFirst = false);
7428 /// Given a list of identifiers (and their locations), resolve the
7429 /// names to either Objective-C protocol qualifiers or type
7430 /// arguments, as appropriate.
7431 void actOnObjCTypeArgsOrProtocolQualifiers(
7433 ParsedType baseType,
7434 SourceLocation lAngleLoc,
7435 ArrayRef<IdentifierInfo *> identifiers,
7436 ArrayRef<SourceLocation> identifierLocs,
7437 SourceLocation rAngleLoc,
7438 SourceLocation &typeArgsLAngleLoc,
7439 SmallVectorImpl<ParsedType> &typeArgs,
7440 SourceLocation &typeArgsRAngleLoc,
7441 SourceLocation &protocolLAngleLoc,
7442 SmallVectorImpl<Decl *> &protocols,
7443 SourceLocation &protocolRAngleLoc,
7444 bool warnOnIncompleteProtocols);
7446 /// Build a an Objective-C protocol-qualified 'id' type where no
7447 /// base type was specified.
7448 TypeResult actOnObjCProtocolQualifierType(
7449 SourceLocation lAngleLoc,
7450 ArrayRef<Decl *> protocols,
7451 ArrayRef<SourceLocation> protocolLocs,
7452 SourceLocation rAngleLoc);
7454 /// Build a specialized and/or protocol-qualified Objective-C type.
7455 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7458 ParsedType BaseType,
7459 SourceLocation TypeArgsLAngleLoc,
7460 ArrayRef<ParsedType> TypeArgs,
7461 SourceLocation TypeArgsRAngleLoc,
7462 SourceLocation ProtocolLAngleLoc,
7463 ArrayRef<Decl *> Protocols,
7464 ArrayRef<SourceLocation> ProtocolLocs,
7465 SourceLocation ProtocolRAngleLoc);
7467 /// Build an Objective-C object pointer type.
7468 QualType BuildObjCObjectType(QualType BaseType,
7470 SourceLocation TypeArgsLAngleLoc,
7471 ArrayRef<TypeSourceInfo *> TypeArgs,
7472 SourceLocation TypeArgsRAngleLoc,
7473 SourceLocation ProtocolLAngleLoc,
7474 ArrayRef<ObjCProtocolDecl *> Protocols,
7475 ArrayRef<SourceLocation> ProtocolLocs,
7476 SourceLocation ProtocolRAngleLoc,
7477 bool FailOnError = false);
7479 /// Check the application of the Objective-C '__kindof' qualifier to
7481 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7483 /// Ensure attributes are consistent with type.
7484 /// \param [in, out] Attributes The attributes to check; they will
7485 /// be modified to be consistent with \p PropertyTy.
7486 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7488 unsigned &Attributes,
7489 bool propertyInPrimaryClass);
7491 /// Process the specified property declaration and create decls for the
7492 /// setters and getters as needed.
7493 /// \param property The property declaration being processed
7494 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7497 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7498 ObjCPropertyDecl *SuperProperty,
7499 const IdentifierInfo *Name,
7500 bool OverridingProtocolProperty);
7502 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7503 ObjCInterfaceDecl *ID);
7505 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7506 ArrayRef<Decl *> allMethods = None,
7507 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7509 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7510 SourceLocation LParenLoc,
7511 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7512 Selector GetterSel, Selector SetterSel,
7513 tok::ObjCKeywordKind MethodImplKind,
7514 DeclContext *lexicalDC = nullptr);
7516 Decl *ActOnPropertyImplDecl(Scope *S,
7517 SourceLocation AtLoc,
7518 SourceLocation PropertyLoc,
7520 IdentifierInfo *PropertyId,
7521 IdentifierInfo *PropertyIvar,
7522 SourceLocation PropertyIvarLoc,
7523 ObjCPropertyQueryKind QueryKind);
7525 enum ObjCSpecialMethodKind {
7531 OSMK_NonRetainingInit
7534 struct ObjCArgInfo {
7535 IdentifierInfo *Name;
7536 SourceLocation NameLoc;
7537 // The Type is null if no type was specified, and the DeclSpec is invalid
7540 ObjCDeclSpec DeclSpec;
7542 /// ArgAttrs - Attribute list for this argument.
7543 AttributeList *ArgAttrs;
7546 Decl *ActOnMethodDeclaration(
7548 SourceLocation BeginLoc, // location of the + or -.
7549 SourceLocation EndLoc, // location of the ; or {.
7550 tok::TokenKind MethodType,
7551 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7552 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7553 // optional arguments. The number of types/arguments is obtained
7554 // from the Sel.getNumArgs().
7555 ObjCArgInfo *ArgInfo,
7556 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7557 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7558 bool isVariadic, bool MethodDefinition);
7560 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7561 const ObjCObjectPointerType *OPT,
7563 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7566 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7567 bool inferObjCARCLifetime(ValueDecl *decl);
7570 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7572 SourceLocation OpLoc,
7573 DeclarationName MemberName,
7574 SourceLocation MemberLoc,
7575 SourceLocation SuperLoc, QualType SuperType,
7579 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7580 IdentifierInfo &propertyName,
7581 SourceLocation receiverNameLoc,
7582 SourceLocation propertyNameLoc);
7584 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7586 /// \brief Describes the kind of message expression indicated by a message
7587 /// send that starts with an identifier.
7588 enum ObjCMessageKind {
7589 /// \brief The message is sent to 'super'.
7591 /// \brief The message is an instance message.
7592 ObjCInstanceMessage,
7593 /// \brief The message is a class message, and the identifier is a type
7598 ObjCMessageKind getObjCMessageKind(Scope *S,
7599 IdentifierInfo *Name,
7600 SourceLocation NameLoc,
7602 bool HasTrailingDot,
7603 ParsedType &ReceiverType);
7605 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7607 SourceLocation LBracLoc,
7608 ArrayRef<SourceLocation> SelectorLocs,
7609 SourceLocation RBracLoc,
7612 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7613 QualType ReceiverType,
7614 SourceLocation SuperLoc,
7616 ObjCMethodDecl *Method,
7617 SourceLocation LBracLoc,
7618 ArrayRef<SourceLocation> SelectorLocs,
7619 SourceLocation RBracLoc,
7621 bool isImplicit = false);
7623 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7624 bool isSuperReceiver,
7627 ObjCMethodDecl *Method,
7630 ExprResult ActOnClassMessage(Scope *S,
7631 ParsedType Receiver,
7633 SourceLocation LBracLoc,
7634 ArrayRef<SourceLocation> SelectorLocs,
7635 SourceLocation RBracLoc,
7638 ExprResult BuildInstanceMessage(Expr *Receiver,
7639 QualType ReceiverType,
7640 SourceLocation SuperLoc,
7642 ObjCMethodDecl *Method,
7643 SourceLocation LBracLoc,
7644 ArrayRef<SourceLocation> SelectorLocs,
7645 SourceLocation RBracLoc,
7647 bool isImplicit = false);
7649 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7650 QualType ReceiverType,
7653 ObjCMethodDecl *Method,
7656 ExprResult ActOnInstanceMessage(Scope *S,
7659 SourceLocation LBracLoc,
7660 ArrayRef<SourceLocation> SelectorLocs,
7661 SourceLocation RBracLoc,
7664 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7665 ObjCBridgeCastKind Kind,
7666 SourceLocation BridgeKeywordLoc,
7667 TypeSourceInfo *TSInfo,
7670 ExprResult ActOnObjCBridgedCast(Scope *S,
7671 SourceLocation LParenLoc,
7672 ObjCBridgeCastKind Kind,
7673 SourceLocation BridgeKeywordLoc,
7675 SourceLocation RParenLoc,
7678 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7680 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7682 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7685 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7686 QualType DestType, QualType SrcType,
7687 ObjCInterfaceDecl *&RelatedClass,
7688 ObjCMethodDecl *&ClassMethod,
7689 ObjCMethodDecl *&InstanceMethod,
7690 TypedefNameDecl *&TDNDecl,
7691 bool CfToNs, bool Diagnose = true);
7693 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7694 QualType DestType, QualType SrcType,
7695 Expr *&SrcExpr, bool Diagnose = true);
7697 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7698 bool Diagnose = true);
7700 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7702 /// \brief Check whether the given new method is a valid override of the
7703 /// given overridden method, and set any properties that should be inherited.
7704 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7705 const ObjCMethodDecl *Overridden);
7707 /// \brief Describes the compatibility of a result type with its method.
7708 enum ResultTypeCompatibilityKind {
7714 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7715 ObjCInterfaceDecl *CurrentClass,
7716 ResultTypeCompatibilityKind RTC);
7718 enum PragmaOptionsAlignKind {
7719 POAK_Native, // #pragma options align=native
7720 POAK_Natural, // #pragma options align=natural
7721 POAK_Packed, // #pragma options align=packed
7722 POAK_Power, // #pragma options align=power
7723 POAK_Mac68k, // #pragma options align=mac68k
7724 POAK_Reset // #pragma options align=reset
7727 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7728 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7729 SourceLocation PragmaLoc);
7731 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7732 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
7733 StringRef SlotLabel, Expr *Alignment);
7735 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7736 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7738 /// ActOnPragmaMSComment - Called on well formed
7739 /// \#pragma comment(kind, "arg").
7740 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
7743 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7744 /// pointers_to_members(representation method[, general purpose
7745 /// representation]).
7746 void ActOnPragmaMSPointersToMembers(
7747 LangOptions::PragmaMSPointersToMembersKind Kind,
7748 SourceLocation PragmaLoc);
7750 /// \brief Called on well formed \#pragma vtordisp().
7751 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
7752 SourceLocation PragmaLoc,
7753 MSVtorDispAttr::Mode Value);
7755 enum PragmaSectionKind {
7762 bool UnifySection(StringRef SectionName,
7764 DeclaratorDecl *TheDecl);
7765 bool UnifySection(StringRef SectionName,
7767 SourceLocation PragmaSectionLocation);
7769 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7770 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7771 PragmaMsStackAction Action,
7772 llvm::StringRef StackSlotLabel,
7773 StringLiteral *SegmentName,
7774 llvm::StringRef PragmaName);
7776 /// \brief Called on well formed \#pragma section().
7777 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7778 int SectionFlags, StringLiteral *SegmentName);
7780 /// \brief Called on well-formed \#pragma init_seg().
7781 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7782 StringLiteral *SegmentName);
7784 /// \brief Called on #pragma clang __debug dump II
7785 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
7787 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7788 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
7791 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7792 void ActOnPragmaUnused(const Token &Identifier,
7794 SourceLocation PragmaLoc);
7796 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7797 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7798 SourceLocation PragmaLoc);
7800 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7801 SourceLocation Loc);
7802 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7804 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7805 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7806 SourceLocation PragmaLoc,
7807 SourceLocation WeakNameLoc);
7809 /// ActOnPragmaRedefineExtname - Called on well formed
7810 /// \#pragma redefine_extname oldname newname.
7811 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7812 IdentifierInfo* AliasName,
7813 SourceLocation PragmaLoc,
7814 SourceLocation WeakNameLoc,
7815 SourceLocation AliasNameLoc);
7817 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7818 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7819 IdentifierInfo* AliasName,
7820 SourceLocation PragmaLoc,
7821 SourceLocation WeakNameLoc,
7822 SourceLocation AliasNameLoc);
7824 /// ActOnPragmaFPContract - Called on well formed
7825 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7826 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7828 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7829 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7830 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7832 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7833 void AddMsStructLayoutForRecord(RecordDecl *RD);
7835 /// FreePackedContext - Deallocate and null out PackContext.
7836 void FreePackedContext();
7838 /// PushNamespaceVisibilityAttr - Note that we've entered a
7839 /// namespace with a visibility attribute.
7840 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7841 SourceLocation Loc);
7843 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7844 /// add an appropriate visibility attribute.
7845 void AddPushedVisibilityAttribute(Decl *RD);
7847 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7848 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7849 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7851 /// FreeVisContext - Deallocate and null out VisContext.
7852 void FreeVisContext();
7854 /// AddCFAuditedAttribute - Check whether we're currently within
7855 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7856 /// the appropriate attribute.
7857 void AddCFAuditedAttribute(Decl *D);
7859 /// \brief Called on well formed \#pragma clang optimize.
7860 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7862 /// \brief Get the location for the currently active "\#pragma clang optimize
7863 /// off". If this location is invalid, then the state of the pragma is "on".
7864 SourceLocation getOptimizeOffPragmaLocation() const {
7865 return OptimizeOffPragmaLocation;
7868 /// \brief Only called on function definitions; if there is a pragma in scope
7869 /// with the effect of a range-based optnone, consider marking the function
7870 /// with attribute optnone.
7871 void AddRangeBasedOptnone(FunctionDecl *FD);
7873 /// \brief Adds the 'optnone' attribute to the function declaration if there
7874 /// are no conflicts; Loc represents the location causing the 'optnone'
7875 /// attribute to be added (usually because of a pragma).
7876 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7878 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7879 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7880 unsigned SpellingListIndex, bool IsPackExpansion);
7881 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7882 unsigned SpellingListIndex, bool IsPackExpansion);
7884 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7886 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7887 unsigned SpellingListIndex);
7889 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7891 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7892 unsigned SpellingListIndex);
7894 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7896 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7897 Expr *MinBlocks, unsigned SpellingListIndex);
7899 /// AddModeAttr - Adds a mode attribute to a particular declaration.
7900 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
7901 unsigned SpellingListIndex, bool InInstantiation = false);
7903 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
7904 ParameterABI ABI, unsigned SpellingListIndex);
7906 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
7907 unsigned SpellingListIndex, bool isNSConsumed,
7908 bool isTemplateInstantiation);
7910 //===--------------------------------------------------------------------===//
7911 // C++ Coroutines TS
7913 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7914 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7915 StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
7917 ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
7918 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
7919 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
7921 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
7923 //===--------------------------------------------------------------------===//
7924 // OpenMP directives and clauses.
7927 void *VarDataSharingAttributesStack;
7928 /// Set to true inside '#pragma omp declare target' region.
7929 bool IsInOpenMPDeclareTargetContext = false;
7930 /// \brief Initialization of data-sharing attributes stack.
7931 void InitDataSharingAttributesStack();
7932 void DestroyDataSharingAttributesStack();
7934 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
7935 bool StrictlyPositive = true);
7936 /// Returns OpenMP nesting level for current directive.
7937 unsigned getOpenMPNestingLevel() const;
7940 /// \brief Return true if the provided declaration \a VD should be captured by
7942 /// \param Level Relative level of nested OpenMP construct for that the check
7944 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
7946 /// \brief Check if the specified variable is used in one of the private
7947 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
7949 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
7950 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7951 ExprObjectKind OK, SourceLocation Loc);
7953 /// \brief Check if the specified variable is used in 'private' clause.
7954 /// \param Level Relative level of nested OpenMP construct for that the check
7956 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
7958 /// \brief Check if the specified variable is captured by 'target' directive.
7959 /// \param Level Relative level of nested OpenMP construct for that the check
7961 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
7963 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7965 /// \brief Called on start of new data sharing attribute block.
7966 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7967 const DeclarationNameInfo &DirName, Scope *CurScope,
7968 SourceLocation Loc);
7969 /// \brief Start analysis of clauses.
7970 void StartOpenMPClause(OpenMPClauseKind K);
7971 /// \brief End analysis of clauses.
7972 void EndOpenMPClause();
7973 /// \brief Called on end of data sharing attribute block.
7974 void EndOpenMPDSABlock(Stmt *CurDirective);
7976 /// \brief Check if the current region is an OpenMP loop region and if it is,
7977 /// mark loop control variable, used in \p Init for loop initialization, as
7978 /// private by default.
7979 /// \param Init First part of the for loop.
7980 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7982 // OpenMP directives and clauses.
7983 /// \brief Called on correct id-expression from the '#pragma omp
7985 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7986 CXXScopeSpec &ScopeSpec,
7987 const DeclarationNameInfo &Id);
7988 /// \brief Called on well-formed '#pragma omp threadprivate'.
7989 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7991 ArrayRef<Expr *> VarList);
7992 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7993 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7995 ArrayRef<Expr *> VarList);
7996 /// \brief Check if the specified type is allowed to be used in 'omp declare
7997 /// reduction' construct.
7998 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
7999 TypeResult ParsedType);
8000 /// \brief Called on start of '#pragma omp declare reduction'.
8001 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8002 Scope *S, DeclContext *DC, DeclarationName Name,
8003 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8004 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8005 /// \brief Initialize declare reduction construct initializer.
8006 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8007 /// \brief Finish current declare reduction construct initializer.
8008 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8009 /// \brief Initialize declare reduction construct initializer.
8010 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8011 /// \brief Finish current declare reduction construct initializer.
8012 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8013 /// \brief Called at the end of '#pragma omp declare reduction'.
8014 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8015 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8017 /// Called on the start of target region i.e. '#pragma omp declare target'.
8018 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8019 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8020 void ActOnFinishOpenMPDeclareTargetDirective();
8021 /// Called on correct id-expression from the '#pragma omp declare target'.
8022 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8023 const DeclarationNameInfo &Id,
8024 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8025 NamedDeclSetType &SameDirectiveDecls);
8026 /// Check declaration inside target region.
8027 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8028 /// Return true inside OpenMP target region.
8029 bool isInOpenMPDeclareTargetContext() const {
8030 return IsInOpenMPDeclareTargetContext;
8033 /// \brief Initialization of captured region for OpenMP region.
8034 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8035 /// \brief End of OpenMP region.
8037 /// \param S Statement associated with the current OpenMP region.
8038 /// \param Clauses List of clauses for the current OpenMP region.
8040 /// \returns Statement for finished OpenMP region.
8041 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8042 StmtResult ActOnOpenMPExecutableDirective(
8043 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8044 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8045 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8046 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8047 /// of the associated statement.
8048 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8050 SourceLocation StartLoc,
8051 SourceLocation EndLoc);
8052 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8053 /// of the associated statement.
8054 StmtResult ActOnOpenMPSimdDirective(
8055 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8056 SourceLocation EndLoc,
8057 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8058 /// \brief Called on well-formed '\#pragma omp for' after parsing
8059 /// of the associated statement.
8060 StmtResult ActOnOpenMPForDirective(
8061 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8062 SourceLocation EndLoc,
8063 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8064 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8065 /// of the associated statement.
8066 StmtResult ActOnOpenMPForSimdDirective(
8067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8068 SourceLocation EndLoc,
8069 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8070 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8071 /// of the associated statement.
8072 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8073 Stmt *AStmt, SourceLocation StartLoc,
8074 SourceLocation EndLoc);
8075 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8076 /// associated statement.
8077 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8078 SourceLocation EndLoc);
8079 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8080 /// associated statement.
8081 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8082 Stmt *AStmt, SourceLocation StartLoc,
8083 SourceLocation EndLoc);
8084 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8085 /// associated statement.
8086 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8087 SourceLocation EndLoc);
8088 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8089 /// associated statement.
8090 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8091 ArrayRef<OMPClause *> Clauses,
8092 Stmt *AStmt, SourceLocation StartLoc,
8093 SourceLocation EndLoc);
8094 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8095 /// of the associated statement.
8096 StmtResult ActOnOpenMPParallelForDirective(
8097 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8098 SourceLocation EndLoc,
8099 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8100 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8101 /// parsing of the associated statement.
8102 StmtResult ActOnOpenMPParallelForSimdDirective(
8103 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8104 SourceLocation EndLoc,
8105 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8106 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8107 /// parsing of the associated statement.
8108 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8110 SourceLocation StartLoc,
8111 SourceLocation EndLoc);
8112 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8113 /// associated statement.
8114 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8115 Stmt *AStmt, SourceLocation StartLoc,
8116 SourceLocation EndLoc);
8117 /// \brief Called on well-formed '\#pragma omp taskyield'.
8118 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8119 SourceLocation EndLoc);
8120 /// \brief Called on well-formed '\#pragma omp barrier'.
8121 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8122 SourceLocation EndLoc);
8123 /// \brief Called on well-formed '\#pragma omp taskwait'.
8124 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8125 SourceLocation EndLoc);
8126 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8127 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8128 SourceLocation EndLoc);
8129 /// \brief Called on well-formed '\#pragma omp flush'.
8130 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8131 SourceLocation StartLoc,
8132 SourceLocation EndLoc);
8133 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8134 /// associated statement.
8135 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8136 Stmt *AStmt, SourceLocation StartLoc,
8137 SourceLocation EndLoc);
8138 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8139 /// associated statement.
8140 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8141 Stmt *AStmt, SourceLocation StartLoc,
8142 SourceLocation EndLoc);
8143 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8144 /// associated statement.
8145 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8146 Stmt *AStmt, SourceLocation StartLoc,
8147 SourceLocation EndLoc);
8148 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8149 /// the associated statement.
8150 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8151 Stmt *AStmt, SourceLocation StartLoc,
8152 SourceLocation EndLoc);
8153 /// \brief Called on well-formed '\#pragma omp target enter data' after
8154 /// parsing of the associated statement.
8155 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8156 SourceLocation StartLoc,
8157 SourceLocation EndLoc);
8158 /// \brief Called on well-formed '\#pragma omp target exit data' after
8159 /// parsing of the associated statement.
8160 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8161 SourceLocation StartLoc,
8162 SourceLocation EndLoc);
8163 /// \brief Called on well-formed '\#pragma omp target parallel' after
8164 /// parsing of the associated statement.
8165 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8167 SourceLocation StartLoc,
8168 SourceLocation EndLoc);
8169 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8170 /// parsing of the associated statement.
8171 StmtResult ActOnOpenMPTargetParallelForDirective(
8172 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8173 SourceLocation EndLoc,
8174 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8175 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8176 /// associated statement.
8177 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8178 Stmt *AStmt, SourceLocation StartLoc,
8179 SourceLocation EndLoc);
8180 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8182 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8183 SourceLocation EndLoc,
8184 OpenMPDirectiveKind CancelRegion);
8185 /// \brief Called on well-formed '\#pragma omp cancel'.
8186 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8187 SourceLocation StartLoc,
8188 SourceLocation EndLoc,
8189 OpenMPDirectiveKind CancelRegion);
8190 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8191 /// associated statement.
8192 StmtResult ActOnOpenMPTaskLoopDirective(
8193 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8194 SourceLocation EndLoc,
8195 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8196 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8197 /// the associated statement.
8198 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8199 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8200 SourceLocation EndLoc,
8201 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8202 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8203 /// of the associated statement.
8204 StmtResult ActOnOpenMPDistributeDirective(
8205 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8206 SourceLocation EndLoc,
8207 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8208 /// \brief Called on well-formed '\#pragma omp target update'.
8209 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8210 SourceLocation StartLoc,
8211 SourceLocation EndLoc);
8212 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8213 /// parsing of the associated statement.
8214 StmtResult ActOnOpenMPDistributeParallelForDirective(
8215 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8216 SourceLocation EndLoc,
8217 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8218 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8219 /// after parsing of the associated statement.
8220 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8221 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8222 SourceLocation EndLoc,
8223 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8224 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8225 /// parsing of the associated statement.
8226 StmtResult ActOnOpenMPDistributeSimdDirective(
8227 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8228 SourceLocation EndLoc,
8229 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8230 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8231 /// parsing of the associated statement.
8232 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8233 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8234 SourceLocation EndLoc,
8235 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8237 /// Checks correctness of linear modifiers.
8238 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8239 SourceLocation LinLoc);
8240 /// Checks that the specified declaration matches requirements for the linear
8242 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8243 OpenMPLinearClauseKind LinKind, QualType Type);
8245 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8246 /// the associated method/function.
8247 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8248 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8249 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8250 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8251 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8253 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8255 SourceLocation StartLoc,
8256 SourceLocation LParenLoc,
8257 SourceLocation EndLoc);
8258 /// \brief Called on well-formed 'if' clause.
8259 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8260 Expr *Condition, SourceLocation StartLoc,
8261 SourceLocation LParenLoc,
8262 SourceLocation NameModifierLoc,
8263 SourceLocation ColonLoc,
8264 SourceLocation EndLoc);
8265 /// \brief Called on well-formed 'final' clause.
8266 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8267 SourceLocation LParenLoc,
8268 SourceLocation EndLoc);
8269 /// \brief Called on well-formed 'num_threads' clause.
8270 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8271 SourceLocation StartLoc,
8272 SourceLocation LParenLoc,
8273 SourceLocation EndLoc);
8274 /// \brief Called on well-formed 'safelen' clause.
8275 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8276 SourceLocation StartLoc,
8277 SourceLocation LParenLoc,
8278 SourceLocation EndLoc);
8279 /// \brief Called on well-formed 'simdlen' clause.
8280 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8281 SourceLocation LParenLoc,
8282 SourceLocation EndLoc);
8283 /// \brief Called on well-formed 'collapse' clause.
8284 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8285 SourceLocation StartLoc,
8286 SourceLocation LParenLoc,
8287 SourceLocation EndLoc);
8288 /// \brief Called on well-formed 'ordered' clause.
8290 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8291 SourceLocation LParenLoc = SourceLocation(),
8292 Expr *NumForLoops = nullptr);
8293 /// \brief Called on well-formed 'grainsize' clause.
8294 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8295 SourceLocation LParenLoc,
8296 SourceLocation EndLoc);
8297 /// \brief Called on well-formed 'num_tasks' clause.
8298 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8299 SourceLocation LParenLoc,
8300 SourceLocation EndLoc);
8301 /// \brief Called on well-formed 'hint' clause.
8302 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8303 SourceLocation LParenLoc,
8304 SourceLocation EndLoc);
8306 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8308 SourceLocation ArgumentLoc,
8309 SourceLocation StartLoc,
8310 SourceLocation LParenLoc,
8311 SourceLocation EndLoc);
8312 /// \brief Called on well-formed 'default' clause.
8313 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8314 SourceLocation KindLoc,
8315 SourceLocation StartLoc,
8316 SourceLocation LParenLoc,
8317 SourceLocation EndLoc);
8318 /// \brief Called on well-formed 'proc_bind' clause.
8319 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8320 SourceLocation KindLoc,
8321 SourceLocation StartLoc,
8322 SourceLocation LParenLoc,
8323 SourceLocation EndLoc);
8325 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8326 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8327 SourceLocation StartLoc, SourceLocation LParenLoc,
8328 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8329 SourceLocation EndLoc);
8330 /// \brief Called on well-formed 'schedule' clause.
8331 OMPClause *ActOnOpenMPScheduleClause(
8332 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8333 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8334 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8335 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8337 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8338 SourceLocation EndLoc);
8339 /// \brief Called on well-formed 'nowait' clause.
8340 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8341 SourceLocation EndLoc);
8342 /// \brief Called on well-formed 'untied' clause.
8343 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8344 SourceLocation EndLoc);
8345 /// \brief Called on well-formed 'mergeable' clause.
8346 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8347 SourceLocation EndLoc);
8348 /// \brief Called on well-formed 'read' clause.
8349 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8350 SourceLocation EndLoc);
8351 /// \brief Called on well-formed 'write' clause.
8352 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8353 SourceLocation EndLoc);
8354 /// \brief Called on well-formed 'update' clause.
8355 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8356 SourceLocation EndLoc);
8357 /// \brief Called on well-formed 'capture' clause.
8358 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8359 SourceLocation EndLoc);
8360 /// \brief Called on well-formed 'seq_cst' clause.
8361 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8362 SourceLocation EndLoc);
8363 /// \brief Called on well-formed 'threads' clause.
8364 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8365 SourceLocation EndLoc);
8366 /// \brief Called on well-formed 'simd' clause.
8367 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8368 SourceLocation EndLoc);
8369 /// \brief Called on well-formed 'nogroup' clause.
8370 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8371 SourceLocation EndLoc);
8373 OMPClause *ActOnOpenMPVarListClause(
8374 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8375 SourceLocation StartLoc, SourceLocation LParenLoc,
8376 SourceLocation ColonLoc, SourceLocation EndLoc,
8377 CXXScopeSpec &ReductionIdScopeSpec,
8378 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8379 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8380 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8381 SourceLocation DepLinMapLoc);
8382 /// \brief Called on well-formed 'private' clause.
8383 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8384 SourceLocation StartLoc,
8385 SourceLocation LParenLoc,
8386 SourceLocation EndLoc);
8387 /// \brief Called on well-formed 'firstprivate' clause.
8388 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8389 SourceLocation StartLoc,
8390 SourceLocation LParenLoc,
8391 SourceLocation EndLoc);
8392 /// \brief Called on well-formed 'lastprivate' clause.
8393 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8394 SourceLocation StartLoc,
8395 SourceLocation LParenLoc,
8396 SourceLocation EndLoc);
8397 /// \brief Called on well-formed 'shared' clause.
8398 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8399 SourceLocation StartLoc,
8400 SourceLocation LParenLoc,
8401 SourceLocation EndLoc);
8402 /// \brief Called on well-formed 'reduction' clause.
8403 OMPClause *ActOnOpenMPReductionClause(
8404 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8405 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8406 CXXScopeSpec &ReductionIdScopeSpec,
8407 const DeclarationNameInfo &ReductionId,
8408 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8409 /// \brief Called on well-formed 'linear' clause.
8411 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8412 SourceLocation StartLoc, SourceLocation LParenLoc,
8413 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8414 SourceLocation ColonLoc, SourceLocation EndLoc);
8415 /// \brief Called on well-formed 'aligned' clause.
8416 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8418 SourceLocation StartLoc,
8419 SourceLocation LParenLoc,
8420 SourceLocation ColonLoc,
8421 SourceLocation EndLoc);
8422 /// \brief Called on well-formed 'copyin' clause.
8423 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8424 SourceLocation StartLoc,
8425 SourceLocation LParenLoc,
8426 SourceLocation EndLoc);
8427 /// \brief Called on well-formed 'copyprivate' clause.
8428 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8429 SourceLocation StartLoc,
8430 SourceLocation LParenLoc,
8431 SourceLocation EndLoc);
8432 /// \brief Called on well-formed 'flush' pseudo clause.
8433 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8434 SourceLocation StartLoc,
8435 SourceLocation LParenLoc,
8436 SourceLocation EndLoc);
8437 /// \brief Called on well-formed 'depend' clause.
8439 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8440 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8441 SourceLocation StartLoc, SourceLocation LParenLoc,
8442 SourceLocation EndLoc);
8443 /// \brief Called on well-formed 'device' clause.
8444 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8445 SourceLocation LParenLoc,
8446 SourceLocation EndLoc);
8447 /// \brief Called on well-formed 'map' clause.
8449 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8450 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8451 SourceLocation MapLoc, SourceLocation ColonLoc,
8452 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8453 SourceLocation LParenLoc, SourceLocation EndLoc);
8454 /// \brief Called on well-formed 'num_teams' clause.
8455 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8456 SourceLocation LParenLoc,
8457 SourceLocation EndLoc);
8458 /// \brief Called on well-formed 'thread_limit' clause.
8459 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8460 SourceLocation StartLoc,
8461 SourceLocation LParenLoc,
8462 SourceLocation EndLoc);
8463 /// \brief Called on well-formed 'priority' clause.
8464 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8465 SourceLocation LParenLoc,
8466 SourceLocation EndLoc);
8467 /// \brief Called on well-formed 'dist_schedule' clause.
8468 OMPClause *ActOnOpenMPDistScheduleClause(
8469 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8470 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8471 SourceLocation CommaLoc, SourceLocation EndLoc);
8472 /// \brief Called on well-formed 'defaultmap' clause.
8473 OMPClause *ActOnOpenMPDefaultmapClause(
8474 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8475 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8476 SourceLocation KindLoc, SourceLocation EndLoc);
8477 /// \brief Called on well-formed 'to' clause.
8478 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8479 SourceLocation StartLoc,
8480 SourceLocation LParenLoc,
8481 SourceLocation EndLoc);
8482 /// \brief Called on well-formed 'from' clause.
8483 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8484 SourceLocation StartLoc,
8485 SourceLocation LParenLoc,
8486 SourceLocation EndLoc);
8487 /// Called on well-formed 'use_device_ptr' clause.
8488 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8489 SourceLocation StartLoc,
8490 SourceLocation LParenLoc,
8491 SourceLocation EndLoc);
8492 /// Called on well-formed 'is_device_ptr' clause.
8493 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8494 SourceLocation StartLoc,
8495 SourceLocation LParenLoc,
8496 SourceLocation EndLoc);
8498 /// \brief The kind of conversion being performed.
8499 enum CheckedConversionKind {
8500 /// \brief An implicit conversion.
8501 CCK_ImplicitConversion,
8502 /// \brief A C-style cast.
8504 /// \brief A functional-style cast.
8506 /// \brief A cast other than a C-style cast.
8510 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8511 /// cast. If there is already an implicit cast, merge into the existing one.
8512 /// If isLvalue, the result of the cast is an lvalue.
8513 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8514 ExprValueKind VK = VK_RValue,
8515 const CXXCastPath *BasePath = nullptr,
8516 CheckedConversionKind CCK
8517 = CCK_ImplicitConversion);
8519 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8520 /// to the conversion from scalar type ScalarTy to the Boolean type.
8521 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8523 /// IgnoredValueConversions - Given that an expression's result is
8524 /// syntactically ignored, perform any conversions that are
8526 ExprResult IgnoredValueConversions(Expr *E);
8528 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8529 // functions and arrays to their respective pointers (C99 6.3.2.1).
8530 ExprResult UsualUnaryConversions(Expr *E);
8532 /// CallExprUnaryConversions - a special case of an unary conversion
8533 /// performed on a function designator of a call expression.
8534 ExprResult CallExprUnaryConversions(Expr *E);
8536 // DefaultFunctionArrayConversion - converts functions and arrays
8537 // to their respective pointers (C99 6.3.2.1).
8538 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8540 // DefaultFunctionArrayLvalueConversion - converts functions and
8541 // arrays to their respective pointers and performs the
8542 // lvalue-to-rvalue conversion.
8543 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8544 bool Diagnose = true);
8546 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8547 // the operand. This is DefaultFunctionArrayLvalueConversion,
8548 // except that it assumes the operand isn't of function or array
8550 ExprResult DefaultLvalueConversion(Expr *E);
8552 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8553 // do not have a prototype. Integer promotions are performed on each
8554 // argument, and arguments that have type float are promoted to double.
8555 ExprResult DefaultArgumentPromotion(Expr *E);
8557 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8558 enum VariadicCallType {
8562 VariadicConstructor,
8563 VariadicDoesNotApply
8566 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8567 const FunctionProtoType *Proto,
8570 // Used for determining in which context a type is allowed to be passed to a
8580 // Determines which VarArgKind fits an expression.
8581 VarArgKind isValidVarArgType(const QualType &Ty);
8583 /// Check to see if the given expression is a valid argument to a variadic
8584 /// function, issuing a diagnostic if not.
8585 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8587 /// Check to see if a given expression could have '.c_str()' called on it.
8588 bool hasCStrMethod(const Expr *E);
8590 /// GatherArgumentsForCall - Collector argument expressions for various
8591 /// form of call prototypes.
8592 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8593 const FunctionProtoType *Proto,
8594 unsigned FirstParam, ArrayRef<Expr *> Args,
8595 SmallVectorImpl<Expr *> &AllArgs,
8596 VariadicCallType CallType = VariadicDoesNotApply,
8597 bool AllowExplicit = false,
8598 bool IsListInitialization = false);
8600 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8601 // will create a runtime trap if the resulting type is not a POD type.
8602 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8603 FunctionDecl *FDecl);
8605 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8606 // operands and then handles various conversions that are common to binary
8607 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8608 // routine returns the first non-arithmetic type found. The client is
8609 // responsible for emitting appropriate error diagnostics.
8610 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8611 bool IsCompAssign = false);
8613 /// AssignConvertType - All of the 'assignment' semantic checks return this
8614 /// enum to indicate whether the assignment was allowed. These checks are
8615 /// done for simple assignments, as well as initialization, return from
8616 /// function, argument passing, etc. The query is phrased in terms of a
8617 /// source and destination type.
8618 enum AssignConvertType {
8619 /// Compatible - the types are compatible according to the standard.
8622 /// PointerToInt - The assignment converts a pointer to an int, which we
8623 /// accept as an extension.
8626 /// IntToPointer - The assignment converts an int to a pointer, which we
8627 /// accept as an extension.
8630 /// FunctionVoidPointer - The assignment is between a function pointer and
8631 /// void*, which the standard doesn't allow, but we accept as an extension.
8632 FunctionVoidPointer,
8634 /// IncompatiblePointer - The assignment is between two pointers types that
8635 /// are not compatible, but we accept them as an extension.
8636 IncompatiblePointer,
8638 /// IncompatiblePointer - The assignment is between two pointers types which
8639 /// point to integers which have a different sign, but are otherwise
8640 /// identical. This is a subset of the above, but broken out because it's by
8641 /// far the most common case of incompatible pointers.
8642 IncompatiblePointerSign,
8644 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8645 /// c/v/r qualifiers, which we accept as an extension.
8646 CompatiblePointerDiscardsQualifiers,
8648 /// IncompatiblePointerDiscardsQualifiers - The assignment
8649 /// discards qualifiers that we don't permit to be discarded,
8650 /// like address spaces.
8651 IncompatiblePointerDiscardsQualifiers,
8653 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8654 /// nested pointer types, and the qualifiers other than the first two
8655 /// levels differ e.g. char ** -> const char **, but we accept them as an
8657 IncompatibleNestedPointerQualifiers,
8659 /// IncompatibleVectors - The assignment is between two vector types that
8660 /// have the same size, which we accept as an extension.
8661 IncompatibleVectors,
8663 /// IntToBlockPointer - The assignment converts an int to a block
8664 /// pointer. We disallow this.
8667 /// IncompatibleBlockPointer - The assignment is between two block
8668 /// pointers types that are not compatible.
8669 IncompatibleBlockPointer,
8671 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8672 /// id type and something else (that is incompatible with it). For example,
8673 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8674 IncompatibleObjCQualifiedId,
8676 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8677 /// object with __weak qualifier.
8678 IncompatibleObjCWeakRef,
8680 /// Incompatible - We reject this conversion outright, it is invalid to
8681 /// represent it in the AST.
8685 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8686 /// assignment conversion type specified by ConvTy. This returns true if the
8687 /// conversion was invalid or false if the conversion was accepted.
8688 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8690 QualType DstType, QualType SrcType,
8691 Expr *SrcExpr, AssignmentAction Action,
8692 bool *Complained = nullptr);
8694 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8695 /// enum. If AllowMask is true, then we also allow the complement of a valid
8696 /// value, to be used as a mask.
8697 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8698 bool AllowMask) const;
8700 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8701 /// integer not in the range of enum values.
8702 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8705 /// CheckAssignmentConstraints - Perform type checking for assignment,
8706 /// argument passing, variable initialization, and function return values.
8708 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8712 /// Check assignment constraints and optionally prepare for a conversion of
8713 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8715 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8718 bool ConvertRHS = true);
8720 // CheckSingleAssignmentConstraints - Currently used by
8721 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8722 // this routine performs the default function/array converions, if ConvertRHS
8724 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8726 bool Diagnose = true,
8727 bool DiagnoseCFAudited = false,
8728 bool ConvertRHS = true);
8730 // \brief If the lhs type is a transparent union, check whether we
8731 // can initialize the transparent union with the given expression.
8732 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8735 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8737 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8739 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8740 AssignmentAction Action,
8741 bool AllowExplicit = false);
8742 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8743 AssignmentAction Action,
8745 ImplicitConversionSequence& ICS);
8746 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8747 const ImplicitConversionSequence& ICS,
8748 AssignmentAction Action,
8749 CheckedConversionKind CCK
8750 = CCK_ImplicitConversion);
8751 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8752 const StandardConversionSequence& SCS,
8753 AssignmentAction Action,
8754 CheckedConversionKind CCK);
8756 /// the following "Check" methods will return a valid/converted QualType
8757 /// or a null QualType (indicating an error diagnostic was issued).
8759 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8760 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8762 QualType CheckPointerToMemberOperands( // C++ 5.5
8763 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8764 SourceLocation OpLoc, bool isIndirect);
8765 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8766 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8768 QualType CheckRemainderOperands( // C99 6.5.5
8769 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8770 bool IsCompAssign = false);
8771 QualType CheckAdditionOperands( // C99 6.5.6
8772 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8773 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
8774 QualType CheckSubtractionOperands( // C99 6.5.6
8775 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8776 QualType* CompLHSTy = nullptr);
8777 QualType CheckShiftOperands( // C99 6.5.7
8778 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8779 BinaryOperatorKind Opc, bool IsCompAssign = false);
8780 QualType CheckCompareOperands( // C99 6.5.8/9
8781 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8782 BinaryOperatorKind Opc, bool isRelational);
8783 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8784 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8785 bool IsCompAssign = false);
8786 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8787 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8788 BinaryOperatorKind Opc);
8789 // CheckAssignmentOperands is used for both simple and compound assignment.
8790 // For simple assignment, pass both expressions and a null converted type.
8791 // For compound assignment, pass both expressions and the converted type.
8792 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8793 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8795 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8796 UnaryOperatorKind Opcode, Expr *Op);
8797 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8798 BinaryOperatorKind Opcode,
8799 Expr *LHS, Expr *RHS);
8800 ExprResult checkPseudoObjectRValue(Expr *E);
8801 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8803 QualType CheckConditionalOperands( // C99 6.5.15
8804 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8805 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8806 QualType CXXCheckConditionalOperands( // C++ 5.16
8807 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8808 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8809 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8810 bool *NonStandardCompositeType = nullptr);
8811 QualType FindCompositePointerType(SourceLocation Loc,
8812 ExprResult &E1, ExprResult &E2,
8813 bool *NonStandardCompositeType = nullptr) {
8814 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8815 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8816 NonStandardCompositeType);
8822 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8823 SourceLocation QuestionLoc);
8825 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8826 SourceLocation QuestionLoc);
8828 void DiagnoseAlwaysNonNullPointer(Expr *E,
8829 Expr::NullPointerConstantKind NullType,
8830 bool IsEqual, SourceRange Range);
8832 /// type checking for vector binary operators.
8833 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8834 SourceLocation Loc, bool IsCompAssign,
8835 bool AllowBothBool, bool AllowBoolConversion);
8836 QualType GetSignedVectorType(QualType V);
8837 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8838 SourceLocation Loc, bool isRelational);
8839 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8840 SourceLocation Loc);
8842 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8843 bool isLaxVectorConversion(QualType srcType, QualType destType);
8845 /// type checking declaration initializers (C99 6.7.8)
8846 bool CheckForConstantInitializer(Expr *e, QualType t);
8848 // type checking C++ declaration initializers (C++ [dcl.init]).
8850 /// ReferenceCompareResult - Expresses the result of comparing two
8851 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8852 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8853 enum ReferenceCompareResult {
8854 /// Ref_Incompatible - The two types are incompatible, so direct
8855 /// reference binding is not possible.
8856 Ref_Incompatible = 0,
8857 /// Ref_Related - The two types are reference-related, which means
8858 /// that their unqualified forms (T1 and T2) are either the same
8859 /// or T1 is a base class of T2.
8861 /// Ref_Compatible_With_Added_Qualification - The two types are
8862 /// reference-compatible with added qualification, meaning that
8863 /// they are reference-compatible and the qualifiers on T1 (cv1)
8864 /// are greater than the qualifiers on T2 (cv2).
8865 Ref_Compatible_With_Added_Qualification,
8866 /// Ref_Compatible - The two types are reference-compatible and
8867 /// have equivalent qualifiers (cv1 == cv2).
8871 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8872 QualType T1, QualType T2,
8873 bool &DerivedToBase,
8874 bool &ObjCConversion,
8875 bool &ObjCLifetimeConversion);
8877 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8878 Expr *CastExpr, CastKind &CastKind,
8879 ExprValueKind &VK, CXXCastPath &Path);
8881 /// \brief Force an expression with unknown-type to an expression of the
8883 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8885 /// \brief Type-check an expression that's being passed to an
8886 /// __unknown_anytype parameter.
8887 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8888 Expr *result, QualType ¶mType);
8890 // CheckVectorCast - check type constraints for vectors.
8891 // Since vectors are an extension, there are no C standard reference for this.
8892 // We allow casting between vectors and integer datatypes of the same size.
8893 // returns true if the cast is invalid
8894 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8897 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
8898 /// implicit casts if necessary.
8899 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8901 // CheckExtVectorCast - check type constraints for extended vectors.
8902 // Since vectors are an extension, there are no C standard reference for this.
8903 // We allow casting between vectors and integer datatypes of the same size,
8904 // or vectors and the element type of that vector.
8905 // returns the cast expr
8906 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8909 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8910 SourceLocation LParenLoc,
8912 SourceLocation RParenLoc);
8914 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
8916 /// \brief Checks for invalid conversions and casts between
8917 /// retainable pointers and other pointer kinds.
8918 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8919 QualType castType, Expr *&op,
8920 CheckedConversionKind CCK,
8921 bool Diagnose = true,
8922 bool DiagnoseCFAudited = false,
8923 BinaryOperatorKind Opc = BO_PtrMemD
8926 Expr *stripARCUnbridgedCast(Expr *e);
8927 void diagnoseARCUnbridgedCast(Expr *e);
8929 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8932 /// checkRetainCycles - Check whether an Objective-C message send
8933 /// might create an obvious retain cycle.
8934 void checkRetainCycles(ObjCMessageExpr *msg);
8935 void checkRetainCycles(Expr *receiver, Expr *argument);
8936 void checkRetainCycles(VarDecl *Var, Expr *Init);
8938 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8939 /// to weak/__unsafe_unretained type.
8940 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8942 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8943 /// to weak/__unsafe_unretained expression.
8944 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8946 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8947 /// \param Method - May be null.
8948 /// \param [out] ReturnType - The return type of the send.
8949 /// \return true iff there were any incompatible types.
8950 bool CheckMessageArgumentTypes(QualType ReceiverType,
8951 MultiExprArg Args, Selector Sel,
8952 ArrayRef<SourceLocation> SelectorLocs,
8953 ObjCMethodDecl *Method, bool isClassMessage,
8954 bool isSuperMessage,
8955 SourceLocation lbrac, SourceLocation rbrac,
8956 SourceRange RecRange,
8957 QualType &ReturnType, ExprValueKind &VK);
8959 /// \brief Determine the result of a message send expression based on
8960 /// the type of the receiver, the method expected to receive the message,
8961 /// and the form of the message send.
8962 QualType getMessageSendResultType(QualType ReceiverType,
8963 ObjCMethodDecl *Method,
8964 bool isClassMessage, bool isSuperMessage);
8966 /// \brief If the given expression involves a message send to a method
8967 /// with a related result type, emit a note describing what happened.
8968 void EmitRelatedResultTypeNote(const Expr *E);
8970 /// \brief Given that we had incompatible pointer types in a return
8971 /// statement, check whether we're in a method with a related result
8972 /// type, and if so, emit a note describing what happened.
8973 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8975 class ConditionResult {
8977 FullExprArg Condition;
8983 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
8985 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
8986 HasKnownValue(IsConstexpr && Condition.get() &&
8987 !Condition.get()->isValueDependent()),
8988 KnownValue(HasKnownValue &&
8989 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
8990 explicit ConditionResult(bool Invalid)
8991 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
8992 HasKnownValue(false), KnownValue(false) {}
8995 ConditionResult() : ConditionResult(false) {}
8996 bool isInvalid() const { return Invalid; }
8997 std::pair<VarDecl *, Expr *> get() const {
8998 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9001 llvm::Optional<bool> getKnownValue() const {
9007 static ConditionResult ConditionError() { return ConditionResult(true); }
9009 enum class ConditionKind {
9010 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9011 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9012 Switch ///< An integral condition for a 'switch' statement.
9015 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9016 Expr *SubExpr, ConditionKind CK);
9018 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9019 SourceLocation StmtLoc,
9022 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9024 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9025 SourceLocation StmtLoc,
9027 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9029 /// CheckBooleanCondition - Diagnose problems involving the use of
9030 /// the given expression as a boolean condition (e.g. in an if
9031 /// statement). Also performs the standard function and array
9032 /// decays, possibly changing the input variable.
9034 /// \param Loc - A location associated with the condition, e.g. the
9036 /// \return true iff there were any errors
9037 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9038 bool IsConstexpr = false);
9040 /// DiagnoseAssignmentAsCondition - Given that an expression is
9041 /// being used as a boolean condition, warn if it's an assignment.
9042 void DiagnoseAssignmentAsCondition(Expr *E);
9044 /// \brief Redundant parentheses over an equality comparison can indicate
9045 /// that the user intended an assignment used as condition.
9046 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9048 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9049 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9051 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9052 /// the specified width and sign. If an overflow occurs, detect it and emit
9053 /// the specified diagnostic.
9054 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9055 unsigned NewWidth, bool NewSign,
9056 SourceLocation Loc, unsigned DiagID);
9058 /// Checks that the Objective-C declaration is declared in the global scope.
9059 /// Emits an error and marks the declaration as invalid if it's not declared
9060 /// in the global scope.
9061 bool CheckObjCDeclScope(Decl *D);
9063 /// \brief Abstract base class used for diagnosing integer constant
9064 /// expression violations.
9065 class VerifyICEDiagnoser {
9069 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9071 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9072 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9073 virtual ~VerifyICEDiagnoser() { }
9076 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9077 /// and reports the appropriate diagnostics. Returns false on success.
9078 /// Can optionally return the value of the expression.
9079 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9080 VerifyICEDiagnoser &Diagnoser,
9081 bool AllowFold = true);
9082 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9084 bool AllowFold = true);
9085 ExprResult VerifyIntegerConstantExpression(Expr *E,
9086 llvm::APSInt *Result = nullptr);
9088 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9089 /// the correct width, and that the field type is valid.
9090 /// Returns false on success.
9091 /// Can optionally return whether the bit-field is of width 0
9092 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9093 QualType FieldTy, bool IsMsStruct,
9094 Expr *BitWidth, bool *ZeroWidth = nullptr);
9096 enum CUDAFunctionTarget {
9104 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
9106 // CUDA function call preference. Must be ordered numerically from
9108 enum CUDAFunctionPreference {
9109 CFP_Never, // Invalid caller/callee combination.
9110 CFP_WrongSide, // Calls from host-device to host or device
9111 // function that do not match current compilation
9112 // mode. Only in effect if
9113 // LangOpts.CUDADisableTargetCallChecks is true.
9114 CFP_HostDevice, // Any calls to host/device functions.
9115 CFP_SameSide, // Calls from host-device to host or device
9116 // function matching current compilation mode.
9117 CFP_Native, // host-to-host or device-to-device calls.
9120 /// Identifies relative preference of a given Caller/Callee
9121 /// combination, based on their host/device attributes.
9122 /// \param Caller function which needs address of \p Callee.
9123 /// nullptr in case of global context.
9124 /// \param Callee target function
9126 /// \returns preference value for particular Caller/Callee combination.
9127 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9128 const FunctionDecl *Callee);
9130 /// Determines whether Caller may invoke Callee, based on their CUDA
9131 /// host/device attributes. Returns true if the call is not allowed.
9132 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
9133 return IdentifyCUDAPreference(Caller, Callee) == CFP_Never;
9136 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9137 /// depending on FD and the current compilation settings.
9138 void maybeAddCUDAHostDeviceAttrs(Scope *S, FunctionDecl *FD,
9139 const LookupResult &Previous);
9141 /// Finds a function in \p Matches with highest calling priority
9142 /// from \p Caller context and erases all functions with lower
9143 /// calling priority.
9144 void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9145 SmallVectorImpl<FunctionDecl *> &Matches);
9146 void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9147 SmallVectorImpl<DeclAccessPair> &Matches);
9148 void EraseUnwantedCUDAMatches(
9149 const FunctionDecl *Caller,
9150 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9152 /// Given a implicit special member, infer its CUDA target from the
9153 /// calls it needs to make to underlying base/field special members.
9154 /// \param ClassDecl the class for which the member is being created.
9155 /// \param CSM the kind of special member.
9156 /// \param MemberDecl the special member itself.
9157 /// \param ConstRHS true if this is a copy operation with a const object on
9159 /// \param Diagnose true if this call should emit diagnostics.
9160 /// \return true if there was an error inferring.
9161 /// The result of this call is implicit CUDA target attribute(s) attached to
9162 /// the member declaration.
9163 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9164 CXXSpecialMember CSM,
9165 CXXMethodDecl *MemberDecl,
9169 /// \return true if \p CD can be considered empty according to CUDA
9170 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9171 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9172 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9174 /// \name Code completion
9176 /// \brief Describes the context in which code completion occurs.
9177 enum ParserCompletionContext {
9178 /// \brief Code completion occurs at top-level or namespace context.
9180 /// \brief Code completion occurs within a class, struct, or union.
9182 /// \brief Code completion occurs within an Objective-C interface, protocol,
9185 /// \brief Code completion occurs within an Objective-C implementation or
9186 /// category implementation
9187 PCC_ObjCImplementation,
9188 /// \brief Code completion occurs within the list of instance variables
9189 /// in an Objective-C interface, protocol, category, or implementation.
9190 PCC_ObjCInstanceVariableList,
9191 /// \brief Code completion occurs following one or more template
9194 /// \brief Code completion occurs following one or more template
9195 /// headers within a class.
9197 /// \brief Code completion occurs within an expression.
9199 /// \brief Code completion occurs within a statement, which may
9200 /// also be an expression or a declaration.
9202 /// \brief Code completion occurs at the beginning of the
9203 /// initialization statement (or expression) in a for loop.
9205 /// \brief Code completion occurs within the condition of an if,
9206 /// while, switch, or for statement.
9208 /// \brief Code completion occurs within the body of a function on a
9209 /// recovery path, where we do not have a specific handle on our position
9211 PCC_RecoveryInFunction,
9212 /// \brief Code completion occurs where only a type is permitted.
9214 /// \brief Code completion occurs in a parenthesized expression, which
9215 /// might also be a type cast.
9216 PCC_ParenthesizedExpression,
9217 /// \brief Code completion occurs within a sequence of declaration
9218 /// specifiers within a function, method, or block.
9219 PCC_LocalDeclarationSpecifiers
9222 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9223 void CodeCompleteOrdinaryName(Scope *S,
9224 ParserCompletionContext CompletionContext);
9225 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9226 bool AllowNonIdentifiers,
9227 bool AllowNestedNameSpecifiers);
9229 struct CodeCompleteExpressionData;
9230 void CodeCompleteExpression(Scope *S,
9231 const CodeCompleteExpressionData &Data);
9232 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9233 SourceLocation OpLoc,
9235 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9236 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9237 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9238 void CodeCompleteBracketDeclarator(Scope *S);
9239 void CodeCompleteCase(Scope *S);
9240 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9241 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9242 ArrayRef<Expr *> Args);
9243 void CodeCompleteInitializer(Scope *S, Decl *D);
9244 void CodeCompleteReturn(Scope *S);
9245 void CodeCompleteAfterIf(Scope *S);
9246 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9248 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9249 bool EnteringContext);
9250 void CodeCompleteUsing(Scope *S);
9251 void CodeCompleteUsingDirective(Scope *S);
9252 void CodeCompleteNamespaceDecl(Scope *S);
9253 void CodeCompleteNamespaceAliasDecl(Scope *S);
9254 void CodeCompleteOperatorName(Scope *S);
9255 void CodeCompleteConstructorInitializer(
9257 ArrayRef<CXXCtorInitializer *> Initializers);
9259 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9260 bool AfterAmpersand);
9262 void CodeCompleteObjCAtDirective(Scope *S);
9263 void CodeCompleteObjCAtVisibility(Scope *S);
9264 void CodeCompleteObjCAtStatement(Scope *S);
9265 void CodeCompleteObjCAtExpression(Scope *S);
9266 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9267 void CodeCompleteObjCPropertyGetter(Scope *S);
9268 void CodeCompleteObjCPropertySetter(Scope *S);
9269 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9271 void CodeCompleteObjCMessageReceiver(Scope *S);
9272 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9273 ArrayRef<IdentifierInfo *> SelIdents,
9274 bool AtArgumentExpression);
9275 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9276 ArrayRef<IdentifierInfo *> SelIdents,
9277 bool AtArgumentExpression,
9278 bool IsSuper = false);
9279 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9280 ArrayRef<IdentifierInfo *> SelIdents,
9281 bool AtArgumentExpression,
9282 ObjCInterfaceDecl *Super = nullptr);
9283 void CodeCompleteObjCForCollection(Scope *S,
9284 DeclGroupPtrTy IterationVar);
9285 void CodeCompleteObjCSelector(Scope *S,
9286 ArrayRef<IdentifierInfo *> SelIdents);
9287 void CodeCompleteObjCProtocolReferences(
9288 ArrayRef<IdentifierLocPair> Protocols);
9289 void CodeCompleteObjCProtocolDecl(Scope *S);
9290 void CodeCompleteObjCInterfaceDecl(Scope *S);
9291 void CodeCompleteObjCSuperclass(Scope *S,
9292 IdentifierInfo *ClassName,
9293 SourceLocation ClassNameLoc);
9294 void CodeCompleteObjCImplementationDecl(Scope *S);
9295 void CodeCompleteObjCInterfaceCategory(Scope *S,
9296 IdentifierInfo *ClassName,
9297 SourceLocation ClassNameLoc);
9298 void CodeCompleteObjCImplementationCategory(Scope *S,
9299 IdentifierInfo *ClassName,
9300 SourceLocation ClassNameLoc);
9301 void CodeCompleteObjCPropertyDefinition(Scope *S);
9302 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9303 IdentifierInfo *PropertyName);
9304 void CodeCompleteObjCMethodDecl(Scope *S,
9305 bool IsInstanceMethod,
9306 ParsedType ReturnType);
9307 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9308 bool IsInstanceMethod,
9309 bool AtParameterName,
9310 ParsedType ReturnType,
9311 ArrayRef<IdentifierInfo *> SelIdents);
9312 void CodeCompletePreprocessorDirective(bool InConditional);
9313 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9314 void CodeCompletePreprocessorMacroName(bool IsDefinition);
9315 void CodeCompletePreprocessorExpression();
9316 void CodeCompletePreprocessorMacroArgument(Scope *S,
9317 IdentifierInfo *Macro,
9318 MacroInfo *MacroInfo,
9320 void CodeCompleteNaturalLanguage();
9321 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9322 CodeCompletionTUInfo &CCTUInfo,
9323 SmallVectorImpl<CodeCompletionResult> &Results);
9326 //===--------------------------------------------------------------------===//
9327 // Extra semantic analysis beyond the C type system
9330 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9331 unsigned ByteNo) const;
9334 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9335 const ArraySubscriptExpr *ASE=nullptr,
9336 bool AllowOnePastEnd=true, bool IndexNegated=false);
9337 void CheckArrayAccess(const Expr *E);
9338 // Used to grab the relevant information from a FormatAttr and a
9339 // FunctionDeclaration.
9340 struct FormatStringInfo {
9342 unsigned FirstDataArg;
9346 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9347 FormatStringInfo *FSI);
9348 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9349 const FunctionProtoType *Proto);
9350 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9351 ArrayRef<const Expr *> Args);
9352 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9353 const FunctionProtoType *Proto);
9354 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9355 void CheckConstructorCall(FunctionDecl *FDecl,
9356 ArrayRef<const Expr *> Args,
9357 const FunctionProtoType *Proto,
9358 SourceLocation Loc);
9360 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
9361 ArrayRef<const Expr *> Args, bool IsMemberFunction,
9362 SourceLocation Loc, SourceRange Range,
9363 VariadicCallType CallType);
9365 bool CheckObjCString(Expr *Arg);
9367 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
9368 unsigned BuiltinID, CallExpr *TheCall);
9370 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
9372 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9373 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9375 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9376 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9377 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9378 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9379 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9381 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
9382 bool SemaBuiltinVAStart(CallExpr *TheCall);
9383 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
9384 bool SemaBuiltinVAStartARM(CallExpr *Call);
9385 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
9386 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
9389 // Used by C++ template instantiation.
9390 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
9391 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
9392 SourceLocation BuiltinLoc,
9393 SourceLocation RParenLoc);
9396 bool SemaBuiltinPrefetch(CallExpr *TheCall);
9397 bool SemaBuiltinAssume(CallExpr *TheCall);
9398 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
9399 bool SemaBuiltinLongjmp(CallExpr *TheCall);
9400 bool SemaBuiltinSetjmp(CallExpr *TheCall);
9401 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
9402 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
9403 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
9404 AtomicExpr::AtomicOp Op);
9405 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
9406 llvm::APSInt &Result);
9407 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
9409 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
9410 int ArgNum, unsigned ExpectedFieldNum,
9413 enum FormatStringType {
9424 static FormatStringType GetFormatStringType(const FormatAttr *Format);
9426 bool FormatStringHasSArg(const StringLiteral *FExpr);
9428 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
9431 bool CheckFormatArguments(const FormatAttr *Format,
9432 ArrayRef<const Expr *> Args,
9434 VariadicCallType CallType,
9435 SourceLocation Loc, SourceRange Range,
9436 llvm::SmallBitVector &CheckedVarArgs);
9437 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
9438 bool HasVAListArg, unsigned format_idx,
9439 unsigned firstDataArg, FormatStringType Type,
9440 VariadicCallType CallType,
9441 SourceLocation Loc, SourceRange range,
9442 llvm::SmallBitVector &CheckedVarArgs);
9444 void CheckAbsoluteValueFunction(const CallExpr *Call,
9445 const FunctionDecl *FDecl,
9446 IdentifierInfo *FnInfo);
9448 void CheckMemaccessArguments(const CallExpr *Call,
9450 IdentifierInfo *FnName);
9452 void CheckStrlcpycatArguments(const CallExpr *Call,
9453 IdentifierInfo *FnName);
9455 void CheckStrncatArguments(const CallExpr *Call,
9456 IdentifierInfo *FnName);
9458 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9459 SourceLocation ReturnLoc,
9460 bool isObjCMethod = false,
9461 const AttrVec *Attrs = nullptr,
9462 const FunctionDecl *FD = nullptr);
9464 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
9465 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
9466 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
9467 void CheckForIntOverflow(Expr *E);
9468 void CheckUnsequencedOperations(Expr *E);
9470 /// \brief Perform semantic checks on a completed expression. This will either
9471 /// be a full-expression or a default argument expression.
9472 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
9473 bool IsConstexpr = false);
9475 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
9478 /// \brief Check if the given expression contains 'break' or 'continue'
9479 /// statement that produces control flow different from GCC.
9480 void CheckBreakContinueBinding(Expr *E);
9482 /// \brief Check whether receiver is mutable ObjC container which
9483 /// attempts to add itself into the container
9484 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
9486 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9487 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9488 bool DeleteWasArrayForm);
9490 /// \brief Register a magic integral constant to be used as a type tag.
9491 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9492 uint64_t MagicValue, QualType Type,
9493 bool LayoutCompatible, bool MustBeNull);
9495 struct TypeTagData {
9498 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
9499 Type(Type), LayoutCompatible(LayoutCompatible),
9500 MustBeNull(MustBeNull)
9505 /// If true, \c Type should be compared with other expression's types for
9506 /// layout-compatibility.
9507 unsigned LayoutCompatible : 1;
9508 unsigned MustBeNull : 1;
9511 /// A pair of ArgumentKind identifier and magic value. This uniquely
9512 /// identifies the magic value.
9513 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
9516 /// \brief A map from magic value to type information.
9517 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
9518 TypeTagForDatatypeMagicValues;
9520 /// \brief Peform checks on a call of a function with argument_with_type_tag
9521 /// or pointer_with_type_tag attributes.
9522 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9523 const Expr * const *ExprArgs);
9525 /// \brief The parser's current scope.
9527 /// The parser maintains this state here.
9530 mutable IdentifierInfo *Ident_super;
9531 mutable IdentifierInfo *Ident___float128;
9533 /// Nullability type specifiers.
9534 IdentifierInfo *Ident__Nonnull = nullptr;
9535 IdentifierInfo *Ident__Nullable = nullptr;
9536 IdentifierInfo *Ident__Null_unspecified = nullptr;
9538 IdentifierInfo *Ident_NSError = nullptr;
9541 friend class Parser;
9542 friend class InitializationSequence;
9543 friend class ASTReader;
9544 friend class ASTDeclReader;
9545 friend class ASTWriter;
9548 /// Retrieve the keyword associated
9549 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
9551 /// The struct behind the CFErrorRef pointer.
9552 RecordDecl *CFError = nullptr;
9554 /// Retrieve the identifier "NSError".
9555 IdentifierInfo *getNSErrorIdent();
9557 /// \brief Retrieve the parser's current scope.
9559 /// This routine must only be used when it is certain that semantic analysis
9560 /// and the parser are in precisely the same context, which is not the case
9561 /// when, e.g., we are performing any kind of template instantiation.
9562 /// Therefore, the only safe places to use this scope are in the parser
9563 /// itself and in routines directly invoked from the parser and *never* from
9564 /// template substitution or instantiation.
9565 Scope *getCurScope() const { return CurScope; }
9567 void incrementMSManglingNumber() const {
9568 return CurScope->incrementMSManglingNumber();
9571 IdentifierInfo *getSuperIdentifier() const;
9572 IdentifierInfo *getFloat128Identifier() const;
9574 Decl *getObjCDeclContext() const;
9576 DeclContext *getCurLexicalContext() const {
9577 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
9580 AvailabilityResult getCurContextAvailability() const;
9582 const DeclContext *getCurObjCLexicalContext() const {
9583 const DeclContext *DC = getCurLexicalContext();
9584 // A category implicitly has the attribute of the interface.
9585 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
9586 DC = CatD->getClassInterface();
9590 /// \brief To be used for checking whether the arguments being passed to
9591 /// function exceeds the number of parameters expected for it.
9592 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
9593 bool PartialOverloading = false) {
9594 // We check whether we're just after a comma in code-completion.
9595 if (NumArgs > 0 && PartialOverloading)
9596 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
9597 return NumArgs > NumParams;
9600 // Emitting members of dllexported classes is delayed until the class
9601 // (including field initializers) is fully parsed.
9602 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
9605 /// \brief RAII object that enters a new expression evaluation context.
9606 class EnterExpressionEvaluationContext {
9608 bool Entered = true;
9611 EnterExpressionEvaluationContext(Sema &Actions,
9612 Sema::ExpressionEvaluationContext NewContext,
9613 Decl *LambdaContextDecl = nullptr,
9614 bool IsDecltype = false,
9615 bool ShouldEnter = true)
9616 : Actions(Actions), Entered(ShouldEnter) {
9618 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
9621 EnterExpressionEvaluationContext(Sema &Actions,
9622 Sema::ExpressionEvaluationContext NewContext,
9623 Sema::ReuseLambdaContextDecl_t,
9624 bool IsDecltype = false)
9625 : Actions(Actions) {
9626 Actions.PushExpressionEvaluationContext(NewContext,
9627 Sema::ReuseLambdaContextDecl,
9631 ~EnterExpressionEvaluationContext() {
9633 Actions.PopExpressionEvaluationContext();
9637 DeductionFailureInfo
9638 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
9639 sema::TemplateDeductionInfo &Info);
9641 /// \brief Contains a late templated function.
9642 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
9643 struct LateParsedTemplate {
9645 /// \brief The template function declaration to be late parsed.
9649 } // end namespace clang