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,
5115 bool IsConstexprSpecified);
5117 /// \brief Endow the lambda scope info with the relevant properties.
5118 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5119 CXXMethodDecl *CallOperator,
5120 SourceRange IntroducerRange,
5121 LambdaCaptureDefault CaptureDefault,
5122 SourceLocation CaptureDefaultLoc,
5123 bool ExplicitParams,
5124 bool ExplicitResultType,
5127 /// \brief Perform initialization analysis of the init-capture and perform
5128 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5129 /// not being used to initialize a reference.
5130 ParsedType actOnLambdaInitCaptureInitialization(
5131 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5132 LambdaCaptureInitKind InitKind, Expr *&Init) {
5133 return ParsedType::make(buildLambdaInitCaptureInitialization(
5134 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5136 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5138 bool DirectInit, Expr *&Init);
5140 /// \brief Create a dummy variable within the declcontext of the lambda's
5141 /// call operator, for name lookup purposes for a lambda init capture.
5143 /// CodeGen handles emission of lambda captures, ignoring these dummy
5144 /// variables appropriately.
5145 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5146 QualType InitCaptureType,
5148 unsigned InitStyle, Expr *Init);
5150 /// \brief Build the implicit field for an init-capture.
5151 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5153 /// \brief Note that we have finished the explicit captures for the
5155 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5157 /// \brief Introduce the lambda parameters into scope.
5158 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5160 /// \brief Deduce a block or lambda's return type based on the return
5161 /// statements present in the body.
5162 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5164 /// ActOnStartOfLambdaDefinition - This is called just before we start
5165 /// parsing the body of a lambda; it analyzes the explicit captures and
5166 /// arguments, and sets up various data-structures for the body of the
5168 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5169 Declarator &ParamInfo, Scope *CurScope);
5171 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5172 /// is invoked to pop the information about the lambda.
5173 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5174 bool IsInstantiation = false);
5176 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5177 /// was successfully completed.
5178 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5181 /// \brief Complete a lambda-expression having processed and attached the
5183 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5184 sema::LambdaScopeInfo *LSI);
5186 /// \brief Define the "body" of the conversion from a lambda object to a
5187 /// function pointer.
5189 /// This routine doesn't actually define a sensible body; rather, it fills
5190 /// in the initialization expression needed to copy the lambda object into
5191 /// the block, and IR generation actually generates the real body of the
5192 /// block pointer conversion.
5193 void DefineImplicitLambdaToFunctionPointerConversion(
5194 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5196 /// \brief Define the "body" of the conversion from a lambda object to a
5199 /// This routine doesn't actually define a sensible body; rather, it fills
5200 /// in the initialization expression needed to copy the lambda object into
5201 /// the block, and IR generation actually generates the real body of the
5202 /// block pointer conversion.
5203 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5204 CXXConversionDecl *Conv);
5206 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5207 SourceLocation ConvLocation,
5208 CXXConversionDecl *Conv,
5211 // ParseObjCStringLiteral - Parse Objective-C string literals.
5212 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5213 ArrayRef<Expr *> Strings);
5215 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5217 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5218 /// numeric literal expression. Type of the expression will be "NSNumber *"
5219 /// or "id" if NSNumber is unavailable.
5220 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5221 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5223 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5225 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5226 /// '@' prefixed parenthesized expression. The type of the expression will
5227 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5228 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5229 /// "const char *" or C structure with attribute 'objc_boxable'.
5230 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5232 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5234 ObjCMethodDecl *getterMethod,
5235 ObjCMethodDecl *setterMethod);
5237 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5238 MutableArrayRef<ObjCDictionaryElement> Elements);
5240 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5241 TypeSourceInfo *EncodedTypeInfo,
5242 SourceLocation RParenLoc);
5243 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5244 CXXConversionDecl *Method,
5245 bool HadMultipleCandidates);
5247 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5248 SourceLocation EncodeLoc,
5249 SourceLocation LParenLoc,
5251 SourceLocation RParenLoc);
5253 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5254 ExprResult ParseObjCSelectorExpression(Selector Sel,
5255 SourceLocation AtLoc,
5256 SourceLocation SelLoc,
5257 SourceLocation LParenLoc,
5258 SourceLocation RParenLoc,
5259 bool WarnMultipleSelectors);
5261 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5262 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5263 SourceLocation AtLoc,
5264 SourceLocation ProtoLoc,
5265 SourceLocation LParenLoc,
5266 SourceLocation ProtoIdLoc,
5267 SourceLocation RParenLoc);
5269 //===--------------------------------------------------------------------===//
5272 Decl *ActOnStartLinkageSpecification(Scope *S,
5273 SourceLocation ExternLoc,
5275 SourceLocation LBraceLoc);
5276 Decl *ActOnFinishLinkageSpecification(Scope *S,
5278 SourceLocation RBraceLoc);
5281 //===--------------------------------------------------------------------===//
5284 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5285 const CXXScopeSpec *SS = nullptr);
5286 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5288 bool ActOnAccessSpecifier(AccessSpecifier Access,
5289 SourceLocation ASLoc,
5290 SourceLocation ColonLoc,
5291 AttributeList *Attrs = nullptr);
5293 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5295 MultiTemplateParamsArg TemplateParameterLists,
5296 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5297 InClassInitStyle InitStyle);
5299 void ActOnStartCXXInClassMemberInitializer();
5300 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5301 SourceLocation EqualLoc,
5304 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5307 IdentifierInfo *MemberOrBase,
5308 ParsedType TemplateTypeTy,
5310 SourceLocation IdLoc,
5311 SourceLocation LParenLoc,
5312 ArrayRef<Expr *> Args,
5313 SourceLocation RParenLoc,
5314 SourceLocation EllipsisLoc);
5316 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5319 IdentifierInfo *MemberOrBase,
5320 ParsedType TemplateTypeTy,
5322 SourceLocation IdLoc,
5324 SourceLocation EllipsisLoc);
5326 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5329 IdentifierInfo *MemberOrBase,
5330 ParsedType TemplateTypeTy,
5332 SourceLocation IdLoc,
5334 SourceLocation EllipsisLoc);
5336 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5338 SourceLocation IdLoc);
5340 MemInitResult BuildBaseInitializer(QualType BaseType,
5341 TypeSourceInfo *BaseTInfo,
5343 CXXRecordDecl *ClassDecl,
5344 SourceLocation EllipsisLoc);
5346 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5348 CXXRecordDecl *ClassDecl);
5350 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5351 CXXCtorInitializer *Initializer);
5353 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5354 ArrayRef<CXXCtorInitializer *> Initializers = None);
5356 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5359 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5360 /// mark all the non-trivial destructors of its members and bases as
5362 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5363 CXXRecordDecl *Record);
5365 /// \brief The list of classes whose vtables have been used within
5366 /// this translation unit, and the source locations at which the
5367 /// first use occurred.
5368 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5370 /// \brief The list of vtables that are required but have not yet been
5372 SmallVector<VTableUse, 16> VTableUses;
5374 /// \brief The set of classes whose vtables have been used within
5375 /// this translation unit, and a bit that will be true if the vtable is
5376 /// required to be emitted (otherwise, it should be emitted only if needed
5377 /// by code generation).
5378 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5380 /// \brief Load any externally-stored vtable uses.
5381 void LoadExternalVTableUses();
5383 /// \brief Note that the vtable for the given class was used at the
5385 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5386 bool DefinitionRequired = false);
5388 /// \brief Mark the exception specifications of all virtual member functions
5389 /// in the given class as needed.
5390 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5391 const CXXRecordDecl *RD);
5393 /// MarkVirtualMembersReferenced - Will mark all members of the given
5394 /// CXXRecordDecl referenced.
5395 void MarkVirtualMembersReferenced(SourceLocation Loc,
5396 const CXXRecordDecl *RD);
5398 /// \brief Define all of the vtables that have been used in this
5399 /// translation unit and reference any virtual members used by those
5402 /// \returns true if any work was done, false otherwise.
5403 bool DefineUsedVTables();
5405 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5407 void ActOnMemInitializers(Decl *ConstructorDecl,
5408 SourceLocation ColonLoc,
5409 ArrayRef<CXXCtorInitializer*> MemInits,
5412 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5413 /// ensure that referenceDLLExportedClassMethods is called some point later
5414 /// when all outer classes of Class are complete.
5415 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5417 void referenceDLLExportedClassMethods();
5419 void propagateDLLAttrToBaseClassTemplate(
5420 CXXRecordDecl *Class, Attr *ClassAttr,
5421 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5422 SourceLocation BaseLoc);
5424 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5425 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5427 SourceLocation LBrac,
5428 SourceLocation RBrac,
5429 AttributeList *AttrList);
5430 void ActOnFinishCXXMemberDecls();
5431 void ActOnFinishCXXNonNestedClass(Decl *D);
5433 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5434 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5435 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5436 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5437 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5438 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5439 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5440 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5441 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5442 CachedTokens &Toks);
5443 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5444 bool IsInsideALocalClassWithinATemplateFunction();
5446 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5448 Expr *AssertMessageExpr,
5449 SourceLocation RParenLoc);
5450 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5452 StringLiteral *AssertMessageExpr,
5453 SourceLocation RParenLoc,
5456 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5457 SourceLocation FriendLoc,
5458 TypeSourceInfo *TSInfo);
5459 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5460 MultiTemplateParamsArg TemplateParams);
5461 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5462 MultiTemplateParamsArg TemplateParams);
5464 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5466 void CheckConstructor(CXXConstructorDecl *Constructor);
5467 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5469 bool CheckDestructor(CXXDestructorDecl *Destructor);
5470 void CheckConversionDeclarator(Declarator &D, QualType &R,
5472 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5474 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5475 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5476 const FunctionProtoType *T);
5477 void CheckDelayedMemberExceptionSpecs();
5479 //===--------------------------------------------------------------------===//
5480 // C++ Derived Classes
5483 /// ActOnBaseSpecifier - Parsed a base specifier
5484 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5485 SourceRange SpecifierRange,
5486 bool Virtual, AccessSpecifier Access,
5487 TypeSourceInfo *TInfo,
5488 SourceLocation EllipsisLoc);
5490 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5491 SourceRange SpecifierRange,
5492 ParsedAttributes &Attrs,
5493 bool Virtual, AccessSpecifier Access,
5494 ParsedType basetype,
5495 SourceLocation BaseLoc,
5496 SourceLocation EllipsisLoc);
5498 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5499 MutableArrayRef<CXXBaseSpecifier *> Bases);
5500 void ActOnBaseSpecifiers(Decl *ClassDecl,
5501 MutableArrayRef<CXXBaseSpecifier *> Bases);
5503 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5504 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5505 CXXBasePaths &Paths);
5507 // FIXME: I don't like this name.
5508 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5510 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5511 SourceLocation Loc, SourceRange Range,
5512 CXXCastPath *BasePath = nullptr,
5513 bool IgnoreAccess = false);
5514 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5515 unsigned InaccessibleBaseID,
5516 unsigned AmbigiousBaseConvID,
5517 SourceLocation Loc, SourceRange Range,
5518 DeclarationName Name,
5519 CXXCastPath *BasePath,
5520 bool IgnoreAccess = false);
5522 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5524 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5525 const CXXMethodDecl *Old);
5527 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5528 /// covariant, according to C++ [class.virtual]p5.
5529 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5530 const CXXMethodDecl *Old);
5532 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5533 /// spec is a subset of base spec.
5534 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5535 const CXXMethodDecl *Old);
5537 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5539 /// CheckOverrideControl - Check C++11 override control semantics.
5540 void CheckOverrideControl(NamedDecl *D);
5542 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5543 /// not used in the declaration of an overriding method.
5544 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5546 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5547 /// overrides a virtual member function marked 'final', according to
5548 /// C++11 [class.virtual]p4.
5549 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5550 const CXXMethodDecl *Old);
5553 //===--------------------------------------------------------------------===//
5554 // C++ Access Control
5564 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5565 NamedDecl *PrevMemberDecl,
5566 AccessSpecifier LexicalAS);
5568 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5569 DeclAccessPair FoundDecl);
5570 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5571 DeclAccessPair FoundDecl);
5572 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5573 SourceRange PlacementRange,
5574 CXXRecordDecl *NamingClass,
5575 DeclAccessPair FoundDecl,
5576 bool Diagnose = true);
5577 AccessResult CheckConstructorAccess(SourceLocation Loc,
5578 CXXConstructorDecl *D,
5579 DeclAccessPair FoundDecl,
5580 const InitializedEntity &Entity,
5581 bool IsCopyBindingRefToTemp = false);
5582 AccessResult CheckConstructorAccess(SourceLocation Loc,
5583 CXXConstructorDecl *D,
5584 DeclAccessPair FoundDecl,
5585 const InitializedEntity &Entity,
5586 const PartialDiagnostic &PDiag);
5587 AccessResult CheckDestructorAccess(SourceLocation Loc,
5588 CXXDestructorDecl *Dtor,
5589 const PartialDiagnostic &PDiag,
5590 QualType objectType = QualType());
5591 AccessResult CheckFriendAccess(NamedDecl *D);
5592 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5593 CXXRecordDecl *NamingClass,
5594 DeclAccessPair Found);
5595 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5598 DeclAccessPair FoundDecl);
5599 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5600 DeclAccessPair FoundDecl);
5601 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5602 QualType Base, QualType Derived,
5603 const CXXBasePath &Path,
5605 bool ForceCheck = false,
5606 bool ForceUnprivileged = false);
5607 void CheckLookupAccess(const LookupResult &R);
5608 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5609 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5610 AccessSpecifier access,
5611 QualType objectType);
5613 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5614 const MultiLevelTemplateArgumentList &TemplateArgs);
5615 void PerformDependentDiagnostics(const DeclContext *Pattern,
5616 const MultiLevelTemplateArgumentList &TemplateArgs);
5618 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5620 /// \brief When true, access checking violations are treated as SFINAE
5621 /// failures rather than hard errors.
5622 bool AccessCheckingSFINAE;
5624 enum AbstractDiagSelID {
5628 AbstractVariableType,
5631 AbstractSynthesizedIvarType,
5635 bool isAbstractType(SourceLocation Loc, QualType T);
5636 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5637 TypeDiagnoser &Diagnoser);
5638 template <typename... Ts>
5639 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5640 const Ts &...Args) {
5641 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5642 return RequireNonAbstractType(Loc, T, Diagnoser);
5645 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5647 //===--------------------------------------------------------------------===//
5648 // C++ Overloaded Operators [C++ 13.5]
5651 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5653 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5655 //===--------------------------------------------------------------------===//
5656 // C++ Templates [C++ 14]
5658 void FilterAcceptableTemplateNames(LookupResult &R,
5659 bool AllowFunctionTemplates = true);
5660 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5661 bool AllowFunctionTemplates = true);
5663 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5664 QualType ObjectType, bool EnteringContext,
5665 bool &MemberOfUnknownSpecialization);
5667 TemplateNameKind isTemplateName(Scope *S,
5669 bool hasTemplateKeyword,
5670 UnqualifiedId &Name,
5671 ParsedType ObjectType,
5672 bool EnteringContext,
5673 TemplateTy &Template,
5674 bool &MemberOfUnknownSpecialization);
5676 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5677 SourceLocation IILoc,
5679 const CXXScopeSpec *SS,
5680 TemplateTy &SuggestedTemplate,
5681 TemplateNameKind &SuggestedKind);
5683 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5684 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5686 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5687 SourceLocation EllipsisLoc,
5688 SourceLocation KeyLoc,
5689 IdentifierInfo *ParamName,
5690 SourceLocation ParamNameLoc,
5691 unsigned Depth, unsigned Position,
5692 SourceLocation EqualLoc,
5693 ParsedType DefaultArg);
5695 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5696 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5699 SourceLocation EqualLoc,
5701 Decl *ActOnTemplateTemplateParameter(Scope *S,
5702 SourceLocation TmpLoc,
5703 TemplateParameterList *Params,
5704 SourceLocation EllipsisLoc,
5705 IdentifierInfo *ParamName,
5706 SourceLocation ParamNameLoc,
5709 SourceLocation EqualLoc,
5710 ParsedTemplateArgument DefaultArg);
5712 TemplateParameterList *
5713 ActOnTemplateParameterList(unsigned Depth,
5714 SourceLocation ExportLoc,
5715 SourceLocation TemplateLoc,
5716 SourceLocation LAngleLoc,
5717 ArrayRef<Decl *> Params,
5718 SourceLocation RAngleLoc,
5719 Expr *RequiresClause);
5721 /// \brief The context in which we are checking a template parameter list.
5722 enum TemplateParamListContext {
5725 TPC_FunctionTemplate,
5726 TPC_ClassTemplateMember,
5727 TPC_FriendClassTemplate,
5728 TPC_FriendFunctionTemplate,
5729 TPC_FriendFunctionTemplateDefinition,
5730 TPC_TypeAliasTemplate
5733 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5734 TemplateParameterList *OldParams,
5735 TemplateParamListContext TPC);
5736 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5737 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5738 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5739 ArrayRef<TemplateParameterList *> ParamLists,
5740 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5742 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5743 SourceLocation KWLoc, CXXScopeSpec &SS,
5744 IdentifierInfo *Name, SourceLocation NameLoc,
5745 AttributeList *Attr,
5746 TemplateParameterList *TemplateParams,
5748 SourceLocation ModulePrivateLoc,
5749 SourceLocation FriendLoc,
5750 unsigned NumOuterTemplateParamLists,
5751 TemplateParameterList **OuterTemplateParamLists,
5752 SkipBodyInfo *SkipBody = nullptr);
5754 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5755 TemplateArgumentListInfo &Out);
5757 void NoteAllFoundTemplates(TemplateName Name);
5759 QualType CheckTemplateIdType(TemplateName Template,
5760 SourceLocation TemplateLoc,
5761 TemplateArgumentListInfo &TemplateArgs);
5764 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5765 TemplateTy Template, SourceLocation TemplateLoc,
5766 SourceLocation LAngleLoc,
5767 ASTTemplateArgsPtr TemplateArgs,
5768 SourceLocation RAngleLoc,
5769 bool IsCtorOrDtorName = false);
5771 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5772 /// such as \c class T::template apply<U>.
5773 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5774 TypeSpecifierType TagSpec,
5775 SourceLocation TagLoc,
5777 SourceLocation TemplateKWLoc,
5778 TemplateTy TemplateD,
5779 SourceLocation TemplateLoc,
5780 SourceLocation LAngleLoc,
5781 ASTTemplateArgsPtr TemplateArgsIn,
5782 SourceLocation RAngleLoc);
5784 DeclResult ActOnVarTemplateSpecialization(
5785 Scope *S, Declarator &D, TypeSourceInfo *DI,
5786 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5787 StorageClass SC, bool IsPartialSpecialization);
5789 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5790 SourceLocation TemplateLoc,
5791 SourceLocation TemplateNameLoc,
5792 const TemplateArgumentListInfo &TemplateArgs);
5794 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5795 const DeclarationNameInfo &NameInfo,
5796 VarTemplateDecl *Template,
5797 SourceLocation TemplateLoc,
5798 const TemplateArgumentListInfo *TemplateArgs);
5800 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5801 SourceLocation TemplateKWLoc,
5804 const TemplateArgumentListInfo *TemplateArgs);
5806 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5807 SourceLocation TemplateKWLoc,
5808 const DeclarationNameInfo &NameInfo,
5809 const TemplateArgumentListInfo *TemplateArgs);
5811 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5813 SourceLocation TemplateKWLoc,
5814 UnqualifiedId &Name,
5815 ParsedType ObjectType,
5816 bool EnteringContext,
5817 TemplateTy &Template);
5820 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5821 SourceLocation KWLoc,
5822 SourceLocation ModulePrivateLoc,
5823 TemplateIdAnnotation &TemplateId,
5824 AttributeList *Attr,
5825 MultiTemplateParamsArg TemplateParameterLists,
5826 SkipBodyInfo *SkipBody = nullptr);
5828 Decl *ActOnTemplateDeclarator(Scope *S,
5829 MultiTemplateParamsArg TemplateParameterLists,
5833 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5834 TemplateSpecializationKind NewTSK,
5835 NamedDecl *PrevDecl,
5836 TemplateSpecializationKind PrevTSK,
5837 SourceLocation PrevPtOfInstantiation,
5840 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5841 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5842 LookupResult &Previous);
5844 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5845 TemplateArgumentListInfo *ExplicitTemplateArgs,
5846 LookupResult &Previous);
5847 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5850 ActOnExplicitInstantiation(Scope *S,
5851 SourceLocation ExternLoc,
5852 SourceLocation TemplateLoc,
5854 SourceLocation KWLoc,
5855 const CXXScopeSpec &SS,
5856 TemplateTy Template,
5857 SourceLocation TemplateNameLoc,
5858 SourceLocation LAngleLoc,
5859 ASTTemplateArgsPtr TemplateArgs,
5860 SourceLocation RAngleLoc,
5861 AttributeList *Attr);
5864 ActOnExplicitInstantiation(Scope *S,
5865 SourceLocation ExternLoc,
5866 SourceLocation TemplateLoc,
5868 SourceLocation KWLoc,
5870 IdentifierInfo *Name,
5871 SourceLocation NameLoc,
5872 AttributeList *Attr);
5874 DeclResult ActOnExplicitInstantiation(Scope *S,
5875 SourceLocation ExternLoc,
5876 SourceLocation TemplateLoc,
5880 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5881 SourceLocation TemplateLoc,
5882 SourceLocation RAngleLoc,
5884 SmallVectorImpl<TemplateArgument>
5886 bool &HasDefaultArg);
5888 /// \brief Specifies the context in which a particular template
5889 /// argument is being checked.
5890 enum CheckTemplateArgumentKind {
5891 /// \brief The template argument was specified in the code or was
5892 /// instantiated with some deduced template arguments.
5895 /// \brief The template argument was deduced via template argument
5899 /// \brief The template argument was deduced from an array bound
5900 /// via template argument deduction.
5901 CTAK_DeducedFromArrayBound
5904 bool CheckTemplateArgument(NamedDecl *Param,
5905 TemplateArgumentLoc &Arg,
5906 NamedDecl *Template,
5907 SourceLocation TemplateLoc,
5908 SourceLocation RAngleLoc,
5909 unsigned ArgumentPackIndex,
5910 SmallVectorImpl<TemplateArgument> &Converted,
5911 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5913 /// \brief Check that the given template arguments can be be provided to
5914 /// the given template, converting the arguments along the way.
5916 /// \param Template The template to which the template arguments are being
5919 /// \param TemplateLoc The location of the template name in the source.
5921 /// \param TemplateArgs The list of template arguments. If the template is
5922 /// a template template parameter, this function may extend the set of
5923 /// template arguments to also include substituted, defaulted template
5926 /// \param PartialTemplateArgs True if the list of template arguments is
5927 /// intentionally partial, e.g., because we're checking just the initial
5928 /// set of template arguments.
5930 /// \param Converted Will receive the converted, canonicalized template
5933 /// \returns true if an error occurred, false otherwise.
5934 bool CheckTemplateArgumentList(TemplateDecl *Template,
5935 SourceLocation TemplateLoc,
5936 TemplateArgumentListInfo &TemplateArgs,
5937 bool PartialTemplateArgs,
5938 SmallVectorImpl<TemplateArgument> &Converted);
5940 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5941 TemplateArgumentLoc &Arg,
5942 SmallVectorImpl<TemplateArgument> &Converted);
5944 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5945 TypeSourceInfo *Arg);
5946 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5947 QualType InstantiatedParamType, Expr *Arg,
5948 TemplateArgument &Converted,
5949 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5950 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5951 TemplateArgumentLoc &Arg,
5952 unsigned ArgumentPackIndex);
5955 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5957 SourceLocation Loc);
5959 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5960 SourceLocation Loc);
5962 /// \brief Enumeration describing how template parameter lists are compared
5964 enum TemplateParameterListEqualKind {
5965 /// \brief We are matching the template parameter lists of two templates
5966 /// that might be redeclarations.
5969 /// template<typename T> struct X;
5970 /// template<typename T> struct X;
5974 /// \brief We are matching the template parameter lists of two template
5975 /// template parameters as part of matching the template parameter lists
5976 /// of two templates that might be redeclarations.
5979 /// template<template<int I> class TT> struct X;
5980 /// template<template<int Value> class Other> struct X;
5982 TPL_TemplateTemplateParmMatch,
5984 /// \brief We are matching the template parameter lists of a template
5985 /// template argument against the template parameter lists of a template
5986 /// template parameter.
5989 /// template<template<int Value> class Metafun> struct X;
5990 /// template<int Value> struct integer_c;
5991 /// X<integer_c> xic;
5993 TPL_TemplateTemplateArgumentMatch
5996 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5997 TemplateParameterList *Old,
5999 TemplateParameterListEqualKind Kind,
6000 SourceLocation TemplateArgLoc
6001 = SourceLocation());
6003 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6005 /// \brief Called when the parser has parsed a C++ typename
6006 /// specifier, e.g., "typename T::type".
6008 /// \param S The scope in which this typename type occurs.
6009 /// \param TypenameLoc the location of the 'typename' keyword
6010 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6011 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6012 /// \param IdLoc the location of the identifier.
6014 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6015 const CXXScopeSpec &SS, const IdentifierInfo &II,
6016 SourceLocation IdLoc);
6018 /// \brief Called when the parser has parsed a C++ typename
6019 /// specifier that ends in a template-id, e.g.,
6020 /// "typename MetaFun::template apply<T1, T2>".
6022 /// \param S The scope in which this typename type occurs.
6023 /// \param TypenameLoc the location of the 'typename' keyword
6024 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6025 /// \param TemplateLoc the location of the 'template' keyword, if any.
6026 /// \param TemplateName The template name.
6027 /// \param TemplateNameLoc The location of the template name.
6028 /// \param LAngleLoc The location of the opening angle bracket ('<').
6029 /// \param TemplateArgs The template arguments.
6030 /// \param RAngleLoc The location of the closing angle bracket ('>').
6032 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6033 const CXXScopeSpec &SS,
6034 SourceLocation TemplateLoc,
6035 TemplateTy TemplateName,
6036 SourceLocation TemplateNameLoc,
6037 SourceLocation LAngleLoc,
6038 ASTTemplateArgsPtr TemplateArgs,
6039 SourceLocation RAngleLoc);
6041 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6042 SourceLocation KeywordLoc,
6043 NestedNameSpecifierLoc QualifierLoc,
6044 const IdentifierInfo &II,
6045 SourceLocation IILoc);
6047 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6049 DeclarationName Name);
6050 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6052 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6053 bool RebuildTemplateParamsInCurrentInstantiation(
6054 TemplateParameterList *Params);
6057 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6058 const TemplateArgumentList &Args);
6061 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6062 const TemplateArgument *Args,
6065 //===--------------------------------------------------------------------===//
6066 // C++ Variadic Templates (C++0x [temp.variadic])
6067 //===--------------------------------------------------------------------===//
6069 /// Determine whether an unexpanded parameter pack might be permitted in this
6070 /// location. Useful for error recovery.
6071 bool isUnexpandedParameterPackPermitted();
6073 /// \brief The context in which an unexpanded parameter pack is
6074 /// being diagnosed.
6076 /// Note that the values of this enumeration line up with the first
6077 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6078 enum UnexpandedParameterPackContext {
6079 /// \brief An arbitrary expression.
6080 UPPC_Expression = 0,
6082 /// \brief The base type of a class type.
6085 /// \brief The type of an arbitrary declaration.
6086 UPPC_DeclarationType,
6088 /// \brief The type of a data member.
6089 UPPC_DataMemberType,
6091 /// \brief The size of a bit-field.
6094 /// \brief The expression in a static assertion.
6095 UPPC_StaticAssertExpression,
6097 /// \brief The fixed underlying type of an enumeration.
6098 UPPC_FixedUnderlyingType,
6100 /// \brief The enumerator value.
6101 UPPC_EnumeratorValue,
6103 /// \brief A using declaration.
6104 UPPC_UsingDeclaration,
6106 /// \brief A friend declaration.
6107 UPPC_FriendDeclaration,
6109 /// \brief A declaration qualifier.
6110 UPPC_DeclarationQualifier,
6112 /// \brief An initializer.
6115 /// \brief A default argument.
6116 UPPC_DefaultArgument,
6118 /// \brief The type of a non-type template parameter.
6119 UPPC_NonTypeTemplateParameterType,
6121 /// \brief The type of an exception.
6124 /// \brief Partial specialization.
6125 UPPC_PartialSpecialization,
6127 /// \brief Microsoft __if_exists.
6130 /// \brief Microsoft __if_not_exists.
6133 /// \brief Lambda expression.
6136 /// \brief Block expression,
6140 /// \brief Diagnose unexpanded parameter packs.
6142 /// \param Loc The location at which we should emit the diagnostic.
6144 /// \param UPPC The context in which we are diagnosing unexpanded
6145 /// parameter packs.
6147 /// \param Unexpanded the set of unexpanded parameter packs.
6149 /// \returns true if an error occurred, false otherwise.
6150 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6151 UnexpandedParameterPackContext UPPC,
6152 ArrayRef<UnexpandedParameterPack> Unexpanded);
6154 /// \brief If the given type contains an unexpanded parameter pack,
6155 /// diagnose the error.
6157 /// \param Loc The source location where a diagnostc should be emitted.
6159 /// \param T The type that is being checked for unexpanded parameter
6162 /// \returns true if an error occurred, false otherwise.
6163 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6164 UnexpandedParameterPackContext UPPC);
6166 /// \brief If the given expression contains an unexpanded parameter
6167 /// pack, diagnose the error.
6169 /// \param E The expression that is being checked for unexpanded
6170 /// parameter packs.
6172 /// \returns true if an error occurred, false otherwise.
6173 bool DiagnoseUnexpandedParameterPack(Expr *E,
6174 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6176 /// \brief If the given nested-name-specifier contains an unexpanded
6177 /// parameter pack, diagnose the error.
6179 /// \param SS The nested-name-specifier that is being checked for
6180 /// unexpanded parameter packs.
6182 /// \returns true if an error occurred, false otherwise.
6183 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6184 UnexpandedParameterPackContext UPPC);
6186 /// \brief If the given name contains an unexpanded parameter pack,
6187 /// diagnose the error.
6189 /// \param NameInfo The name (with source location information) that
6190 /// is being checked for unexpanded parameter packs.
6192 /// \returns true if an error occurred, false otherwise.
6193 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6194 UnexpandedParameterPackContext UPPC);
6196 /// \brief If the given template name contains an unexpanded parameter pack,
6197 /// diagnose the error.
6199 /// \param Loc The location of the template name.
6201 /// \param Template The template name that is being checked for unexpanded
6202 /// parameter packs.
6204 /// \returns true if an error occurred, false otherwise.
6205 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6206 TemplateName Template,
6207 UnexpandedParameterPackContext UPPC);
6209 /// \brief If the given template argument contains an unexpanded parameter
6210 /// pack, diagnose the error.
6212 /// \param Arg The template argument that is being checked for unexpanded
6213 /// parameter packs.
6215 /// \returns true if an error occurred, false otherwise.
6216 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6217 UnexpandedParameterPackContext UPPC);
6219 /// \brief Collect the set of unexpanded parameter packs within the given
6220 /// template argument.
6222 /// \param Arg The template argument that will be traversed to find
6223 /// unexpanded parameter packs.
6224 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6225 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6227 /// \brief Collect the set of unexpanded parameter packs within the given
6228 /// template argument.
6230 /// \param Arg The template argument that will be traversed to find
6231 /// unexpanded parameter packs.
6232 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6233 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6235 /// \brief Collect the set of unexpanded parameter packs within the given
6238 /// \param T The type that will be traversed to find
6239 /// unexpanded parameter packs.
6240 void collectUnexpandedParameterPacks(QualType T,
6241 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6243 /// \brief Collect the set of unexpanded parameter packs within the given
6246 /// \param TL The type that will be traversed to find
6247 /// unexpanded parameter packs.
6248 void collectUnexpandedParameterPacks(TypeLoc TL,
6249 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6251 /// \brief Collect the set of unexpanded parameter packs within the given
6252 /// nested-name-specifier.
6254 /// \param SS The nested-name-specifier that will be traversed to find
6255 /// unexpanded parameter packs.
6256 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6257 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6259 /// \brief Collect the set of unexpanded parameter packs within the given
6262 /// \param NameInfo The name that will be traversed to find
6263 /// unexpanded parameter packs.
6264 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6265 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6267 /// \brief Invoked when parsing a template argument followed by an
6268 /// ellipsis, which creates a pack expansion.
6270 /// \param Arg The template argument preceding the ellipsis, which
6271 /// may already be invalid.
6273 /// \param EllipsisLoc The location of the ellipsis.
6274 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6275 SourceLocation EllipsisLoc);
6277 /// \brief Invoked when parsing a type followed by an ellipsis, which
6278 /// creates a pack expansion.
6280 /// \param Type The type preceding the ellipsis, which will become
6281 /// the pattern of the pack expansion.
6283 /// \param EllipsisLoc The location of the ellipsis.
6284 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6286 /// \brief Construct a pack expansion type from the pattern of the pack
6288 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6289 SourceLocation EllipsisLoc,
6290 Optional<unsigned> NumExpansions);
6292 /// \brief Construct a pack expansion type from the pattern of the pack
6294 QualType CheckPackExpansion(QualType Pattern,
6295 SourceRange PatternRange,
6296 SourceLocation EllipsisLoc,
6297 Optional<unsigned> NumExpansions);
6299 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6300 /// creates a pack expansion.
6302 /// \param Pattern The expression preceding the ellipsis, which will become
6303 /// the pattern of the pack expansion.
6305 /// \param EllipsisLoc The location of the ellipsis.
6306 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6308 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6309 /// creates a pack expansion.
6311 /// \param Pattern The expression preceding the ellipsis, which will become
6312 /// the pattern of the pack expansion.
6314 /// \param EllipsisLoc The location of the ellipsis.
6315 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6316 Optional<unsigned> NumExpansions);
6318 /// \brief Determine whether we could expand a pack expansion with the
6319 /// given set of parameter packs into separate arguments by repeatedly
6320 /// transforming the pattern.
6322 /// \param EllipsisLoc The location of the ellipsis that identifies the
6325 /// \param PatternRange The source range that covers the entire pattern of
6326 /// the pack expansion.
6328 /// \param Unexpanded The set of unexpanded parameter packs within the
6331 /// \param ShouldExpand Will be set to \c true if the transformer should
6332 /// expand the corresponding pack expansions into separate arguments. When
6333 /// set, \c NumExpansions must also be set.
6335 /// \param RetainExpansion Whether the caller should add an unexpanded
6336 /// pack expansion after all of the expanded arguments. This is used
6337 /// when extending explicitly-specified template argument packs per
6338 /// C++0x [temp.arg.explicit]p9.
6340 /// \param NumExpansions The number of separate arguments that will be in
6341 /// the expanded form of the corresponding pack expansion. This is both an
6342 /// input and an output parameter, which can be set by the caller if the
6343 /// number of expansions is known a priori (e.g., due to a prior substitution)
6344 /// and will be set by the callee when the number of expansions is known.
6345 /// The callee must set this value when \c ShouldExpand is \c true; it may
6346 /// set this value in other cases.
6348 /// \returns true if an error occurred (e.g., because the parameter packs
6349 /// are to be instantiated with arguments of different lengths), false
6350 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6352 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6353 SourceRange PatternRange,
6354 ArrayRef<UnexpandedParameterPack> Unexpanded,
6355 const MultiLevelTemplateArgumentList &TemplateArgs,
6357 bool &RetainExpansion,
6358 Optional<unsigned> &NumExpansions);
6360 /// \brief Determine the number of arguments in the given pack expansion
6363 /// This routine assumes that the number of arguments in the expansion is
6364 /// consistent across all of the unexpanded parameter packs in its pattern.
6366 /// Returns an empty Optional if the type can't be expanded.
6367 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6368 const MultiLevelTemplateArgumentList &TemplateArgs);
6370 /// \brief Determine whether the given declarator contains any unexpanded
6371 /// parameter packs.
6373 /// This routine is used by the parser to disambiguate function declarators
6374 /// with an ellipsis prior to the ')', e.g.,
6380 /// To determine whether we have an (unnamed) function parameter pack or
6381 /// a variadic function.
6383 /// \returns true if the declarator contains any unexpanded parameter packs,
6384 /// false otherwise.
6385 bool containsUnexpandedParameterPacks(Declarator &D);
6387 /// \brief Returns the pattern of the pack expansion for a template argument.
6389 /// \param OrigLoc The template argument to expand.
6391 /// \param Ellipsis Will be set to the location of the ellipsis.
6393 /// \param NumExpansions Will be set to the number of expansions that will
6394 /// be generated from this pack expansion, if known a priori.
6395 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6396 TemplateArgumentLoc OrigLoc,
6397 SourceLocation &Ellipsis,
6398 Optional<unsigned> &NumExpansions) const;
6400 //===--------------------------------------------------------------------===//
6401 // C++ Template Argument Deduction (C++ [temp.deduct])
6402 //===--------------------------------------------------------------------===//
6404 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6406 /// \brief Describes the result of template argument deduction.
6408 /// The TemplateDeductionResult enumeration describes the result of
6409 /// template argument deduction, as returned from
6410 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6411 /// structure provides additional information about the results of
6412 /// template argument deduction, e.g., the deduced template argument
6413 /// list (if successful) or the specific template parameters or
6414 /// deduced arguments that were involved in the failure.
6415 enum TemplateDeductionResult {
6416 /// \brief Template argument deduction was successful.
6418 /// \brief The declaration was invalid; do nothing.
6420 /// \brief Template argument deduction exceeded the maximum template
6421 /// instantiation depth (which has already been diagnosed).
6422 TDK_InstantiationDepth,
6423 /// \brief Template argument deduction did not deduce a value
6424 /// for every template parameter.
6426 /// \brief Template argument deduction produced inconsistent
6427 /// deduced values for the given template parameter.
6429 /// \brief Template argument deduction failed due to inconsistent
6430 /// cv-qualifiers on a template parameter type that would
6431 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6432 /// but were given a non-const "X".
6434 /// \brief Substitution of the deduced template argument values
6435 /// resulted in an error.
6436 TDK_SubstitutionFailure,
6437 /// \brief After substituting deduced template arguments, a dependent
6438 /// parameter type did not match the corresponding argument.
6439 TDK_DeducedMismatch,
6440 /// \brief A non-depnedent component of the parameter did not match the
6441 /// corresponding component of the argument.
6442 TDK_NonDeducedMismatch,
6443 /// \brief When performing template argument deduction for a function
6444 /// template, there were too many call arguments.
6445 TDK_TooManyArguments,
6446 /// \brief When performing template argument deduction for a function
6447 /// template, there were too few call arguments.
6448 TDK_TooFewArguments,
6449 /// \brief The explicitly-specified template arguments were not valid
6450 /// template arguments for the given template.
6451 TDK_InvalidExplicitArguments,
6452 /// \brief The arguments included an overloaded function name that could
6453 /// not be resolved to a suitable function.
6454 TDK_FailedOverloadResolution,
6455 /// \brief Deduction failed; that's all we know.
6456 TDK_MiscellaneousDeductionFailure
6459 TemplateDeductionResult
6460 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6461 const TemplateArgumentList &TemplateArgs,
6462 sema::TemplateDeductionInfo &Info);
6464 TemplateDeductionResult
6465 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6466 const TemplateArgumentList &TemplateArgs,
6467 sema::TemplateDeductionInfo &Info);
6469 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6470 FunctionTemplateDecl *FunctionTemplate,
6471 TemplateArgumentListInfo &ExplicitTemplateArgs,
6472 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6473 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6474 sema::TemplateDeductionInfo &Info);
6476 /// brief A function argument from which we performed template argument
6477 // deduction for a call.
6478 struct OriginalCallArg {
6479 OriginalCallArg(QualType OriginalParamType,
6481 QualType OriginalArgType)
6482 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6483 OriginalArgType(OriginalArgType) { }
6485 QualType OriginalParamType;
6487 QualType OriginalArgType;
6490 TemplateDeductionResult
6491 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6492 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6493 unsigned NumExplicitlySpecified,
6494 FunctionDecl *&Specialization,
6495 sema::TemplateDeductionInfo &Info,
6496 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6497 bool PartialOverloading = false);
6499 TemplateDeductionResult
6500 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6501 TemplateArgumentListInfo *ExplicitTemplateArgs,
6502 ArrayRef<Expr *> Args,
6503 FunctionDecl *&Specialization,
6504 sema::TemplateDeductionInfo &Info,
6505 bool PartialOverloading = false);
6507 TemplateDeductionResult
6508 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6509 TemplateArgumentListInfo *ExplicitTemplateArgs,
6510 QualType ArgFunctionType,
6511 FunctionDecl *&Specialization,
6512 sema::TemplateDeductionInfo &Info,
6513 bool InOverloadResolution = false);
6515 TemplateDeductionResult
6516 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6518 CXXConversionDecl *&Specialization,
6519 sema::TemplateDeductionInfo &Info);
6521 TemplateDeductionResult
6522 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6523 TemplateArgumentListInfo *ExplicitTemplateArgs,
6524 FunctionDecl *&Specialization,
6525 sema::TemplateDeductionInfo &Info,
6526 bool InOverloadResolution = false);
6528 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6529 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6530 /// \brief Substitute Replacement for auto in TypeWithAuto
6531 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6532 QualType Replacement);
6534 /// \brief Result type of DeduceAutoType.
6535 enum DeduceAutoResult {
6538 DAR_FailedAlreadyDiagnosed
6541 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6543 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6545 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6546 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6547 bool Diagnose = true);
6549 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6550 QualType Type, TypeSourceInfo *TSI,
6551 SourceRange Range, bool DirectInit,
6554 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6556 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6557 SourceLocation ReturnLoc,
6558 Expr *&RetExpr, AutoType *AT);
6560 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6561 FunctionTemplateDecl *FT2,
6563 TemplatePartialOrderingContext TPOC,
6564 unsigned NumCallArguments1,
6565 unsigned NumCallArguments2);
6566 UnresolvedSetIterator
6567 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6568 TemplateSpecCandidateSet &FailedCandidates,
6570 const PartialDiagnostic &NoneDiag,
6571 const PartialDiagnostic &AmbigDiag,
6572 const PartialDiagnostic &CandidateDiag,
6573 bool Complain = true, QualType TargetType = QualType());
6575 ClassTemplatePartialSpecializationDecl *
6576 getMoreSpecializedPartialSpecialization(
6577 ClassTemplatePartialSpecializationDecl *PS1,
6578 ClassTemplatePartialSpecializationDecl *PS2,
6579 SourceLocation Loc);
6581 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6582 VarTemplatePartialSpecializationDecl *PS1,
6583 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6585 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6588 llvm::SmallBitVector &Used);
6589 void MarkDeducedTemplateParameters(
6590 const FunctionTemplateDecl *FunctionTemplate,
6591 llvm::SmallBitVector &Deduced) {
6592 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6594 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6595 const FunctionTemplateDecl *FunctionTemplate,
6596 llvm::SmallBitVector &Deduced);
6598 //===--------------------------------------------------------------------===//
6599 // C++ Template Instantiation
6602 MultiLevelTemplateArgumentList
6603 getTemplateInstantiationArgs(NamedDecl *D,
6604 const TemplateArgumentList *Innermost = nullptr,
6605 bool RelativeToPrimary = false,
6606 const FunctionDecl *Pattern = nullptr);
6608 /// \brief A template instantiation that is currently in progress.
6609 struct ActiveTemplateInstantiation {
6610 /// \brief The kind of template instantiation we are performing
6611 enum InstantiationKind {
6612 /// We are instantiating a template declaration. The entity is
6613 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6614 TemplateInstantiation,
6616 /// We are instantiating a default argument for a template
6617 /// parameter. The Entity is the template, and
6618 /// TemplateArgs/NumTemplateArguments provides the template
6619 /// arguments as specified.
6620 /// FIXME: Use a TemplateArgumentList
6621 DefaultTemplateArgumentInstantiation,
6623 /// We are instantiating a default argument for a function.
6624 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6625 /// provides the template arguments as specified.
6626 DefaultFunctionArgumentInstantiation,
6628 /// We are substituting explicit template arguments provided for
6629 /// a function template. The entity is a FunctionTemplateDecl.
6630 ExplicitTemplateArgumentSubstitution,
6632 /// We are substituting template argument determined as part of
6633 /// template argument deduction for either a class template
6634 /// partial specialization or a function template. The
6635 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6636 /// a FunctionTemplateDecl.
6637 DeducedTemplateArgumentSubstitution,
6639 /// We are substituting prior template arguments into a new
6640 /// template parameter. The template parameter itself is either a
6641 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6642 PriorTemplateArgumentSubstitution,
6644 /// We are checking the validity of a default template argument that
6645 /// has been used when naming a template-id.
6646 DefaultTemplateArgumentChecking,
6648 /// We are instantiating the exception specification for a function
6649 /// template which was deferred until it was needed.
6650 ExceptionSpecInstantiation
6653 /// \brief The point of instantiation within the source code.
6654 SourceLocation PointOfInstantiation;
6656 /// \brief The template (or partial specialization) in which we are
6657 /// performing the instantiation, for substitutions of prior template
6659 NamedDecl *Template;
6661 /// \brief The entity that is being instantiated.
6664 /// \brief The list of template arguments we are substituting, if they
6665 /// are not part of the entity.
6666 const TemplateArgument *TemplateArgs;
6668 /// \brief The number of template arguments in TemplateArgs.
6669 unsigned NumTemplateArgs;
6671 ArrayRef<TemplateArgument> template_arguments() const {
6672 return {TemplateArgs, NumTemplateArgs};
6675 /// \brief The template deduction info object associated with the
6676 /// substitution or checking of explicit or deduced template arguments.
6677 sema::TemplateDeductionInfo *DeductionInfo;
6679 /// \brief The source range that covers the construct that cause
6680 /// the instantiation, e.g., the template-id that causes a class
6681 /// template instantiation.
6682 SourceRange InstantiationRange;
6684 ActiveTemplateInstantiation()
6685 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6686 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6688 /// \brief Determines whether this template is an actual instantiation
6689 /// that should be counted toward the maximum instantiation depth.
6690 bool isInstantiationRecord() const;
6692 friend bool operator==(const ActiveTemplateInstantiation &X,
6693 const ActiveTemplateInstantiation &Y) {
6694 if (X.Kind != Y.Kind)
6697 if (X.Entity != Y.Entity)
6701 case TemplateInstantiation:
6702 case ExceptionSpecInstantiation:
6705 case PriorTemplateArgumentSubstitution:
6706 case DefaultTemplateArgumentChecking:
6707 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6709 case DefaultTemplateArgumentInstantiation:
6710 case ExplicitTemplateArgumentSubstitution:
6711 case DeducedTemplateArgumentSubstitution:
6712 case DefaultFunctionArgumentInstantiation:
6713 return X.TemplateArgs == Y.TemplateArgs;
6717 llvm_unreachable("Invalid InstantiationKind!");
6720 friend bool operator!=(const ActiveTemplateInstantiation &X,
6721 const ActiveTemplateInstantiation &Y) {
6726 /// \brief List of active template instantiations.
6728 /// This vector is treated as a stack. As one template instantiation
6729 /// requires another template instantiation, additional
6730 /// instantiations are pushed onto the stack up to a
6731 /// user-configurable limit LangOptions::InstantiationDepth.
6732 SmallVector<ActiveTemplateInstantiation, 16>
6733 ActiveTemplateInstantiations;
6735 /// \brief Extra modules inspected when performing a lookup during a template
6736 /// instantiation. Computed lazily.
6737 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6739 /// \brief Cache of additional modules that should be used for name lookup
6740 /// within the current template instantiation. Computed lazily; use
6741 /// getLookupModules() to get a complete set.
6742 llvm::DenseSet<Module*> LookupModulesCache;
6744 /// \brief Get the set of additional modules that should be checked during
6745 /// name lookup. A module and its imports become visible when instanting a
6746 /// template defined within it.
6747 llvm::DenseSet<Module*> &getLookupModules();
6749 /// \brief Map from the most recent declaration of a namespace to the most
6750 /// recent visible declaration of that namespace.
6751 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
6753 /// \brief Whether we are in a SFINAE context that is not associated with
6754 /// template instantiation.
6756 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6757 /// of a template instantiation or template argument deduction.
6758 bool InNonInstantiationSFINAEContext;
6760 /// \brief The number of ActiveTemplateInstantiation entries in
6761 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6762 /// therefore, should not be counted as part of the instantiation depth.
6763 unsigned NonInstantiationEntries;
6765 /// \brief The last template from which a template instantiation
6766 /// error or warning was produced.
6768 /// This value is used to suppress printing of redundant template
6769 /// instantiation backtraces when there are multiple errors in the
6770 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6771 /// to implement it anywhere else.
6772 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6774 /// \brief The current index into pack expansion arguments that will be
6775 /// used for substitution of parameter packs.
6777 /// The pack expansion index will be -1 to indicate that parameter packs
6778 /// should be instantiated as themselves. Otherwise, the index specifies
6779 /// which argument within the parameter pack will be used for substitution.
6780 int ArgumentPackSubstitutionIndex;
6782 /// \brief RAII object used to change the argument pack substitution index
6783 /// within a \c Sema object.
6785 /// See \c ArgumentPackSubstitutionIndex for more information.
6786 class ArgumentPackSubstitutionIndexRAII {
6788 int OldSubstitutionIndex;
6791 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6792 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6793 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6796 ~ArgumentPackSubstitutionIndexRAII() {
6797 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6801 friend class ArgumentPackSubstitutionRAII;
6803 /// \brief For each declaration that involved template argument deduction, the
6804 /// set of diagnostics that were suppressed during that template argument
6807 /// FIXME: Serialize this structure to the AST file.
6808 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6809 SuppressedDiagnosticsMap;
6810 SuppressedDiagnosticsMap SuppressedDiagnostics;
6812 /// \brief A stack object to be created when performing template
6815 /// Construction of an object of type \c InstantiatingTemplate
6816 /// pushes the current instantiation onto the stack of active
6817 /// instantiations. If the size of this stack exceeds the maximum
6818 /// number of recursive template instantiations, construction
6819 /// produces an error and evaluates true.
6821 /// Destruction of this object will pop the named instantiation off
6823 struct InstantiatingTemplate {
6824 /// \brief Note that we are instantiating a class template,
6825 /// function template, variable template, alias template,
6826 /// or a member thereof.
6827 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6829 SourceRange InstantiationRange = SourceRange());
6831 struct ExceptionSpecification {};
6832 /// \brief Note that we are instantiating an exception specification
6833 /// of a function template.
6834 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6835 FunctionDecl *Entity, ExceptionSpecification,
6836 SourceRange InstantiationRange = SourceRange());
6838 /// \brief Note that we are instantiating a default argument in a
6840 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6841 TemplateDecl *Template,
6842 ArrayRef<TemplateArgument> TemplateArgs,
6843 SourceRange InstantiationRange = SourceRange());
6845 /// \brief Note that we are instantiating a default argument in a
6847 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6848 FunctionTemplateDecl *FunctionTemplate,
6849 ArrayRef<TemplateArgument> TemplateArgs,
6850 ActiveTemplateInstantiation::InstantiationKind Kind,
6851 sema::TemplateDeductionInfo &DeductionInfo,
6852 SourceRange InstantiationRange = SourceRange());
6854 /// \brief Note that we are instantiating as part of template
6855 /// argument deduction for a class template partial
6857 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6858 ClassTemplatePartialSpecializationDecl *PartialSpec,
6859 ArrayRef<TemplateArgument> TemplateArgs,
6860 sema::TemplateDeductionInfo &DeductionInfo,
6861 SourceRange InstantiationRange = SourceRange());
6863 /// \brief Note that we are instantiating as part of template
6864 /// argument deduction for a variable template partial
6866 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6867 VarTemplatePartialSpecializationDecl *PartialSpec,
6868 ArrayRef<TemplateArgument> TemplateArgs,
6869 sema::TemplateDeductionInfo &DeductionInfo,
6870 SourceRange InstantiationRange = SourceRange());
6872 /// \brief Note that we are instantiating a default argument for a function
6874 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6876 ArrayRef<TemplateArgument> TemplateArgs,
6877 SourceRange InstantiationRange = SourceRange());
6879 /// \brief Note that we are substituting prior template arguments into a
6880 /// non-type parameter.
6881 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6882 NamedDecl *Template,
6883 NonTypeTemplateParmDecl *Param,
6884 ArrayRef<TemplateArgument> TemplateArgs,
6885 SourceRange InstantiationRange);
6887 /// \brief Note that we are substituting prior template arguments into a
6888 /// template template parameter.
6889 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6890 NamedDecl *Template,
6891 TemplateTemplateParmDecl *Param,
6892 ArrayRef<TemplateArgument> TemplateArgs,
6893 SourceRange InstantiationRange);
6895 /// \brief Note that we are checking the default template argument
6896 /// against the template parameter for a given template-id.
6897 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6898 TemplateDecl *Template,
6900 ArrayRef<TemplateArgument> TemplateArgs,
6901 SourceRange InstantiationRange);
6904 /// \brief Note that we have finished instantiating this template.
6907 ~InstantiatingTemplate() { Clear(); }
6909 /// \brief Determines whether we have exceeded the maximum
6910 /// recursive template instantiations.
6911 bool isInvalid() const { return Invalid; }
6916 bool SavedInNonInstantiationSFINAEContext;
6917 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6918 SourceRange InstantiationRange);
6920 InstantiatingTemplate(
6921 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6922 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6923 Decl *Entity, NamedDecl *Template = nullptr,
6924 ArrayRef<TemplateArgument> TemplateArgs = None,
6925 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6927 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6929 InstantiatingTemplate&
6930 operator=(const InstantiatingTemplate&) = delete;
6933 void PrintInstantiationStack();
6935 /// \brief Determines whether we are currently in a context where
6936 /// template argument substitution failures are not considered
6939 /// \returns An empty \c Optional if we're not in a SFINAE context.
6940 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6941 /// template-deduction context object, which can be used to capture
6942 /// diagnostics that will be suppressed.
6943 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6945 /// \brief Determines whether we are currently in a context that
6946 /// is not evaluated as per C++ [expr] p5.
6947 bool isUnevaluatedContext() const {
6948 assert(!ExprEvalContexts.empty() &&
6949 "Must be in an expression evaluation context");
6950 return ExprEvalContexts.back().isUnevaluated();
6953 /// \brief RAII class used to determine whether SFINAE has
6954 /// trapped any errors that occur during template argument
6958 unsigned PrevSFINAEErrors;
6959 bool PrevInNonInstantiationSFINAEContext;
6960 bool PrevAccessCheckingSFINAE;
6963 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6964 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6965 PrevInNonInstantiationSFINAEContext(
6966 SemaRef.InNonInstantiationSFINAEContext),
6967 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6969 if (!SemaRef.isSFINAEContext())
6970 SemaRef.InNonInstantiationSFINAEContext = true;
6971 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6975 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6976 SemaRef.InNonInstantiationSFINAEContext
6977 = PrevInNonInstantiationSFINAEContext;
6978 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6981 /// \brief Determine whether any SFINAE errors have been trapped.
6982 bool hasErrorOccurred() const {
6983 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6987 /// \brief RAII class used to indicate that we are performing provisional
6988 /// semantic analysis to determine the validity of a construct, so
6989 /// typo-correction and diagnostics in the immediate context (not within
6990 /// implicitly-instantiated templates) should be suppressed.
6991 class TentativeAnalysisScope {
6993 // FIXME: Using a SFINAETrap for this is a hack.
6995 bool PrevDisableTypoCorrection;
6997 explicit TentativeAnalysisScope(Sema &SemaRef)
6998 : SemaRef(SemaRef), Trap(SemaRef, true),
6999 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7000 SemaRef.DisableTypoCorrection = true;
7002 ~TentativeAnalysisScope() {
7003 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7007 /// \brief The current instantiation scope used to store local
7009 LocalInstantiationScope *CurrentInstantiationScope;
7011 /// \brief Tracks whether we are in a context where typo correction is
7013 bool DisableTypoCorrection;
7015 /// \brief The number of typos corrected by CorrectTypo.
7016 unsigned TyposCorrected;
7018 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7019 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7021 /// \brief A cache containing identifiers for which typo correction failed and
7022 /// their locations, so that repeated attempts to correct an identifier in a
7023 /// given location are ignored if typo correction already failed for it.
7024 IdentifierSourceLocations TypoCorrectionFailures;
7026 /// \brief Worker object for performing CFG-based warnings.
7027 sema::AnalysisBasedWarnings AnalysisWarnings;
7028 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7030 /// \brief An entity for which implicit template instantiation is required.
7032 /// The source location associated with the declaration is the first place in
7033 /// the source code where the declaration was "used". It is not necessarily
7034 /// the point of instantiation (which will be either before or after the
7035 /// namespace-scope declaration that triggered this implicit instantiation),
7036 /// However, it is the location that diagnostics should generally refer to,
7037 /// because users will need to know what code triggered the instantiation.
7038 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7040 /// \brief The queue of implicit template instantiations that are required
7041 /// but have not yet been performed.
7042 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7044 class SavePendingInstantiationsAndVTableUsesRAII {
7046 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7047 : S(S), Enabled(Enabled) {
7048 if (!Enabled) return;
7050 SavedPendingInstantiations.swap(S.PendingInstantiations);
7051 SavedVTableUses.swap(S.VTableUses);
7054 ~SavePendingInstantiationsAndVTableUsesRAII() {
7055 if (!Enabled) return;
7057 // Restore the set of pending vtables.
7058 assert(S.VTableUses.empty() &&
7059 "VTableUses should be empty before it is discarded.");
7060 S.VTableUses.swap(SavedVTableUses);
7062 // Restore the set of pending implicit instantiations.
7063 assert(S.PendingInstantiations.empty() &&
7064 "PendingInstantiations should be empty before it is discarded.");
7065 S.PendingInstantiations.swap(SavedPendingInstantiations);
7070 SmallVector<VTableUse, 16> SavedVTableUses;
7071 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7075 /// \brief The queue of implicit template instantiations that are required
7076 /// and must be performed within the current local scope.
7078 /// This queue is only used for member functions of local classes in
7079 /// templates, which must be instantiated in the same scope as their
7080 /// enclosing function, so that they can reference function-local
7081 /// types, static variables, enumerators, etc.
7082 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7084 class SavePendingLocalImplicitInstantiationsRAII {
7086 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7087 SavedPendingLocalImplicitInstantiations.swap(
7088 S.PendingLocalImplicitInstantiations);
7091 ~SavePendingLocalImplicitInstantiationsRAII() {
7092 assert(S.PendingLocalImplicitInstantiations.empty() &&
7093 "there shouldn't be any pending local implicit instantiations");
7094 SavedPendingLocalImplicitInstantiations.swap(
7095 S.PendingLocalImplicitInstantiations);
7100 std::deque<PendingImplicitInstantiation>
7101 SavedPendingLocalImplicitInstantiations;
7104 /// A helper class for building up ExtParameterInfos.
7105 class ExtParameterInfoBuilder {
7106 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7107 bool HasInteresting = false;
7110 /// Set the ExtParameterInfo for the parameter at the given index,
7112 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7113 assert(Infos.size() <= index);
7114 Infos.resize(index);
7115 Infos.push_back(info);
7117 if (!HasInteresting)
7118 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7121 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7122 /// ExtParameterInfo array we've built up.
7123 const FunctionProtoType::ExtParameterInfo *
7124 getPointerOrNull(unsigned numParams) {
7125 if (!HasInteresting) return nullptr;
7126 Infos.resize(numParams);
7127 return Infos.data();
7131 void PerformPendingInstantiations(bool LocalOnly = false);
7133 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7134 const MultiLevelTemplateArgumentList &TemplateArgs,
7135 SourceLocation Loc, DeclarationName Entity);
7137 QualType SubstType(QualType T,
7138 const MultiLevelTemplateArgumentList &TemplateArgs,
7139 SourceLocation Loc, DeclarationName Entity);
7141 TypeSourceInfo *SubstType(TypeLoc TL,
7142 const MultiLevelTemplateArgumentList &TemplateArgs,
7143 SourceLocation Loc, DeclarationName Entity);
7145 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7146 const MultiLevelTemplateArgumentList &TemplateArgs,
7148 DeclarationName Entity,
7149 CXXRecordDecl *ThisContext,
7150 unsigned ThisTypeQuals);
7151 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7152 const MultiLevelTemplateArgumentList &Args);
7153 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7154 const MultiLevelTemplateArgumentList &TemplateArgs,
7155 int indexAdjustment,
7156 Optional<unsigned> NumExpansions,
7157 bool ExpectParameterPack);
7158 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7159 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7160 const MultiLevelTemplateArgumentList &TemplateArgs,
7161 SmallVectorImpl<QualType> &ParamTypes,
7162 SmallVectorImpl<ParmVarDecl *> *OutParams,
7163 ExtParameterInfoBuilder &ParamInfos);
7164 ExprResult SubstExpr(Expr *E,
7165 const MultiLevelTemplateArgumentList &TemplateArgs);
7167 /// \brief Substitute the given template arguments into a list of
7168 /// expressions, expanding pack expansions if required.
7170 /// \param Exprs The list of expressions to substitute into.
7172 /// \param IsCall Whether this is some form of call, in which case
7173 /// default arguments will be dropped.
7175 /// \param TemplateArgs The set of template arguments to substitute.
7177 /// \param Outputs Will receive all of the substituted arguments.
7179 /// \returns true if an error occurred, false otherwise.
7180 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7181 const MultiLevelTemplateArgumentList &TemplateArgs,
7182 SmallVectorImpl<Expr *> &Outputs);
7184 StmtResult SubstStmt(Stmt *S,
7185 const MultiLevelTemplateArgumentList &TemplateArgs);
7187 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7188 const MultiLevelTemplateArgumentList &TemplateArgs);
7190 ExprResult SubstInitializer(Expr *E,
7191 const MultiLevelTemplateArgumentList &TemplateArgs,
7192 bool CXXDirectInit);
7195 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7196 CXXRecordDecl *Pattern,
7197 const MultiLevelTemplateArgumentList &TemplateArgs);
7200 InstantiateClass(SourceLocation PointOfInstantiation,
7201 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7202 const MultiLevelTemplateArgumentList &TemplateArgs,
7203 TemplateSpecializationKind TSK,
7204 bool Complain = true);
7206 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7207 EnumDecl *Instantiation, EnumDecl *Pattern,
7208 const MultiLevelTemplateArgumentList &TemplateArgs,
7209 TemplateSpecializationKind TSK);
7211 bool InstantiateInClassInitializer(
7212 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7213 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7215 struct LateInstantiatedAttribute {
7216 const Attr *TmplAttr;
7217 LocalInstantiationScope *Scope;
7220 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7222 : TmplAttr(A), Scope(S), NewDecl(D)
7225 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7227 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7228 const Decl *Pattern, Decl *Inst,
7229 LateInstantiatedAttrVec *LateAttrs = nullptr,
7230 LocalInstantiationScope *OuterMostScope = nullptr);
7233 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7234 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7235 TemplateSpecializationKind TSK,
7236 bool Complain = true);
7238 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7239 CXXRecordDecl *Instantiation,
7240 const MultiLevelTemplateArgumentList &TemplateArgs,
7241 TemplateSpecializationKind TSK);
7243 void InstantiateClassTemplateSpecializationMembers(
7244 SourceLocation PointOfInstantiation,
7245 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7246 TemplateSpecializationKind TSK);
7248 NestedNameSpecifierLoc
7249 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7250 const MultiLevelTemplateArgumentList &TemplateArgs);
7253 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7254 const MultiLevelTemplateArgumentList &TemplateArgs);
7256 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7258 const MultiLevelTemplateArgumentList &TemplateArgs);
7259 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7260 TemplateArgumentListInfo &Result,
7261 const MultiLevelTemplateArgumentList &TemplateArgs);
7263 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7264 FunctionDecl *Function);
7265 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7266 FunctionDecl *Function,
7267 bool Recursive = false,
7268 bool DefinitionRequired = false,
7269 bool AtEndOfTU = false);
7270 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7271 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7272 const TemplateArgumentList &TemplateArgList,
7273 const TemplateArgumentListInfo &TemplateArgsInfo,
7274 SmallVectorImpl<TemplateArgument> &Converted,
7275 SourceLocation PointOfInstantiation, void *InsertPos,
7276 LateInstantiatedAttrVec *LateAttrs = nullptr,
7277 LocalInstantiationScope *StartingScope = nullptr);
7278 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7279 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7280 const MultiLevelTemplateArgumentList &TemplateArgs);
7282 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7283 const MultiLevelTemplateArgumentList &TemplateArgs,
7284 LateInstantiatedAttrVec *LateAttrs,
7286 LocalInstantiationScope *StartingScope,
7287 bool InstantiatingVarTemplate = false);
7288 void InstantiateVariableInitializer(
7289 VarDecl *Var, VarDecl *OldVar,
7290 const MultiLevelTemplateArgumentList &TemplateArgs);
7291 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7292 VarDecl *Var, bool Recursive = false,
7293 bool DefinitionRequired = false,
7294 bool AtEndOfTU = false);
7295 void InstantiateStaticDataMemberDefinition(
7296 SourceLocation PointOfInstantiation,
7298 bool Recursive = false,
7299 bool DefinitionRequired = false);
7301 void InstantiateMemInitializers(CXXConstructorDecl *New,
7302 const CXXConstructorDecl *Tmpl,
7303 const MultiLevelTemplateArgumentList &TemplateArgs);
7305 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7306 const MultiLevelTemplateArgumentList &TemplateArgs);
7307 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7308 const MultiLevelTemplateArgumentList &TemplateArgs);
7310 // Objective-C declarations.
7311 enum ObjCContainerKind {
7318 OCK_CategoryImplementation
7320 ObjCContainerKind getObjCContainerKind() const;
7322 DeclResult actOnObjCTypeParam(Scope *S,
7323 ObjCTypeParamVariance variance,
7324 SourceLocation varianceLoc,
7326 IdentifierInfo *paramName,
7327 SourceLocation paramLoc,
7328 SourceLocation colonLoc,
7329 ParsedType typeBound);
7331 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7332 ArrayRef<Decl *> typeParams,
7333 SourceLocation rAngleLoc);
7334 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7336 Decl *ActOnStartClassInterface(Scope *S,
7337 SourceLocation AtInterfaceLoc,
7338 IdentifierInfo *ClassName,
7339 SourceLocation ClassLoc,
7340 ObjCTypeParamList *typeParamList,
7341 IdentifierInfo *SuperName,
7342 SourceLocation SuperLoc,
7343 ArrayRef<ParsedType> SuperTypeArgs,
7344 SourceRange SuperTypeArgsRange,
7345 Decl * const *ProtoRefs,
7346 unsigned NumProtoRefs,
7347 const SourceLocation *ProtoLocs,
7348 SourceLocation EndProtoLoc,
7349 AttributeList *AttrList);
7351 void ActOnSuperClassOfClassInterface(Scope *S,
7352 SourceLocation AtInterfaceLoc,
7353 ObjCInterfaceDecl *IDecl,
7354 IdentifierInfo *ClassName,
7355 SourceLocation ClassLoc,
7356 IdentifierInfo *SuperName,
7357 SourceLocation SuperLoc,
7358 ArrayRef<ParsedType> SuperTypeArgs,
7359 SourceRange SuperTypeArgsRange);
7361 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7362 IdentifierInfo *SuperName,
7363 SourceLocation SuperLoc);
7365 Decl *ActOnCompatibilityAlias(
7366 SourceLocation AtCompatibilityAliasLoc,
7367 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7368 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7370 bool CheckForwardProtocolDeclarationForCircularDependency(
7371 IdentifierInfo *PName,
7372 SourceLocation &PLoc, SourceLocation PrevLoc,
7373 const ObjCList<ObjCProtocolDecl> &PList);
7375 Decl *ActOnStartProtocolInterface(
7376 SourceLocation AtProtoInterfaceLoc,
7377 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7378 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7379 const SourceLocation *ProtoLocs,
7380 SourceLocation EndProtoLoc,
7381 AttributeList *AttrList);
7383 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7384 IdentifierInfo *ClassName,
7385 SourceLocation ClassLoc,
7386 ObjCTypeParamList *typeParamList,
7387 IdentifierInfo *CategoryName,
7388 SourceLocation CategoryLoc,
7389 Decl * const *ProtoRefs,
7390 unsigned NumProtoRefs,
7391 const SourceLocation *ProtoLocs,
7392 SourceLocation EndProtoLoc);
7394 Decl *ActOnStartClassImplementation(
7395 SourceLocation AtClassImplLoc,
7396 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7397 IdentifierInfo *SuperClassname,
7398 SourceLocation SuperClassLoc);
7400 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7401 IdentifierInfo *ClassName,
7402 SourceLocation ClassLoc,
7403 IdentifierInfo *CatName,
7404 SourceLocation CatLoc);
7406 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7407 ArrayRef<Decl *> Decls);
7409 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7410 IdentifierInfo **IdentList,
7411 SourceLocation *IdentLocs,
7412 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7415 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7416 ArrayRef<IdentifierLocPair> IdentList,
7417 AttributeList *attrList);
7419 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7420 ArrayRef<IdentifierLocPair> ProtocolId,
7421 SmallVectorImpl<Decl *> &Protocols);
7423 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7424 SourceLocation ProtocolLoc,
7425 IdentifierInfo *TypeArgId,
7426 SourceLocation TypeArgLoc,
7427 bool SelectProtocolFirst = false);
7429 /// Given a list of identifiers (and their locations), resolve the
7430 /// names to either Objective-C protocol qualifiers or type
7431 /// arguments, as appropriate.
7432 void actOnObjCTypeArgsOrProtocolQualifiers(
7434 ParsedType baseType,
7435 SourceLocation lAngleLoc,
7436 ArrayRef<IdentifierInfo *> identifiers,
7437 ArrayRef<SourceLocation> identifierLocs,
7438 SourceLocation rAngleLoc,
7439 SourceLocation &typeArgsLAngleLoc,
7440 SmallVectorImpl<ParsedType> &typeArgs,
7441 SourceLocation &typeArgsRAngleLoc,
7442 SourceLocation &protocolLAngleLoc,
7443 SmallVectorImpl<Decl *> &protocols,
7444 SourceLocation &protocolRAngleLoc,
7445 bool warnOnIncompleteProtocols);
7447 /// Build a an Objective-C protocol-qualified 'id' type where no
7448 /// base type was specified.
7449 TypeResult actOnObjCProtocolQualifierType(
7450 SourceLocation lAngleLoc,
7451 ArrayRef<Decl *> protocols,
7452 ArrayRef<SourceLocation> protocolLocs,
7453 SourceLocation rAngleLoc);
7455 /// Build a specialized and/or protocol-qualified Objective-C type.
7456 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7459 ParsedType BaseType,
7460 SourceLocation TypeArgsLAngleLoc,
7461 ArrayRef<ParsedType> TypeArgs,
7462 SourceLocation TypeArgsRAngleLoc,
7463 SourceLocation ProtocolLAngleLoc,
7464 ArrayRef<Decl *> Protocols,
7465 ArrayRef<SourceLocation> ProtocolLocs,
7466 SourceLocation ProtocolRAngleLoc);
7468 /// Build an Objective-C object pointer type.
7469 QualType BuildObjCObjectType(QualType BaseType,
7471 SourceLocation TypeArgsLAngleLoc,
7472 ArrayRef<TypeSourceInfo *> TypeArgs,
7473 SourceLocation TypeArgsRAngleLoc,
7474 SourceLocation ProtocolLAngleLoc,
7475 ArrayRef<ObjCProtocolDecl *> Protocols,
7476 ArrayRef<SourceLocation> ProtocolLocs,
7477 SourceLocation ProtocolRAngleLoc,
7478 bool FailOnError = false);
7480 /// Check the application of the Objective-C '__kindof' qualifier to
7482 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7484 /// Ensure attributes are consistent with type.
7485 /// \param [in, out] Attributes The attributes to check; they will
7486 /// be modified to be consistent with \p PropertyTy.
7487 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7489 unsigned &Attributes,
7490 bool propertyInPrimaryClass);
7492 /// Process the specified property declaration and create decls for the
7493 /// setters and getters as needed.
7494 /// \param property The property declaration being processed
7495 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7498 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7499 ObjCPropertyDecl *SuperProperty,
7500 const IdentifierInfo *Name,
7501 bool OverridingProtocolProperty);
7503 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7504 ObjCInterfaceDecl *ID);
7506 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7507 ArrayRef<Decl *> allMethods = None,
7508 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7510 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7511 SourceLocation LParenLoc,
7512 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7513 Selector GetterSel, Selector SetterSel,
7514 tok::ObjCKeywordKind MethodImplKind,
7515 DeclContext *lexicalDC = nullptr);
7517 Decl *ActOnPropertyImplDecl(Scope *S,
7518 SourceLocation AtLoc,
7519 SourceLocation PropertyLoc,
7521 IdentifierInfo *PropertyId,
7522 IdentifierInfo *PropertyIvar,
7523 SourceLocation PropertyIvarLoc,
7524 ObjCPropertyQueryKind QueryKind);
7526 enum ObjCSpecialMethodKind {
7532 OSMK_NonRetainingInit
7535 struct ObjCArgInfo {
7536 IdentifierInfo *Name;
7537 SourceLocation NameLoc;
7538 // The Type is null if no type was specified, and the DeclSpec is invalid
7541 ObjCDeclSpec DeclSpec;
7543 /// ArgAttrs - Attribute list for this argument.
7544 AttributeList *ArgAttrs;
7547 Decl *ActOnMethodDeclaration(
7549 SourceLocation BeginLoc, // location of the + or -.
7550 SourceLocation EndLoc, // location of the ; or {.
7551 tok::TokenKind MethodType,
7552 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7553 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7554 // optional arguments. The number of types/arguments is obtained
7555 // from the Sel.getNumArgs().
7556 ObjCArgInfo *ArgInfo,
7557 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7558 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7559 bool isVariadic, bool MethodDefinition);
7561 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7562 const ObjCObjectPointerType *OPT,
7564 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7567 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7568 bool inferObjCARCLifetime(ValueDecl *decl);
7571 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7573 SourceLocation OpLoc,
7574 DeclarationName MemberName,
7575 SourceLocation MemberLoc,
7576 SourceLocation SuperLoc, QualType SuperType,
7580 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7581 IdentifierInfo &propertyName,
7582 SourceLocation receiverNameLoc,
7583 SourceLocation propertyNameLoc);
7585 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7587 /// \brief Describes the kind of message expression indicated by a message
7588 /// send that starts with an identifier.
7589 enum ObjCMessageKind {
7590 /// \brief The message is sent to 'super'.
7592 /// \brief The message is an instance message.
7593 ObjCInstanceMessage,
7594 /// \brief The message is a class message, and the identifier is a type
7599 ObjCMessageKind getObjCMessageKind(Scope *S,
7600 IdentifierInfo *Name,
7601 SourceLocation NameLoc,
7603 bool HasTrailingDot,
7604 ParsedType &ReceiverType);
7606 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7608 SourceLocation LBracLoc,
7609 ArrayRef<SourceLocation> SelectorLocs,
7610 SourceLocation RBracLoc,
7613 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7614 QualType ReceiverType,
7615 SourceLocation SuperLoc,
7617 ObjCMethodDecl *Method,
7618 SourceLocation LBracLoc,
7619 ArrayRef<SourceLocation> SelectorLocs,
7620 SourceLocation RBracLoc,
7622 bool isImplicit = false);
7624 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7625 bool isSuperReceiver,
7628 ObjCMethodDecl *Method,
7631 ExprResult ActOnClassMessage(Scope *S,
7632 ParsedType Receiver,
7634 SourceLocation LBracLoc,
7635 ArrayRef<SourceLocation> SelectorLocs,
7636 SourceLocation RBracLoc,
7639 ExprResult BuildInstanceMessage(Expr *Receiver,
7640 QualType ReceiverType,
7641 SourceLocation SuperLoc,
7643 ObjCMethodDecl *Method,
7644 SourceLocation LBracLoc,
7645 ArrayRef<SourceLocation> SelectorLocs,
7646 SourceLocation RBracLoc,
7648 bool isImplicit = false);
7650 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7651 QualType ReceiverType,
7654 ObjCMethodDecl *Method,
7657 ExprResult ActOnInstanceMessage(Scope *S,
7660 SourceLocation LBracLoc,
7661 ArrayRef<SourceLocation> SelectorLocs,
7662 SourceLocation RBracLoc,
7665 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7666 ObjCBridgeCastKind Kind,
7667 SourceLocation BridgeKeywordLoc,
7668 TypeSourceInfo *TSInfo,
7671 ExprResult ActOnObjCBridgedCast(Scope *S,
7672 SourceLocation LParenLoc,
7673 ObjCBridgeCastKind Kind,
7674 SourceLocation BridgeKeywordLoc,
7676 SourceLocation RParenLoc,
7679 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7681 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7683 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7686 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7687 QualType DestType, QualType SrcType,
7688 ObjCInterfaceDecl *&RelatedClass,
7689 ObjCMethodDecl *&ClassMethod,
7690 ObjCMethodDecl *&InstanceMethod,
7691 TypedefNameDecl *&TDNDecl,
7692 bool CfToNs, bool Diagnose = true);
7694 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7695 QualType DestType, QualType SrcType,
7696 Expr *&SrcExpr, bool Diagnose = true);
7698 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7699 bool Diagnose = true);
7701 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7703 /// \brief Check whether the given new method is a valid override of the
7704 /// given overridden method, and set any properties that should be inherited.
7705 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7706 const ObjCMethodDecl *Overridden);
7708 /// \brief Describes the compatibility of a result type with its method.
7709 enum ResultTypeCompatibilityKind {
7715 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7716 ObjCInterfaceDecl *CurrentClass,
7717 ResultTypeCompatibilityKind RTC);
7719 enum PragmaOptionsAlignKind {
7720 POAK_Native, // #pragma options align=native
7721 POAK_Natural, // #pragma options align=natural
7722 POAK_Packed, // #pragma options align=packed
7723 POAK_Power, // #pragma options align=power
7724 POAK_Mac68k, // #pragma options align=mac68k
7725 POAK_Reset // #pragma options align=reset
7728 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7729 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7730 SourceLocation PragmaLoc);
7732 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7733 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
7734 StringRef SlotLabel, Expr *Alignment);
7736 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7737 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7739 /// ActOnPragmaMSComment - Called on well formed
7740 /// \#pragma comment(kind, "arg").
7741 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
7744 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7745 /// pointers_to_members(representation method[, general purpose
7746 /// representation]).
7747 void ActOnPragmaMSPointersToMembers(
7748 LangOptions::PragmaMSPointersToMembersKind Kind,
7749 SourceLocation PragmaLoc);
7751 /// \brief Called on well formed \#pragma vtordisp().
7752 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
7753 SourceLocation PragmaLoc,
7754 MSVtorDispAttr::Mode Value);
7756 enum PragmaSectionKind {
7763 bool UnifySection(StringRef SectionName,
7765 DeclaratorDecl *TheDecl);
7766 bool UnifySection(StringRef SectionName,
7768 SourceLocation PragmaSectionLocation);
7770 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7771 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7772 PragmaMsStackAction Action,
7773 llvm::StringRef StackSlotLabel,
7774 StringLiteral *SegmentName,
7775 llvm::StringRef PragmaName);
7777 /// \brief Called on well formed \#pragma section().
7778 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7779 int SectionFlags, StringLiteral *SegmentName);
7781 /// \brief Called on well-formed \#pragma init_seg().
7782 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7783 StringLiteral *SegmentName);
7785 /// \brief Called on #pragma clang __debug dump II
7786 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
7788 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7789 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
7792 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7793 void ActOnPragmaUnused(const Token &Identifier,
7795 SourceLocation PragmaLoc);
7797 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7798 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7799 SourceLocation PragmaLoc);
7801 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7802 SourceLocation Loc);
7803 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7805 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7806 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7807 SourceLocation PragmaLoc,
7808 SourceLocation WeakNameLoc);
7810 /// ActOnPragmaRedefineExtname - Called on well formed
7811 /// \#pragma redefine_extname oldname newname.
7812 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7813 IdentifierInfo* AliasName,
7814 SourceLocation PragmaLoc,
7815 SourceLocation WeakNameLoc,
7816 SourceLocation AliasNameLoc);
7818 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7819 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7820 IdentifierInfo* AliasName,
7821 SourceLocation PragmaLoc,
7822 SourceLocation WeakNameLoc,
7823 SourceLocation AliasNameLoc);
7825 /// ActOnPragmaFPContract - Called on well formed
7826 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7827 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7829 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7830 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7831 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7833 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7834 void AddMsStructLayoutForRecord(RecordDecl *RD);
7836 /// FreePackedContext - Deallocate and null out PackContext.
7837 void FreePackedContext();
7839 /// PushNamespaceVisibilityAttr - Note that we've entered a
7840 /// namespace with a visibility attribute.
7841 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7842 SourceLocation Loc);
7844 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7845 /// add an appropriate visibility attribute.
7846 void AddPushedVisibilityAttribute(Decl *RD);
7848 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7849 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7850 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7852 /// FreeVisContext - Deallocate and null out VisContext.
7853 void FreeVisContext();
7855 /// AddCFAuditedAttribute - Check whether we're currently within
7856 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7857 /// the appropriate attribute.
7858 void AddCFAuditedAttribute(Decl *D);
7860 /// \brief Called on well formed \#pragma clang optimize.
7861 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7863 /// \brief Get the location for the currently active "\#pragma clang optimize
7864 /// off". If this location is invalid, then the state of the pragma is "on".
7865 SourceLocation getOptimizeOffPragmaLocation() const {
7866 return OptimizeOffPragmaLocation;
7869 /// \brief Only called on function definitions; if there is a pragma in scope
7870 /// with the effect of a range-based optnone, consider marking the function
7871 /// with attribute optnone.
7872 void AddRangeBasedOptnone(FunctionDecl *FD);
7874 /// \brief Adds the 'optnone' attribute to the function declaration if there
7875 /// are no conflicts; Loc represents the location causing the 'optnone'
7876 /// attribute to be added (usually because of a pragma).
7877 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7879 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7880 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7881 unsigned SpellingListIndex, bool IsPackExpansion);
7882 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7883 unsigned SpellingListIndex, bool IsPackExpansion);
7885 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7887 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7888 unsigned SpellingListIndex);
7890 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7892 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7893 unsigned SpellingListIndex);
7895 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7897 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7898 Expr *MinBlocks, unsigned SpellingListIndex);
7900 /// AddModeAttr - Adds a mode attribute to a particular declaration.
7901 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
7902 unsigned SpellingListIndex, bool InInstantiation = false);
7904 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
7905 ParameterABI ABI, unsigned SpellingListIndex);
7907 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
7908 unsigned SpellingListIndex, bool isNSConsumed,
7909 bool isTemplateInstantiation);
7911 //===--------------------------------------------------------------------===//
7912 // C++ Coroutines TS
7914 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7915 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7916 StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
7918 ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
7919 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
7920 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
7922 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
7924 //===--------------------------------------------------------------------===//
7925 // OpenMP directives and clauses.
7928 void *VarDataSharingAttributesStack;
7929 /// Set to true inside '#pragma omp declare target' region.
7930 bool IsInOpenMPDeclareTargetContext = false;
7931 /// \brief Initialization of data-sharing attributes stack.
7932 void InitDataSharingAttributesStack();
7933 void DestroyDataSharingAttributesStack();
7935 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
7936 bool StrictlyPositive = true);
7937 /// Returns OpenMP nesting level for current directive.
7938 unsigned getOpenMPNestingLevel() const;
7941 /// \brief Return true if the provided declaration \a VD should be captured by
7943 /// \param Level Relative level of nested OpenMP construct for that the check
7945 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
7947 /// \brief Check if the specified variable is used in one of the private
7948 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
7950 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
7951 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7952 ExprObjectKind OK, SourceLocation Loc);
7954 /// \brief Check if the specified variable is used in 'private' clause.
7955 /// \param Level Relative level of nested OpenMP construct for that the check
7957 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
7959 /// \brief Check if the specified variable is captured by 'target' directive.
7960 /// \param Level Relative level of nested OpenMP construct for that the check
7962 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
7964 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7966 /// \brief Called on start of new data sharing attribute block.
7967 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7968 const DeclarationNameInfo &DirName, Scope *CurScope,
7969 SourceLocation Loc);
7970 /// \brief Start analysis of clauses.
7971 void StartOpenMPClause(OpenMPClauseKind K);
7972 /// \brief End analysis of clauses.
7973 void EndOpenMPClause();
7974 /// \brief Called on end of data sharing attribute block.
7975 void EndOpenMPDSABlock(Stmt *CurDirective);
7977 /// \brief Check if the current region is an OpenMP loop region and if it is,
7978 /// mark loop control variable, used in \p Init for loop initialization, as
7979 /// private by default.
7980 /// \param Init First part of the for loop.
7981 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7983 // OpenMP directives and clauses.
7984 /// \brief Called on correct id-expression from the '#pragma omp
7986 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7987 CXXScopeSpec &ScopeSpec,
7988 const DeclarationNameInfo &Id);
7989 /// \brief Called on well-formed '#pragma omp threadprivate'.
7990 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7992 ArrayRef<Expr *> VarList);
7993 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7994 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7996 ArrayRef<Expr *> VarList);
7997 /// \brief Check if the specified type is allowed to be used in 'omp declare
7998 /// reduction' construct.
7999 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8000 TypeResult ParsedType);
8001 /// \brief Called on start of '#pragma omp declare reduction'.
8002 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8003 Scope *S, DeclContext *DC, DeclarationName Name,
8004 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8005 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8006 /// \brief Initialize declare reduction construct initializer.
8007 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8008 /// \brief Finish current declare reduction construct initializer.
8009 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8010 /// \brief Initialize declare reduction construct initializer.
8011 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8012 /// \brief Finish current declare reduction construct initializer.
8013 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8014 /// \brief Called at the end of '#pragma omp declare reduction'.
8015 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8016 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8018 /// Called on the start of target region i.e. '#pragma omp declare target'.
8019 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8020 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8021 void ActOnFinishOpenMPDeclareTargetDirective();
8022 /// Called on correct id-expression from the '#pragma omp declare target'.
8023 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8024 const DeclarationNameInfo &Id,
8025 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8026 NamedDeclSetType &SameDirectiveDecls);
8027 /// Check declaration inside target region.
8028 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8029 /// Return true inside OpenMP target region.
8030 bool isInOpenMPDeclareTargetContext() const {
8031 return IsInOpenMPDeclareTargetContext;
8034 /// \brief Initialization of captured region for OpenMP region.
8035 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8036 /// \brief End of OpenMP region.
8038 /// \param S Statement associated with the current OpenMP region.
8039 /// \param Clauses List of clauses for the current OpenMP region.
8041 /// \returns Statement for finished OpenMP region.
8042 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8043 StmtResult ActOnOpenMPExecutableDirective(
8044 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8045 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8046 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8047 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8048 /// of the associated statement.
8049 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8051 SourceLocation StartLoc,
8052 SourceLocation EndLoc);
8053 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8054 /// of the associated statement.
8055 StmtResult ActOnOpenMPSimdDirective(
8056 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8057 SourceLocation EndLoc,
8058 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8059 /// \brief Called on well-formed '\#pragma omp for' after parsing
8060 /// of the associated statement.
8061 StmtResult ActOnOpenMPForDirective(
8062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8063 SourceLocation EndLoc,
8064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8065 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8066 /// of the associated statement.
8067 StmtResult ActOnOpenMPForSimdDirective(
8068 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8069 SourceLocation EndLoc,
8070 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8071 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8072 /// of the associated statement.
8073 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8074 Stmt *AStmt, SourceLocation StartLoc,
8075 SourceLocation EndLoc);
8076 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8077 /// associated statement.
8078 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8079 SourceLocation EndLoc);
8080 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8081 /// associated statement.
8082 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8083 Stmt *AStmt, SourceLocation StartLoc,
8084 SourceLocation EndLoc);
8085 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8086 /// associated statement.
8087 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8088 SourceLocation EndLoc);
8089 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8090 /// associated statement.
8091 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8092 ArrayRef<OMPClause *> Clauses,
8093 Stmt *AStmt, SourceLocation StartLoc,
8094 SourceLocation EndLoc);
8095 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8096 /// of the associated statement.
8097 StmtResult ActOnOpenMPParallelForDirective(
8098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8099 SourceLocation EndLoc,
8100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8101 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8102 /// parsing of the associated statement.
8103 StmtResult ActOnOpenMPParallelForSimdDirective(
8104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8105 SourceLocation EndLoc,
8106 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8107 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8108 /// parsing of the associated statement.
8109 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8111 SourceLocation StartLoc,
8112 SourceLocation EndLoc);
8113 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8114 /// associated statement.
8115 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8116 Stmt *AStmt, SourceLocation StartLoc,
8117 SourceLocation EndLoc);
8118 /// \brief Called on well-formed '\#pragma omp taskyield'.
8119 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8120 SourceLocation EndLoc);
8121 /// \brief Called on well-formed '\#pragma omp barrier'.
8122 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8123 SourceLocation EndLoc);
8124 /// \brief Called on well-formed '\#pragma omp taskwait'.
8125 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8126 SourceLocation EndLoc);
8127 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8128 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8129 SourceLocation EndLoc);
8130 /// \brief Called on well-formed '\#pragma omp flush'.
8131 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8132 SourceLocation StartLoc,
8133 SourceLocation EndLoc);
8134 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8135 /// associated statement.
8136 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8137 Stmt *AStmt, SourceLocation StartLoc,
8138 SourceLocation EndLoc);
8139 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8140 /// associated statement.
8141 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8142 Stmt *AStmt, SourceLocation StartLoc,
8143 SourceLocation EndLoc);
8144 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8145 /// associated statement.
8146 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8147 Stmt *AStmt, SourceLocation StartLoc,
8148 SourceLocation EndLoc);
8149 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8150 /// the associated statement.
8151 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8152 Stmt *AStmt, SourceLocation StartLoc,
8153 SourceLocation EndLoc);
8154 /// \brief Called on well-formed '\#pragma omp target enter data' after
8155 /// parsing of the associated statement.
8156 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8157 SourceLocation StartLoc,
8158 SourceLocation EndLoc);
8159 /// \brief Called on well-formed '\#pragma omp target exit data' after
8160 /// parsing of the associated statement.
8161 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8162 SourceLocation StartLoc,
8163 SourceLocation EndLoc);
8164 /// \brief Called on well-formed '\#pragma omp target parallel' after
8165 /// parsing of the associated statement.
8166 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8168 SourceLocation StartLoc,
8169 SourceLocation EndLoc);
8170 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8171 /// parsing of the associated statement.
8172 StmtResult ActOnOpenMPTargetParallelForDirective(
8173 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8174 SourceLocation EndLoc,
8175 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8176 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8177 /// associated statement.
8178 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8179 Stmt *AStmt, SourceLocation StartLoc,
8180 SourceLocation EndLoc);
8181 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8183 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8184 SourceLocation EndLoc,
8185 OpenMPDirectiveKind CancelRegion);
8186 /// \brief Called on well-formed '\#pragma omp cancel'.
8187 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8188 SourceLocation StartLoc,
8189 SourceLocation EndLoc,
8190 OpenMPDirectiveKind CancelRegion);
8191 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8192 /// associated statement.
8193 StmtResult ActOnOpenMPTaskLoopDirective(
8194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8195 SourceLocation EndLoc,
8196 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8197 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8198 /// the associated statement.
8199 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8200 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8201 SourceLocation EndLoc,
8202 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8203 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8204 /// of the associated statement.
8205 StmtResult ActOnOpenMPDistributeDirective(
8206 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8207 SourceLocation EndLoc,
8208 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8209 /// \brief Called on well-formed '\#pragma omp target update'.
8210 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8211 SourceLocation StartLoc,
8212 SourceLocation EndLoc);
8213 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8214 /// parsing of the associated statement.
8215 StmtResult ActOnOpenMPDistributeParallelForDirective(
8216 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8217 SourceLocation EndLoc,
8218 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8219 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8220 /// after parsing of the associated statement.
8221 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8222 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8223 SourceLocation EndLoc,
8224 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8225 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8226 /// parsing of the associated statement.
8227 StmtResult ActOnOpenMPDistributeSimdDirective(
8228 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8229 SourceLocation EndLoc,
8230 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8231 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8232 /// parsing of the associated statement.
8233 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8234 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8235 SourceLocation EndLoc,
8236 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8238 /// Checks correctness of linear modifiers.
8239 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8240 SourceLocation LinLoc);
8241 /// Checks that the specified declaration matches requirements for the linear
8243 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8244 OpenMPLinearClauseKind LinKind, QualType Type);
8246 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8247 /// the associated method/function.
8248 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8249 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8250 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8251 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8252 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8254 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8256 SourceLocation StartLoc,
8257 SourceLocation LParenLoc,
8258 SourceLocation EndLoc);
8259 /// \brief Called on well-formed 'if' clause.
8260 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8261 Expr *Condition, SourceLocation StartLoc,
8262 SourceLocation LParenLoc,
8263 SourceLocation NameModifierLoc,
8264 SourceLocation ColonLoc,
8265 SourceLocation EndLoc);
8266 /// \brief Called on well-formed 'final' clause.
8267 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8268 SourceLocation LParenLoc,
8269 SourceLocation EndLoc);
8270 /// \brief Called on well-formed 'num_threads' clause.
8271 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8272 SourceLocation StartLoc,
8273 SourceLocation LParenLoc,
8274 SourceLocation EndLoc);
8275 /// \brief Called on well-formed 'safelen' clause.
8276 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8277 SourceLocation StartLoc,
8278 SourceLocation LParenLoc,
8279 SourceLocation EndLoc);
8280 /// \brief Called on well-formed 'simdlen' clause.
8281 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8282 SourceLocation LParenLoc,
8283 SourceLocation EndLoc);
8284 /// \brief Called on well-formed 'collapse' clause.
8285 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8286 SourceLocation StartLoc,
8287 SourceLocation LParenLoc,
8288 SourceLocation EndLoc);
8289 /// \brief Called on well-formed 'ordered' clause.
8291 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8292 SourceLocation LParenLoc = SourceLocation(),
8293 Expr *NumForLoops = nullptr);
8294 /// \brief Called on well-formed 'grainsize' clause.
8295 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8296 SourceLocation LParenLoc,
8297 SourceLocation EndLoc);
8298 /// \brief Called on well-formed 'num_tasks' clause.
8299 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8300 SourceLocation LParenLoc,
8301 SourceLocation EndLoc);
8302 /// \brief Called on well-formed 'hint' clause.
8303 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8304 SourceLocation LParenLoc,
8305 SourceLocation EndLoc);
8307 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8309 SourceLocation ArgumentLoc,
8310 SourceLocation StartLoc,
8311 SourceLocation LParenLoc,
8312 SourceLocation EndLoc);
8313 /// \brief Called on well-formed 'default' clause.
8314 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8315 SourceLocation KindLoc,
8316 SourceLocation StartLoc,
8317 SourceLocation LParenLoc,
8318 SourceLocation EndLoc);
8319 /// \brief Called on well-formed 'proc_bind' clause.
8320 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8321 SourceLocation KindLoc,
8322 SourceLocation StartLoc,
8323 SourceLocation LParenLoc,
8324 SourceLocation EndLoc);
8326 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8327 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8328 SourceLocation StartLoc, SourceLocation LParenLoc,
8329 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8330 SourceLocation EndLoc);
8331 /// \brief Called on well-formed 'schedule' clause.
8332 OMPClause *ActOnOpenMPScheduleClause(
8333 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8334 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8335 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8336 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8338 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8339 SourceLocation EndLoc);
8340 /// \brief Called on well-formed 'nowait' clause.
8341 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8342 SourceLocation EndLoc);
8343 /// \brief Called on well-formed 'untied' clause.
8344 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8345 SourceLocation EndLoc);
8346 /// \brief Called on well-formed 'mergeable' clause.
8347 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8348 SourceLocation EndLoc);
8349 /// \brief Called on well-formed 'read' clause.
8350 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8351 SourceLocation EndLoc);
8352 /// \brief Called on well-formed 'write' clause.
8353 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8354 SourceLocation EndLoc);
8355 /// \brief Called on well-formed 'update' clause.
8356 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8357 SourceLocation EndLoc);
8358 /// \brief Called on well-formed 'capture' clause.
8359 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8360 SourceLocation EndLoc);
8361 /// \brief Called on well-formed 'seq_cst' clause.
8362 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8363 SourceLocation EndLoc);
8364 /// \brief Called on well-formed 'threads' clause.
8365 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8366 SourceLocation EndLoc);
8367 /// \brief Called on well-formed 'simd' clause.
8368 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8369 SourceLocation EndLoc);
8370 /// \brief Called on well-formed 'nogroup' clause.
8371 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8372 SourceLocation EndLoc);
8374 OMPClause *ActOnOpenMPVarListClause(
8375 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8376 SourceLocation StartLoc, SourceLocation LParenLoc,
8377 SourceLocation ColonLoc, SourceLocation EndLoc,
8378 CXXScopeSpec &ReductionIdScopeSpec,
8379 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8380 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8381 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8382 SourceLocation DepLinMapLoc);
8383 /// \brief Called on well-formed 'private' clause.
8384 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8385 SourceLocation StartLoc,
8386 SourceLocation LParenLoc,
8387 SourceLocation EndLoc);
8388 /// \brief Called on well-formed 'firstprivate' clause.
8389 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8390 SourceLocation StartLoc,
8391 SourceLocation LParenLoc,
8392 SourceLocation EndLoc);
8393 /// \brief Called on well-formed 'lastprivate' clause.
8394 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8395 SourceLocation StartLoc,
8396 SourceLocation LParenLoc,
8397 SourceLocation EndLoc);
8398 /// \brief Called on well-formed 'shared' clause.
8399 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8400 SourceLocation StartLoc,
8401 SourceLocation LParenLoc,
8402 SourceLocation EndLoc);
8403 /// \brief Called on well-formed 'reduction' clause.
8404 OMPClause *ActOnOpenMPReductionClause(
8405 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8406 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8407 CXXScopeSpec &ReductionIdScopeSpec,
8408 const DeclarationNameInfo &ReductionId,
8409 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8410 /// \brief Called on well-formed 'linear' clause.
8412 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8413 SourceLocation StartLoc, SourceLocation LParenLoc,
8414 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8415 SourceLocation ColonLoc, SourceLocation EndLoc);
8416 /// \brief Called on well-formed 'aligned' clause.
8417 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8419 SourceLocation StartLoc,
8420 SourceLocation LParenLoc,
8421 SourceLocation ColonLoc,
8422 SourceLocation EndLoc);
8423 /// \brief Called on well-formed 'copyin' clause.
8424 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8425 SourceLocation StartLoc,
8426 SourceLocation LParenLoc,
8427 SourceLocation EndLoc);
8428 /// \brief Called on well-formed 'copyprivate' clause.
8429 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8430 SourceLocation StartLoc,
8431 SourceLocation LParenLoc,
8432 SourceLocation EndLoc);
8433 /// \brief Called on well-formed 'flush' pseudo clause.
8434 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8435 SourceLocation StartLoc,
8436 SourceLocation LParenLoc,
8437 SourceLocation EndLoc);
8438 /// \brief Called on well-formed 'depend' clause.
8440 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8441 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8442 SourceLocation StartLoc, SourceLocation LParenLoc,
8443 SourceLocation EndLoc);
8444 /// \brief Called on well-formed 'device' clause.
8445 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8446 SourceLocation LParenLoc,
8447 SourceLocation EndLoc);
8448 /// \brief Called on well-formed 'map' clause.
8450 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8451 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8452 SourceLocation MapLoc, SourceLocation ColonLoc,
8453 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8454 SourceLocation LParenLoc, SourceLocation EndLoc);
8455 /// \brief Called on well-formed 'num_teams' clause.
8456 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8457 SourceLocation LParenLoc,
8458 SourceLocation EndLoc);
8459 /// \brief Called on well-formed 'thread_limit' clause.
8460 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8461 SourceLocation StartLoc,
8462 SourceLocation LParenLoc,
8463 SourceLocation EndLoc);
8464 /// \brief Called on well-formed 'priority' clause.
8465 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8466 SourceLocation LParenLoc,
8467 SourceLocation EndLoc);
8468 /// \brief Called on well-formed 'dist_schedule' clause.
8469 OMPClause *ActOnOpenMPDistScheduleClause(
8470 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8471 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8472 SourceLocation CommaLoc, SourceLocation EndLoc);
8473 /// \brief Called on well-formed 'defaultmap' clause.
8474 OMPClause *ActOnOpenMPDefaultmapClause(
8475 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8476 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8477 SourceLocation KindLoc, SourceLocation EndLoc);
8478 /// \brief Called on well-formed 'to' clause.
8479 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8480 SourceLocation StartLoc,
8481 SourceLocation LParenLoc,
8482 SourceLocation EndLoc);
8483 /// \brief Called on well-formed 'from' clause.
8484 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8485 SourceLocation StartLoc,
8486 SourceLocation LParenLoc,
8487 SourceLocation EndLoc);
8488 /// Called on well-formed 'use_device_ptr' clause.
8489 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8490 SourceLocation StartLoc,
8491 SourceLocation LParenLoc,
8492 SourceLocation EndLoc);
8493 /// Called on well-formed 'is_device_ptr' clause.
8494 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8495 SourceLocation StartLoc,
8496 SourceLocation LParenLoc,
8497 SourceLocation EndLoc);
8499 /// \brief The kind of conversion being performed.
8500 enum CheckedConversionKind {
8501 /// \brief An implicit conversion.
8502 CCK_ImplicitConversion,
8503 /// \brief A C-style cast.
8505 /// \brief A functional-style cast.
8507 /// \brief A cast other than a C-style cast.
8511 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8512 /// cast. If there is already an implicit cast, merge into the existing one.
8513 /// If isLvalue, the result of the cast is an lvalue.
8514 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8515 ExprValueKind VK = VK_RValue,
8516 const CXXCastPath *BasePath = nullptr,
8517 CheckedConversionKind CCK
8518 = CCK_ImplicitConversion);
8520 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8521 /// to the conversion from scalar type ScalarTy to the Boolean type.
8522 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8524 /// IgnoredValueConversions - Given that an expression's result is
8525 /// syntactically ignored, perform any conversions that are
8527 ExprResult IgnoredValueConversions(Expr *E);
8529 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8530 // functions and arrays to their respective pointers (C99 6.3.2.1).
8531 ExprResult UsualUnaryConversions(Expr *E);
8533 /// CallExprUnaryConversions - a special case of an unary conversion
8534 /// performed on a function designator of a call expression.
8535 ExprResult CallExprUnaryConversions(Expr *E);
8537 // DefaultFunctionArrayConversion - converts functions and arrays
8538 // to their respective pointers (C99 6.3.2.1).
8539 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8541 // DefaultFunctionArrayLvalueConversion - converts functions and
8542 // arrays to their respective pointers and performs the
8543 // lvalue-to-rvalue conversion.
8544 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8545 bool Diagnose = true);
8547 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8548 // the operand. This is DefaultFunctionArrayLvalueConversion,
8549 // except that it assumes the operand isn't of function or array
8551 ExprResult DefaultLvalueConversion(Expr *E);
8553 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8554 // do not have a prototype. Integer promotions are performed on each
8555 // argument, and arguments that have type float are promoted to double.
8556 ExprResult DefaultArgumentPromotion(Expr *E);
8558 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8559 enum VariadicCallType {
8563 VariadicConstructor,
8564 VariadicDoesNotApply
8567 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8568 const FunctionProtoType *Proto,
8571 // Used for determining in which context a type is allowed to be passed to a
8581 // Determines which VarArgKind fits an expression.
8582 VarArgKind isValidVarArgType(const QualType &Ty);
8584 /// Check to see if the given expression is a valid argument to a variadic
8585 /// function, issuing a diagnostic if not.
8586 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8588 /// Check to see if a given expression could have '.c_str()' called on it.
8589 bool hasCStrMethod(const Expr *E);
8591 /// GatherArgumentsForCall - Collector argument expressions for various
8592 /// form of call prototypes.
8593 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8594 const FunctionProtoType *Proto,
8595 unsigned FirstParam, ArrayRef<Expr *> Args,
8596 SmallVectorImpl<Expr *> &AllArgs,
8597 VariadicCallType CallType = VariadicDoesNotApply,
8598 bool AllowExplicit = false,
8599 bool IsListInitialization = false);
8601 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8602 // will create a runtime trap if the resulting type is not a POD type.
8603 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8604 FunctionDecl *FDecl);
8606 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8607 // operands and then handles various conversions that are common to binary
8608 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8609 // routine returns the first non-arithmetic type found. The client is
8610 // responsible for emitting appropriate error diagnostics.
8611 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8612 bool IsCompAssign = false);
8614 /// AssignConvertType - All of the 'assignment' semantic checks return this
8615 /// enum to indicate whether the assignment was allowed. These checks are
8616 /// done for simple assignments, as well as initialization, return from
8617 /// function, argument passing, etc. The query is phrased in terms of a
8618 /// source and destination type.
8619 enum AssignConvertType {
8620 /// Compatible - the types are compatible according to the standard.
8623 /// PointerToInt - The assignment converts a pointer to an int, which we
8624 /// accept as an extension.
8627 /// IntToPointer - The assignment converts an int to a pointer, which we
8628 /// accept as an extension.
8631 /// FunctionVoidPointer - The assignment is between a function pointer and
8632 /// void*, which the standard doesn't allow, but we accept as an extension.
8633 FunctionVoidPointer,
8635 /// IncompatiblePointer - The assignment is between two pointers types that
8636 /// are not compatible, but we accept them as an extension.
8637 IncompatiblePointer,
8639 /// IncompatiblePointer - The assignment is between two pointers types which
8640 /// point to integers which have a different sign, but are otherwise
8641 /// identical. This is a subset of the above, but broken out because it's by
8642 /// far the most common case of incompatible pointers.
8643 IncompatiblePointerSign,
8645 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8646 /// c/v/r qualifiers, which we accept as an extension.
8647 CompatiblePointerDiscardsQualifiers,
8649 /// IncompatiblePointerDiscardsQualifiers - The assignment
8650 /// discards qualifiers that we don't permit to be discarded,
8651 /// like address spaces.
8652 IncompatiblePointerDiscardsQualifiers,
8654 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8655 /// nested pointer types, and the qualifiers other than the first two
8656 /// levels differ e.g. char ** -> const char **, but we accept them as an
8658 IncompatibleNestedPointerQualifiers,
8660 /// IncompatibleVectors - The assignment is between two vector types that
8661 /// have the same size, which we accept as an extension.
8662 IncompatibleVectors,
8664 /// IntToBlockPointer - The assignment converts an int to a block
8665 /// pointer. We disallow this.
8668 /// IncompatibleBlockPointer - The assignment is between two block
8669 /// pointers types that are not compatible.
8670 IncompatibleBlockPointer,
8672 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8673 /// id type and something else (that is incompatible with it). For example,
8674 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8675 IncompatibleObjCQualifiedId,
8677 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8678 /// object with __weak qualifier.
8679 IncompatibleObjCWeakRef,
8681 /// Incompatible - We reject this conversion outright, it is invalid to
8682 /// represent it in the AST.
8686 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8687 /// assignment conversion type specified by ConvTy. This returns true if the
8688 /// conversion was invalid or false if the conversion was accepted.
8689 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8691 QualType DstType, QualType SrcType,
8692 Expr *SrcExpr, AssignmentAction Action,
8693 bool *Complained = nullptr);
8695 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8696 /// enum. If AllowMask is true, then we also allow the complement of a valid
8697 /// value, to be used as a mask.
8698 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8699 bool AllowMask) const;
8701 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8702 /// integer not in the range of enum values.
8703 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8706 /// CheckAssignmentConstraints - Perform type checking for assignment,
8707 /// argument passing, variable initialization, and function return values.
8709 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8713 /// Check assignment constraints and optionally prepare for a conversion of
8714 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8716 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8719 bool ConvertRHS = true);
8721 // CheckSingleAssignmentConstraints - Currently used by
8722 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8723 // this routine performs the default function/array converions, if ConvertRHS
8725 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8727 bool Diagnose = true,
8728 bool DiagnoseCFAudited = false,
8729 bool ConvertRHS = true);
8731 // \brief If the lhs type is a transparent union, check whether we
8732 // can initialize the transparent union with the given expression.
8733 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8736 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8738 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8740 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8741 AssignmentAction Action,
8742 bool AllowExplicit = false);
8743 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8744 AssignmentAction Action,
8746 ImplicitConversionSequence& ICS);
8747 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8748 const ImplicitConversionSequence& ICS,
8749 AssignmentAction Action,
8750 CheckedConversionKind CCK
8751 = CCK_ImplicitConversion);
8752 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8753 const StandardConversionSequence& SCS,
8754 AssignmentAction Action,
8755 CheckedConversionKind CCK);
8757 /// the following "Check" methods will return a valid/converted QualType
8758 /// or a null QualType (indicating an error diagnostic was issued).
8760 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8761 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8763 QualType CheckPointerToMemberOperands( // C++ 5.5
8764 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8765 SourceLocation OpLoc, bool isIndirect);
8766 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8767 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8769 QualType CheckRemainderOperands( // C99 6.5.5
8770 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8771 bool IsCompAssign = false);
8772 QualType CheckAdditionOperands( // C99 6.5.6
8773 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8774 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
8775 QualType CheckSubtractionOperands( // C99 6.5.6
8776 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8777 QualType* CompLHSTy = nullptr);
8778 QualType CheckShiftOperands( // C99 6.5.7
8779 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8780 BinaryOperatorKind Opc, bool IsCompAssign = false);
8781 QualType CheckCompareOperands( // C99 6.5.8/9
8782 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8783 BinaryOperatorKind Opc, bool isRelational);
8784 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8785 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8786 bool IsCompAssign = false);
8787 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8788 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8789 BinaryOperatorKind Opc);
8790 // CheckAssignmentOperands is used for both simple and compound assignment.
8791 // For simple assignment, pass both expressions and a null converted type.
8792 // For compound assignment, pass both expressions and the converted type.
8793 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8794 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8796 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8797 UnaryOperatorKind Opcode, Expr *Op);
8798 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8799 BinaryOperatorKind Opcode,
8800 Expr *LHS, Expr *RHS);
8801 ExprResult checkPseudoObjectRValue(Expr *E);
8802 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8804 QualType CheckConditionalOperands( // C99 6.5.15
8805 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8806 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8807 QualType CXXCheckConditionalOperands( // C++ 5.16
8808 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8809 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8810 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8811 bool *NonStandardCompositeType = nullptr);
8812 QualType FindCompositePointerType(SourceLocation Loc,
8813 ExprResult &E1, ExprResult &E2,
8814 bool *NonStandardCompositeType = nullptr) {
8815 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8816 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8817 NonStandardCompositeType);
8823 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8824 SourceLocation QuestionLoc);
8826 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8827 SourceLocation QuestionLoc);
8829 void DiagnoseAlwaysNonNullPointer(Expr *E,
8830 Expr::NullPointerConstantKind NullType,
8831 bool IsEqual, SourceRange Range);
8833 /// type checking for vector binary operators.
8834 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8835 SourceLocation Loc, bool IsCompAssign,
8836 bool AllowBothBool, bool AllowBoolConversion);
8837 QualType GetSignedVectorType(QualType V);
8838 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8839 SourceLocation Loc, bool isRelational);
8840 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8841 SourceLocation Loc);
8843 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8844 bool isLaxVectorConversion(QualType srcType, QualType destType);
8846 /// type checking declaration initializers (C99 6.7.8)
8847 bool CheckForConstantInitializer(Expr *e, QualType t);
8849 // type checking C++ declaration initializers (C++ [dcl.init]).
8851 /// ReferenceCompareResult - Expresses the result of comparing two
8852 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8853 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8854 enum ReferenceCompareResult {
8855 /// Ref_Incompatible - The two types are incompatible, so direct
8856 /// reference binding is not possible.
8857 Ref_Incompatible = 0,
8858 /// Ref_Related - The two types are reference-related, which means
8859 /// that their unqualified forms (T1 and T2) are either the same
8860 /// or T1 is a base class of T2.
8862 /// Ref_Compatible_With_Added_Qualification - The two types are
8863 /// reference-compatible with added qualification, meaning that
8864 /// they are reference-compatible and the qualifiers on T1 (cv1)
8865 /// are greater than the qualifiers on T2 (cv2).
8866 Ref_Compatible_With_Added_Qualification,
8867 /// Ref_Compatible - The two types are reference-compatible and
8868 /// have equivalent qualifiers (cv1 == cv2).
8872 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8873 QualType T1, QualType T2,
8874 bool &DerivedToBase,
8875 bool &ObjCConversion,
8876 bool &ObjCLifetimeConversion);
8878 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8879 Expr *CastExpr, CastKind &CastKind,
8880 ExprValueKind &VK, CXXCastPath &Path);
8882 /// \brief Force an expression with unknown-type to an expression of the
8884 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8886 /// \brief Type-check an expression that's being passed to an
8887 /// __unknown_anytype parameter.
8888 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8889 Expr *result, QualType ¶mType);
8891 // CheckVectorCast - check type constraints for vectors.
8892 // Since vectors are an extension, there are no C standard reference for this.
8893 // We allow casting between vectors and integer datatypes of the same size.
8894 // returns true if the cast is invalid
8895 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8898 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
8899 /// implicit casts if necessary.
8900 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8902 // CheckExtVectorCast - check type constraints for extended vectors.
8903 // Since vectors are an extension, there are no C standard reference for this.
8904 // We allow casting between vectors and integer datatypes of the same size,
8905 // or vectors and the element type of that vector.
8906 // returns the cast expr
8907 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8910 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8911 SourceLocation LParenLoc,
8913 SourceLocation RParenLoc);
8915 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
8917 /// \brief Checks for invalid conversions and casts between
8918 /// retainable pointers and other pointer kinds.
8919 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8920 QualType castType, Expr *&op,
8921 CheckedConversionKind CCK,
8922 bool Diagnose = true,
8923 bool DiagnoseCFAudited = false,
8924 BinaryOperatorKind Opc = BO_PtrMemD
8927 Expr *stripARCUnbridgedCast(Expr *e);
8928 void diagnoseARCUnbridgedCast(Expr *e);
8930 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8933 /// checkRetainCycles - Check whether an Objective-C message send
8934 /// might create an obvious retain cycle.
8935 void checkRetainCycles(ObjCMessageExpr *msg);
8936 void checkRetainCycles(Expr *receiver, Expr *argument);
8937 void checkRetainCycles(VarDecl *Var, Expr *Init);
8939 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8940 /// to weak/__unsafe_unretained type.
8941 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8943 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8944 /// to weak/__unsafe_unretained expression.
8945 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8947 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8948 /// \param Method - May be null.
8949 /// \param [out] ReturnType - The return type of the send.
8950 /// \return true iff there were any incompatible types.
8951 bool CheckMessageArgumentTypes(QualType ReceiverType,
8952 MultiExprArg Args, Selector Sel,
8953 ArrayRef<SourceLocation> SelectorLocs,
8954 ObjCMethodDecl *Method, bool isClassMessage,
8955 bool isSuperMessage,
8956 SourceLocation lbrac, SourceLocation rbrac,
8957 SourceRange RecRange,
8958 QualType &ReturnType, ExprValueKind &VK);
8960 /// \brief Determine the result of a message send expression based on
8961 /// the type of the receiver, the method expected to receive the message,
8962 /// and the form of the message send.
8963 QualType getMessageSendResultType(QualType ReceiverType,
8964 ObjCMethodDecl *Method,
8965 bool isClassMessage, bool isSuperMessage);
8967 /// \brief If the given expression involves a message send to a method
8968 /// with a related result type, emit a note describing what happened.
8969 void EmitRelatedResultTypeNote(const Expr *E);
8971 /// \brief Given that we had incompatible pointer types in a return
8972 /// statement, check whether we're in a method with a related result
8973 /// type, and if so, emit a note describing what happened.
8974 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8976 class ConditionResult {
8978 FullExprArg Condition;
8984 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
8986 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
8987 HasKnownValue(IsConstexpr && Condition.get() &&
8988 !Condition.get()->isValueDependent()),
8989 KnownValue(HasKnownValue &&
8990 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
8991 explicit ConditionResult(bool Invalid)
8992 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
8993 HasKnownValue(false), KnownValue(false) {}
8996 ConditionResult() : ConditionResult(false) {}
8997 bool isInvalid() const { return Invalid; }
8998 std::pair<VarDecl *, Expr *> get() const {
8999 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9002 llvm::Optional<bool> getKnownValue() const {
9008 static ConditionResult ConditionError() { return ConditionResult(true); }
9010 enum class ConditionKind {
9011 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9012 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9013 Switch ///< An integral condition for a 'switch' statement.
9016 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9017 Expr *SubExpr, ConditionKind CK);
9019 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9020 SourceLocation StmtLoc,
9023 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9025 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9026 SourceLocation StmtLoc,
9028 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9030 /// CheckBooleanCondition - Diagnose problems involving the use of
9031 /// the given expression as a boolean condition (e.g. in an if
9032 /// statement). Also performs the standard function and array
9033 /// decays, possibly changing the input variable.
9035 /// \param Loc - A location associated with the condition, e.g. the
9037 /// \return true iff there were any errors
9038 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9039 bool IsConstexpr = false);
9041 /// DiagnoseAssignmentAsCondition - Given that an expression is
9042 /// being used as a boolean condition, warn if it's an assignment.
9043 void DiagnoseAssignmentAsCondition(Expr *E);
9045 /// \brief Redundant parentheses over an equality comparison can indicate
9046 /// that the user intended an assignment used as condition.
9047 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9049 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9050 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9052 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9053 /// the specified width and sign. If an overflow occurs, detect it and emit
9054 /// the specified diagnostic.
9055 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9056 unsigned NewWidth, bool NewSign,
9057 SourceLocation Loc, unsigned DiagID);
9059 /// Checks that the Objective-C declaration is declared in the global scope.
9060 /// Emits an error and marks the declaration as invalid if it's not declared
9061 /// in the global scope.
9062 bool CheckObjCDeclScope(Decl *D);
9064 /// \brief Abstract base class used for diagnosing integer constant
9065 /// expression violations.
9066 class VerifyICEDiagnoser {
9070 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9072 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9073 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9074 virtual ~VerifyICEDiagnoser() { }
9077 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9078 /// and reports the appropriate diagnostics. Returns false on success.
9079 /// Can optionally return the value of the expression.
9080 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9081 VerifyICEDiagnoser &Diagnoser,
9082 bool AllowFold = true);
9083 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9085 bool AllowFold = true);
9086 ExprResult VerifyIntegerConstantExpression(Expr *E,
9087 llvm::APSInt *Result = nullptr);
9089 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9090 /// the correct width, and that the field type is valid.
9091 /// Returns false on success.
9092 /// Can optionally return whether the bit-field is of width 0
9093 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9094 QualType FieldTy, bool IsMsStruct,
9095 Expr *BitWidth, bool *ZeroWidth = nullptr);
9097 enum CUDAFunctionTarget {
9105 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
9107 // CUDA function call preference. Must be ordered numerically from
9109 enum CUDAFunctionPreference {
9110 CFP_Never, // Invalid caller/callee combination.
9111 CFP_WrongSide, // Calls from host-device to host or device
9112 // function that do not match current compilation
9113 // mode. Only in effect if
9114 // LangOpts.CUDADisableTargetCallChecks is true.
9115 CFP_HostDevice, // Any calls to host/device functions.
9116 CFP_SameSide, // Calls from host-device to host or device
9117 // function matching current compilation mode.
9118 CFP_Native, // host-to-host or device-to-device calls.
9121 /// Identifies relative preference of a given Caller/Callee
9122 /// combination, based on their host/device attributes.
9123 /// \param Caller function which needs address of \p Callee.
9124 /// nullptr in case of global context.
9125 /// \param Callee target function
9127 /// \returns preference value for particular Caller/Callee combination.
9128 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9129 const FunctionDecl *Callee);
9131 /// Determines whether Caller may invoke Callee, based on their CUDA
9132 /// host/device attributes. Returns true if the call is not allowed.
9133 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
9134 return IdentifyCUDAPreference(Caller, Callee) == CFP_Never;
9137 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9138 /// depending on FD and the current compilation settings.
9139 void maybeAddCUDAHostDeviceAttrs(Scope *S, FunctionDecl *FD,
9140 const LookupResult &Previous);
9142 /// Finds a function in \p Matches with highest calling priority
9143 /// from \p Caller context and erases all functions with lower
9144 /// calling priority.
9145 void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9146 SmallVectorImpl<FunctionDecl *> &Matches);
9147 void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9148 SmallVectorImpl<DeclAccessPair> &Matches);
9149 void EraseUnwantedCUDAMatches(
9150 const FunctionDecl *Caller,
9151 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9153 /// Given a implicit special member, infer its CUDA target from the
9154 /// calls it needs to make to underlying base/field special members.
9155 /// \param ClassDecl the class for which the member is being created.
9156 /// \param CSM the kind of special member.
9157 /// \param MemberDecl the special member itself.
9158 /// \param ConstRHS true if this is a copy operation with a const object on
9160 /// \param Diagnose true if this call should emit diagnostics.
9161 /// \return true if there was an error inferring.
9162 /// The result of this call is implicit CUDA target attribute(s) attached to
9163 /// the member declaration.
9164 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9165 CXXSpecialMember CSM,
9166 CXXMethodDecl *MemberDecl,
9170 /// \return true if \p CD can be considered empty according to CUDA
9171 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9172 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9173 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9175 /// \name Code completion
9177 /// \brief Describes the context in which code completion occurs.
9178 enum ParserCompletionContext {
9179 /// \brief Code completion occurs at top-level or namespace context.
9181 /// \brief Code completion occurs within a class, struct, or union.
9183 /// \brief Code completion occurs within an Objective-C interface, protocol,
9186 /// \brief Code completion occurs within an Objective-C implementation or
9187 /// category implementation
9188 PCC_ObjCImplementation,
9189 /// \brief Code completion occurs within the list of instance variables
9190 /// in an Objective-C interface, protocol, category, or implementation.
9191 PCC_ObjCInstanceVariableList,
9192 /// \brief Code completion occurs following one or more template
9195 /// \brief Code completion occurs following one or more template
9196 /// headers within a class.
9198 /// \brief Code completion occurs within an expression.
9200 /// \brief Code completion occurs within a statement, which may
9201 /// also be an expression or a declaration.
9203 /// \brief Code completion occurs at the beginning of the
9204 /// initialization statement (or expression) in a for loop.
9206 /// \brief Code completion occurs within the condition of an if,
9207 /// while, switch, or for statement.
9209 /// \brief Code completion occurs within the body of a function on a
9210 /// recovery path, where we do not have a specific handle on our position
9212 PCC_RecoveryInFunction,
9213 /// \brief Code completion occurs where only a type is permitted.
9215 /// \brief Code completion occurs in a parenthesized expression, which
9216 /// might also be a type cast.
9217 PCC_ParenthesizedExpression,
9218 /// \brief Code completion occurs within a sequence of declaration
9219 /// specifiers within a function, method, or block.
9220 PCC_LocalDeclarationSpecifiers
9223 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9224 void CodeCompleteOrdinaryName(Scope *S,
9225 ParserCompletionContext CompletionContext);
9226 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9227 bool AllowNonIdentifiers,
9228 bool AllowNestedNameSpecifiers);
9230 struct CodeCompleteExpressionData;
9231 void CodeCompleteExpression(Scope *S,
9232 const CodeCompleteExpressionData &Data);
9233 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9234 SourceLocation OpLoc,
9236 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9237 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9238 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9239 void CodeCompleteBracketDeclarator(Scope *S);
9240 void CodeCompleteCase(Scope *S);
9241 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9242 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9243 ArrayRef<Expr *> Args);
9244 void CodeCompleteInitializer(Scope *S, Decl *D);
9245 void CodeCompleteReturn(Scope *S);
9246 void CodeCompleteAfterIf(Scope *S);
9247 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9249 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9250 bool EnteringContext);
9251 void CodeCompleteUsing(Scope *S);
9252 void CodeCompleteUsingDirective(Scope *S);
9253 void CodeCompleteNamespaceDecl(Scope *S);
9254 void CodeCompleteNamespaceAliasDecl(Scope *S);
9255 void CodeCompleteOperatorName(Scope *S);
9256 void CodeCompleteConstructorInitializer(
9258 ArrayRef<CXXCtorInitializer *> Initializers);
9260 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9261 bool AfterAmpersand);
9263 void CodeCompleteObjCAtDirective(Scope *S);
9264 void CodeCompleteObjCAtVisibility(Scope *S);
9265 void CodeCompleteObjCAtStatement(Scope *S);
9266 void CodeCompleteObjCAtExpression(Scope *S);
9267 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9268 void CodeCompleteObjCPropertyGetter(Scope *S);
9269 void CodeCompleteObjCPropertySetter(Scope *S);
9270 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9272 void CodeCompleteObjCMessageReceiver(Scope *S);
9273 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9274 ArrayRef<IdentifierInfo *> SelIdents,
9275 bool AtArgumentExpression);
9276 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9277 ArrayRef<IdentifierInfo *> SelIdents,
9278 bool AtArgumentExpression,
9279 bool IsSuper = false);
9280 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9281 ArrayRef<IdentifierInfo *> SelIdents,
9282 bool AtArgumentExpression,
9283 ObjCInterfaceDecl *Super = nullptr);
9284 void CodeCompleteObjCForCollection(Scope *S,
9285 DeclGroupPtrTy IterationVar);
9286 void CodeCompleteObjCSelector(Scope *S,
9287 ArrayRef<IdentifierInfo *> SelIdents);
9288 void CodeCompleteObjCProtocolReferences(
9289 ArrayRef<IdentifierLocPair> Protocols);
9290 void CodeCompleteObjCProtocolDecl(Scope *S);
9291 void CodeCompleteObjCInterfaceDecl(Scope *S);
9292 void CodeCompleteObjCSuperclass(Scope *S,
9293 IdentifierInfo *ClassName,
9294 SourceLocation ClassNameLoc);
9295 void CodeCompleteObjCImplementationDecl(Scope *S);
9296 void CodeCompleteObjCInterfaceCategory(Scope *S,
9297 IdentifierInfo *ClassName,
9298 SourceLocation ClassNameLoc);
9299 void CodeCompleteObjCImplementationCategory(Scope *S,
9300 IdentifierInfo *ClassName,
9301 SourceLocation ClassNameLoc);
9302 void CodeCompleteObjCPropertyDefinition(Scope *S);
9303 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9304 IdentifierInfo *PropertyName);
9305 void CodeCompleteObjCMethodDecl(Scope *S,
9306 bool IsInstanceMethod,
9307 ParsedType ReturnType);
9308 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9309 bool IsInstanceMethod,
9310 bool AtParameterName,
9311 ParsedType ReturnType,
9312 ArrayRef<IdentifierInfo *> SelIdents);
9313 void CodeCompletePreprocessorDirective(bool InConditional);
9314 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9315 void CodeCompletePreprocessorMacroName(bool IsDefinition);
9316 void CodeCompletePreprocessorExpression();
9317 void CodeCompletePreprocessorMacroArgument(Scope *S,
9318 IdentifierInfo *Macro,
9319 MacroInfo *MacroInfo,
9321 void CodeCompleteNaturalLanguage();
9322 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9323 CodeCompletionTUInfo &CCTUInfo,
9324 SmallVectorImpl<CodeCompletionResult> &Results);
9327 //===--------------------------------------------------------------------===//
9328 // Extra semantic analysis beyond the C type system
9331 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9332 unsigned ByteNo) const;
9335 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9336 const ArraySubscriptExpr *ASE=nullptr,
9337 bool AllowOnePastEnd=true, bool IndexNegated=false);
9338 void CheckArrayAccess(const Expr *E);
9339 // Used to grab the relevant information from a FormatAttr and a
9340 // FunctionDeclaration.
9341 struct FormatStringInfo {
9343 unsigned FirstDataArg;
9347 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9348 FormatStringInfo *FSI);
9349 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9350 const FunctionProtoType *Proto);
9351 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9352 ArrayRef<const Expr *> Args);
9353 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9354 const FunctionProtoType *Proto);
9355 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9356 void CheckConstructorCall(FunctionDecl *FDecl,
9357 ArrayRef<const Expr *> Args,
9358 const FunctionProtoType *Proto,
9359 SourceLocation Loc);
9361 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
9362 ArrayRef<const Expr *> Args, bool IsMemberFunction,
9363 SourceLocation Loc, SourceRange Range,
9364 VariadicCallType CallType);
9366 bool CheckObjCString(Expr *Arg);
9368 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
9369 unsigned BuiltinID, CallExpr *TheCall);
9371 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
9373 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9374 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9376 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9377 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9378 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9379 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9380 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9382 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
9383 bool SemaBuiltinVAStart(CallExpr *TheCall);
9384 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
9385 bool SemaBuiltinVAStartARM(CallExpr *Call);
9386 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
9387 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
9390 // Used by C++ template instantiation.
9391 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
9392 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
9393 SourceLocation BuiltinLoc,
9394 SourceLocation RParenLoc);
9397 bool SemaBuiltinPrefetch(CallExpr *TheCall);
9398 bool SemaBuiltinAssume(CallExpr *TheCall);
9399 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
9400 bool SemaBuiltinLongjmp(CallExpr *TheCall);
9401 bool SemaBuiltinSetjmp(CallExpr *TheCall);
9402 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
9403 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
9404 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
9405 AtomicExpr::AtomicOp Op);
9406 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
9407 llvm::APSInt &Result);
9408 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
9410 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
9411 int ArgNum, unsigned ExpectedFieldNum,
9414 enum FormatStringType {
9425 static FormatStringType GetFormatStringType(const FormatAttr *Format);
9427 bool FormatStringHasSArg(const StringLiteral *FExpr);
9429 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
9432 bool CheckFormatArguments(const FormatAttr *Format,
9433 ArrayRef<const Expr *> Args,
9435 VariadicCallType CallType,
9436 SourceLocation Loc, SourceRange Range,
9437 llvm::SmallBitVector &CheckedVarArgs);
9438 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
9439 bool HasVAListArg, unsigned format_idx,
9440 unsigned firstDataArg, FormatStringType Type,
9441 VariadicCallType CallType,
9442 SourceLocation Loc, SourceRange range,
9443 llvm::SmallBitVector &CheckedVarArgs);
9445 void CheckAbsoluteValueFunction(const CallExpr *Call,
9446 const FunctionDecl *FDecl,
9447 IdentifierInfo *FnInfo);
9449 void CheckMemaccessArguments(const CallExpr *Call,
9451 IdentifierInfo *FnName);
9453 void CheckStrlcpycatArguments(const CallExpr *Call,
9454 IdentifierInfo *FnName);
9456 void CheckStrncatArguments(const CallExpr *Call,
9457 IdentifierInfo *FnName);
9459 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9460 SourceLocation ReturnLoc,
9461 bool isObjCMethod = false,
9462 const AttrVec *Attrs = nullptr,
9463 const FunctionDecl *FD = nullptr);
9465 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
9466 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
9467 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
9468 void CheckForIntOverflow(Expr *E);
9469 void CheckUnsequencedOperations(Expr *E);
9471 /// \brief Perform semantic checks on a completed expression. This will either
9472 /// be a full-expression or a default argument expression.
9473 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
9474 bool IsConstexpr = false);
9476 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
9479 /// \brief Check if the given expression contains 'break' or 'continue'
9480 /// statement that produces control flow different from GCC.
9481 void CheckBreakContinueBinding(Expr *E);
9483 /// \brief Check whether receiver is mutable ObjC container which
9484 /// attempts to add itself into the container
9485 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
9487 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9488 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9489 bool DeleteWasArrayForm);
9491 /// \brief Register a magic integral constant to be used as a type tag.
9492 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9493 uint64_t MagicValue, QualType Type,
9494 bool LayoutCompatible, bool MustBeNull);
9496 struct TypeTagData {
9499 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
9500 Type(Type), LayoutCompatible(LayoutCompatible),
9501 MustBeNull(MustBeNull)
9506 /// If true, \c Type should be compared with other expression's types for
9507 /// layout-compatibility.
9508 unsigned LayoutCompatible : 1;
9509 unsigned MustBeNull : 1;
9512 /// A pair of ArgumentKind identifier and magic value. This uniquely
9513 /// identifies the magic value.
9514 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
9517 /// \brief A map from magic value to type information.
9518 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
9519 TypeTagForDatatypeMagicValues;
9521 /// \brief Peform checks on a call of a function with argument_with_type_tag
9522 /// or pointer_with_type_tag attributes.
9523 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9524 const Expr * const *ExprArgs);
9526 /// \brief The parser's current scope.
9528 /// The parser maintains this state here.
9531 mutable IdentifierInfo *Ident_super;
9532 mutable IdentifierInfo *Ident___float128;
9534 /// Nullability type specifiers.
9535 IdentifierInfo *Ident__Nonnull = nullptr;
9536 IdentifierInfo *Ident__Nullable = nullptr;
9537 IdentifierInfo *Ident__Null_unspecified = nullptr;
9539 IdentifierInfo *Ident_NSError = nullptr;
9542 friend class Parser;
9543 friend class InitializationSequence;
9544 friend class ASTReader;
9545 friend class ASTDeclReader;
9546 friend class ASTWriter;
9549 /// Retrieve the keyword associated
9550 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
9552 /// The struct behind the CFErrorRef pointer.
9553 RecordDecl *CFError = nullptr;
9555 /// Retrieve the identifier "NSError".
9556 IdentifierInfo *getNSErrorIdent();
9558 /// \brief Retrieve the parser's current scope.
9560 /// This routine must only be used when it is certain that semantic analysis
9561 /// and the parser are in precisely the same context, which is not the case
9562 /// when, e.g., we are performing any kind of template instantiation.
9563 /// Therefore, the only safe places to use this scope are in the parser
9564 /// itself and in routines directly invoked from the parser and *never* from
9565 /// template substitution or instantiation.
9566 Scope *getCurScope() const { return CurScope; }
9568 void incrementMSManglingNumber() const {
9569 return CurScope->incrementMSManglingNumber();
9572 IdentifierInfo *getSuperIdentifier() const;
9573 IdentifierInfo *getFloat128Identifier() const;
9575 Decl *getObjCDeclContext() const;
9577 DeclContext *getCurLexicalContext() const {
9578 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
9581 AvailabilityResult getCurContextAvailability() const;
9583 const DeclContext *getCurObjCLexicalContext() const {
9584 const DeclContext *DC = getCurLexicalContext();
9585 // A category implicitly has the attribute of the interface.
9586 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
9587 DC = CatD->getClassInterface();
9591 /// \brief To be used for checking whether the arguments being passed to
9592 /// function exceeds the number of parameters expected for it.
9593 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
9594 bool PartialOverloading = false) {
9595 // We check whether we're just after a comma in code-completion.
9596 if (NumArgs > 0 && PartialOverloading)
9597 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
9598 return NumArgs > NumParams;
9601 // Emitting members of dllexported classes is delayed until the class
9602 // (including field initializers) is fully parsed.
9603 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
9606 /// \brief RAII object that enters a new expression evaluation context.
9607 class EnterExpressionEvaluationContext {
9609 bool Entered = true;
9612 EnterExpressionEvaluationContext(Sema &Actions,
9613 Sema::ExpressionEvaluationContext NewContext,
9614 Decl *LambdaContextDecl = nullptr,
9615 bool IsDecltype = false,
9616 bool ShouldEnter = true)
9617 : Actions(Actions), Entered(ShouldEnter) {
9619 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
9622 EnterExpressionEvaluationContext(Sema &Actions,
9623 Sema::ExpressionEvaluationContext NewContext,
9624 Sema::ReuseLambdaContextDecl_t,
9625 bool IsDecltype = false)
9626 : Actions(Actions) {
9627 Actions.PushExpressionEvaluationContext(NewContext,
9628 Sema::ReuseLambdaContextDecl,
9632 ~EnterExpressionEvaluationContext() {
9634 Actions.PopExpressionEvaluationContext();
9638 DeductionFailureInfo
9639 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
9640 sema::TemplateDeductionInfo &Info);
9642 /// \brief Contains a late templated function.
9643 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
9644 struct LateParsedTemplate {
9646 /// \brief The template function declaration to be late parsed.
9650 } // end namespace clang