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