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/StmtCXX.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/AST/TypeOrdering.h"
32 #include "clang/Basic/ExpressionTraits.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/OpenMPKinds.h"
36 #include "clang/Basic/PragmaKinds.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TemplateKinds.h"
39 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/ExternalSemaSource.h"
44 #include "clang/Sema/IdentifierResolver.h"
45 #include "clang/Sema/ObjCMethodList.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
48 #include "clang/Sema/ScopeInfo.h"
49 #include "clang/Sema/TypoCorrection.h"
50 #include "clang/Sema/Weak.h"
51 #include "llvm/ADT/ArrayRef.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class InlineAsmIdentifierInfo;
74 class ASTMutationListener;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
107 class DeclAccessPair;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
116 class EnumConstantDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
134 class LocalInstantiationScope;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class MultiLevelTemplateArgumentList;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
167 class StandardConversionSequence;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
175 class TemplateParameterList;
176 class TemplatePartialOrderingContext;
177 class TemplateTemplateParmDecl;
181 class TypedefNameDecl;
183 class TypoCorrectionConsumer;
185 class UnresolvedLookupExpr;
186 class UnresolvedMemberExpr;
187 class UnresolvedSetImpl;
188 class UnresolvedSetIterator;
190 class UsingShadowDecl;
193 class VarTemplateSpecializationDecl;
194 class VisibilityAttr;
195 class VisibleDeclConsumer;
196 class IndirectFieldDecl;
197 struct DeductionFailureInfo;
198 class TemplateSpecCandidateSet;
201 class AccessedEntity;
202 class BlockScopeInfo;
203 class CapturedRegionScopeInfo;
204 class CapturingScopeInfo;
205 class CompoundScopeInfo;
206 class DelayedDiagnostic;
207 class DelayedDiagnosticPool;
208 class FunctionScopeInfo;
209 class LambdaScopeInfo;
210 class PossiblyUnreachableDiag;
211 class TemplateDeductionInfo;
214 namespace threadSafety {
216 void threadSafetyCleanup(BeforeSet* Cache);
219 // FIXME: No way to easily map from TemplateTypeParmTypes to
220 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
221 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222 SourceLocation> UnexpandedParameterPack;
224 /// Describes whether we've seen any nullability information for the given
226 struct FileNullability {
227 /// The first pointer declarator (of any pointer kind) in the file that does
228 /// not have a corresponding nullability annotation.
229 SourceLocation PointerLoc;
231 /// Which kind of pointer declarator we saw.
234 /// Whether we saw any type nullability annotations in the given file.
235 bool SawTypeNullability = false;
238 /// A mapping from file IDs to a record of whether we've seen nullability
239 /// information in that file.
240 class FileNullabilityMap {
241 /// A mapping from file IDs to the nullability information for each file ID.
242 llvm::DenseMap<FileID, FileNullability> Map;
244 /// A single-element cache based on the file ID.
247 FileNullability Nullability;
251 FileNullability &operator[](FileID file) {
252 // Check the single-element cache.
253 if (file == Cache.File)
254 return Cache.Nullability;
256 // It's not in the single-element cache; flush the cache if we have one.
257 if (!Cache.File.isInvalid()) {
258 Map[Cache.File] = Cache.Nullability;
261 // Pull this entry into the cache.
263 Cache.Nullability = Map[file];
264 return Cache.Nullability;
268 /// Sema - This implements semantic analysis and AST building for C.
270 Sema(const Sema &) = delete;
271 void operator=(const Sema &) = delete;
273 ///\brief Source of additional semantic information.
274 ExternalSemaSource *ExternalSource;
276 ///\brief Whether Sema has generated a multiplexer and has to delete it.
277 bool isMultiplexExternalSource;
279 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
281 bool isVisibleSlow(const NamedDecl *D);
283 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
284 const NamedDecl *New) {
285 // We are about to link these. It is now safe to compute the linkage of
286 // the new decl. If the new decl has external linkage, we will
287 // link it with the hidden decl (which also has external linkage) and
288 // it will keep having external linkage. If it has internal linkage, we
289 // will not link it. Since it has no previous decls, it will remain
290 // with internal linkage.
291 return isVisible(Old) || New->isExternallyVisible();
293 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
296 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297 typedef OpaquePtr<TemplateName> TemplateTy;
298 typedef OpaquePtr<QualType> TypeTy;
300 OpenCLOptions OpenCLFeatures;
301 FPOptions FPFeatures;
303 const LangOptions &LangOpts;
306 ASTConsumer &Consumer;
307 DiagnosticsEngine &Diags;
308 SourceManager &SourceMgr;
310 /// \brief Flag indicating whether or not to collect detailed statistics.
313 /// \brief Code-completion consumer.
314 CodeCompleteConsumer *CodeCompleter;
316 /// CurContext - This is the current declaration context of parsing.
317 DeclContext *CurContext;
319 /// \brief Generally null except when we temporarily switch decl contexts,
320 /// like in \see ActOnObjCTemporaryExitContainerContext.
321 DeclContext *OriginalLexicalContext;
323 /// VAListTagName - The declaration name corresponding to __va_list_tag.
324 /// This is used as part of a hack to omit that class from ADL results.
325 DeclarationName VAListTagName;
327 bool MSStructPragmaOn; // True when \#pragma ms_struct on
329 /// \brief Controls member pointer representation format under the MS ABI.
330 LangOptions::PragmaMSPointersToMembersKind
331 MSPointerToMemberRepresentationMethod;
333 /// Stack of active SEH __finally scopes. Can be empty.
334 SmallVector<Scope*, 2> CurrentSEHFinally;
336 /// \brief Source location for newly created implicit MSInheritanceAttrs
337 SourceLocation ImplicitMSInheritanceAttrLoc;
339 enum PragmaMsStackAction {
340 PSK_Reset = 0x0, // #pragma ()
341 PSK_Set = 0x1, // #pragma (value)
342 PSK_Push = 0x2, // #pragma (push[, id])
343 PSK_Pop = 0x4, // #pragma (pop[, id])
344 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
345 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
346 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
349 template<typename ValueType>
352 llvm::StringRef StackSlotLabel;
354 SourceLocation PragmaLocation;
355 Slot(llvm::StringRef StackSlotLabel,
357 SourceLocation PragmaLocation)
358 : StackSlotLabel(StackSlotLabel), Value(Value),
359 PragmaLocation(PragmaLocation) {}
361 void Act(SourceLocation PragmaLocation,
362 PragmaMsStackAction Action,
363 llvm::StringRef StackSlotLabel,
366 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
367 // method body to restore the stacks on exit, so it works like this:
370 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
372 // #pragma <name>(pop, InternalPragmaSlot)
375 // It works even with #pragma vtordisp, although MSVC doesn't support
376 // #pragma vtordisp(push [, id], n)
379 // Push / pop a named sentinel slot.
380 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
381 assert((Action == PSK_Push || Action == PSK_Pop) &&
382 "Can only push / pop #pragma stack sentinels!");
383 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
387 explicit PragmaStack(const ValueType &Default)
388 : DefaultValue(Default), CurrentValue(Default) {}
390 SmallVector<Slot, 2> Stack;
391 ValueType DefaultValue; // Value used for PSK_Reset action.
392 ValueType CurrentValue;
393 SourceLocation CurrentPragmaLocation;
395 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
396 // we shouldn't do so if they're in a module).
398 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
399 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
401 /// 0: Suppress all vtordisps
402 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
404 /// 2: Always insert vtordisps to support RTTI on partially constructed
406 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
408 // Sentinel to represent when the stack is set to mac68k alignment.
409 static const unsigned kMac68kAlignmentSentinel = ~0U;
410 PragmaStack<unsigned> PackStack;
412 PragmaStack<StringLiteral *> DataSegStack;
413 PragmaStack<StringLiteral *> BSSSegStack;
414 PragmaStack<StringLiteral *> ConstSegStack;
415 PragmaStack<StringLiteral *> CodeSegStack;
417 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
418 // Actions should be performed only if we enter / exit a C++ method body.
419 class PragmaStackSentinelRAII {
421 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
422 ~PragmaStackSentinelRAII();
430 /// A mapping that describes the nullability we've seen in each header file.
431 FileNullabilityMap NullabilityMap;
433 /// Last section used with #pragma init_seg.
434 StringLiteral *CurInitSeg;
435 SourceLocation CurInitSegLoc;
437 /// VisContext - Manages the stack for \#pragma GCC visibility.
438 void *VisContext; // Really a "PragmaVisStack*"
440 /// \brief This represents the last location of a "#pragma clang optimize off"
441 /// directive if such a directive has not been closed by an "on" yet. If
442 /// optimizations are currently "on", this is set to an invalid location.
443 SourceLocation OptimizeOffPragmaLocation;
445 /// \brief Flag indicating if Sema is building a recovery call expression.
447 /// This flag is used to avoid building recovery call expressions
448 /// if Sema is already doing so, which would cause infinite recursions.
449 bool IsBuildingRecoveryCallExpr;
451 /// Used to control the generation of ExprWithCleanups.
454 /// ExprCleanupObjects - This is the stack of objects requiring
455 /// cleanup that are created by the current full expression. The
456 /// element type here is ExprWithCleanups::Object.
457 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
459 /// \brief Store a list of either DeclRefExprs or MemberExprs
460 /// that contain a reference to a variable (constant) that may or may not
461 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
462 /// and discarded value conversions have been applied to all subexpressions
463 /// of the enclosing full expression. This is cleared at the end of each
465 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
467 /// \brief Stack containing information about each of the nested
468 /// function, block, and method scopes that are currently active.
470 /// This array is never empty. Clients should ignore the first
471 /// element, which is used to cache a single FunctionScopeInfo
472 /// that's used to parse every top-level function.
473 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
475 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
476 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
479 /// ExtVectorDecls - This is a list all the extended vector types. This allows
480 /// us to associate a raw vector type with one of the ext_vector type names.
481 /// This is only necessary for issuing pretty diagnostics.
482 ExtVectorDeclsType ExtVectorDecls;
484 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
485 std::unique_ptr<CXXFieldCollector> FieldCollector;
487 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
489 /// \brief Set containing all declared private fields that are not used.
490 NamedDeclSetType UnusedPrivateFields;
492 /// \brief Set containing all typedefs that are likely unused.
493 llvm::SmallSetVector<const TypedefNameDecl *, 4>
494 UnusedLocalTypedefNameCandidates;
496 /// \brief Delete-expressions to be analyzed at the end of translation unit
498 /// This list contains class members, and locations of delete-expressions
499 /// that could not be proven as to whether they mismatch with new-expression
500 /// used in initializer of the field.
501 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
502 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
503 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
505 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
507 /// PureVirtualClassDiagSet - a set of class declarations which we have
508 /// emitted a list of pure virtual functions. Used to prevent emitting the
509 /// same list more than once.
510 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
512 /// ParsingInitForAutoVars - a set of declarations with auto types for which
513 /// we are currently parsing the initializer.
514 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
516 /// \brief Look for a locally scoped extern "C" declaration by the given name.
517 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
519 typedef LazyVector<VarDecl *, ExternalSemaSource,
520 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
521 TentativeDefinitionsType;
523 /// \brief All the tentative definitions encountered in the TU.
524 TentativeDefinitionsType TentativeDefinitions;
526 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
527 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
528 UnusedFileScopedDeclsType;
530 /// \brief The set of file scoped decls seen so far that have not been used
531 /// and must warn if not used. Only contains the first declaration.
532 UnusedFileScopedDeclsType UnusedFileScopedDecls;
534 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
535 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
536 DelegatingCtorDeclsType;
538 /// \brief All the delegating constructors seen so far in the file, used for
539 /// cycle detection at the end of the TU.
540 DelegatingCtorDeclsType DelegatingCtorDecls;
542 /// \brief All the overriding functions seen during a class definition
543 /// that had their exception spec checks delayed, plus the overridden
545 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
546 DelayedExceptionSpecChecks;
548 /// \brief All the members seen during a class definition which were both
549 /// explicitly defaulted and had explicitly-specified exception
550 /// specifications, along with the function type containing their
551 /// user-specified exception specification. Those exception specifications
552 /// were overridden with the default specifications, but we still need to
553 /// check whether they are compatible with the default specification, and
554 /// we can't do that until the nesting set of class definitions is complete.
555 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
556 DelayedDefaultedMemberExceptionSpecs;
558 typedef llvm::MapVector<const FunctionDecl *,
559 std::unique_ptr<LateParsedTemplate>>
560 LateParsedTemplateMapT;
561 LateParsedTemplateMapT LateParsedTemplateMap;
563 /// \brief Callback to the parser to parse templated functions when needed.
564 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
565 typedef void LateTemplateParserCleanupCB(void *P);
566 LateTemplateParserCB *LateTemplateParser;
567 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
570 void SetLateTemplateParser(LateTemplateParserCB *LTP,
571 LateTemplateParserCleanupCB *LTPCleanup,
573 LateTemplateParser = LTP;
574 LateTemplateParserCleanup = LTPCleanup;
578 class DelayedDiagnostics;
580 class DelayedDiagnosticsState {
581 sema::DelayedDiagnosticPool *SavedPool;
582 friend class Sema::DelayedDiagnostics;
584 typedef DelayedDiagnosticsState ParsingDeclState;
585 typedef DelayedDiagnosticsState ProcessingContextState;
587 /// A class which encapsulates the logic for delaying diagnostics
588 /// during parsing and other processing.
589 class DelayedDiagnostics {
590 /// \brief The current pool of diagnostics into which delayed
591 /// diagnostics should go.
592 sema::DelayedDiagnosticPool *CurPool;
595 DelayedDiagnostics() : CurPool(nullptr) {}
597 /// Adds a delayed diagnostic.
598 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
600 /// Determines whether diagnostics should be delayed.
601 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
603 /// Returns the current delayed-diagnostics pool.
604 sema::DelayedDiagnosticPool *getCurrentPool() const {
608 /// Enter a new scope. Access and deprecation diagnostics will be
609 /// collected in this pool.
610 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
611 DelayedDiagnosticsState state;
612 state.SavedPool = CurPool;
617 /// Leave a delayed-diagnostic state that was previously pushed.
618 /// Do not emit any of the diagnostics. This is performed as part
619 /// of the bookkeeping of popping a pool "properly".
620 void popWithoutEmitting(DelayedDiagnosticsState state) {
621 CurPool = state.SavedPool;
624 /// Enter a new scope where access and deprecation diagnostics are
626 DelayedDiagnosticsState pushUndelayed() {
627 DelayedDiagnosticsState state;
628 state.SavedPool = CurPool;
633 /// Undo a previous pushUndelayed().
634 void popUndelayed(DelayedDiagnosticsState state) {
635 assert(CurPool == nullptr);
636 CurPool = state.SavedPool;
638 } DelayedDiagnostics;
640 /// A RAII object to temporarily push a declaration context.
644 DeclContext *SavedContext;
645 ProcessingContextState SavedContextState;
646 QualType SavedCXXThisTypeOverride;
649 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
650 : S(S), SavedContext(S.CurContext),
651 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
652 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
654 assert(ContextToPush && "pushing null context");
655 S.CurContext = ContextToPush;
657 S.CXXThisTypeOverride = QualType();
661 if (!SavedContext) return;
662 S.CurContext = SavedContext;
663 S.DelayedDiagnostics.popUndelayed(SavedContextState);
664 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
665 SavedContext = nullptr;
673 /// \brief RAII object to handle the state changes required to synthesize
675 class SynthesizedFunctionScope {
677 Sema::ContextRAII SavedContext;
680 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
681 : S(S), SavedContext(S, DC)
683 S.PushFunctionScope();
684 S.PushExpressionEvaluationContext(
685 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
688 ~SynthesizedFunctionScope() {
689 S.PopExpressionEvaluationContext();
690 S.PopFunctionScopeInfo();
694 /// WeakUndeclaredIdentifiers - Identifiers contained in
695 /// \#pragma weak before declared. rare. may alias another
696 /// identifier, declared or undeclared
697 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
699 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
700 /// \#pragma redefine_extname before declared. Used in Solaris system headers
701 /// to define functions that occur in multiple standards to call the version
702 /// in the currently selected standard.
703 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
706 /// \brief Load weak undeclared identifiers from the external source.
707 void LoadExternalWeakUndeclaredIdentifiers();
709 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
710 /// \#pragma weak during processing of other Decls.
711 /// I couldn't figure out a clean way to generate these in-line, so
712 /// we store them here and handle separately -- which is a hack.
713 /// It would be best to refactor this.
714 SmallVector<Decl*,2> WeakTopLevelDecl;
716 IdentifierResolver IdResolver;
718 /// Translation Unit Scope - useful to Objective-C actions that need
719 /// to lookup file scope declarations in the "ordinary" C decl namespace.
720 /// For example, user-defined classes, built-in "id" type, etc.
723 /// \brief The C++ "std" namespace, where the standard library resides.
724 LazyDeclPtr StdNamespace;
726 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
727 /// standard library.
728 LazyDeclPtr StdBadAlloc;
730 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
731 /// standard library.
732 LazyDeclPtr StdAlignValT;
734 /// \brief The C++ "std::experimental" namespace, where the experimental parts
735 /// of the standard library resides.
736 NamespaceDecl *StdExperimentalNamespaceCache;
738 /// \brief The C++ "std::initializer_list" template, which is defined in
739 /// \<initializer_list>.
740 ClassTemplateDecl *StdInitializerList;
742 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
743 RecordDecl *CXXTypeInfoDecl;
745 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
746 RecordDecl *MSVCGuidDecl;
748 /// \brief Caches identifiers/selectors for NSFoundation APIs.
749 std::unique_ptr<NSAPI> NSAPIObj;
751 /// \brief The declaration of the Objective-C NSNumber class.
752 ObjCInterfaceDecl *NSNumberDecl;
754 /// \brief The declaration of the Objective-C NSValue class.
755 ObjCInterfaceDecl *NSValueDecl;
757 /// \brief Pointer to NSNumber type (NSNumber *).
758 QualType NSNumberPointer;
760 /// \brief Pointer to NSValue type (NSValue *).
761 QualType NSValuePointer;
763 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
764 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
766 /// \brief The declaration of the Objective-C NSString class.
767 ObjCInterfaceDecl *NSStringDecl;
769 /// \brief Pointer to NSString type (NSString *).
770 QualType NSStringPointer;
772 /// \brief The declaration of the stringWithUTF8String: method.
773 ObjCMethodDecl *StringWithUTF8StringMethod;
775 /// \brief The declaration of the valueWithBytes:objCType: method.
776 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
778 /// \brief The declaration of the Objective-C NSArray class.
779 ObjCInterfaceDecl *NSArrayDecl;
781 /// \brief The declaration of the arrayWithObjects:count: method.
782 ObjCMethodDecl *ArrayWithObjectsMethod;
784 /// \brief The declaration of the Objective-C NSDictionary class.
785 ObjCInterfaceDecl *NSDictionaryDecl;
787 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
788 ObjCMethodDecl *DictionaryWithObjectsMethod;
790 /// \brief id<NSCopying> type.
791 QualType QIDNSCopying;
793 /// \brief will hold 'respondsToSelector:'
794 Selector RespondsToSelectorSel;
796 /// A flag to remember whether the implicit forms of operator new and delete
797 /// have been declared.
798 bool GlobalNewDeleteDeclared;
800 /// A flag to indicate that we're in a context that permits abstract
801 /// references to fields. This is really a
802 bool AllowAbstractFieldReference;
804 /// \brief Describes how the expressions currently being parsed are
805 /// evaluated at run-time, if at all.
806 enum class ExpressionEvaluationContext {
807 /// \brief The current expression and its subexpressions occur within an
808 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
809 /// \c sizeof, where the type of the expression may be significant but
810 /// no code will be generated to evaluate the value of the expression at
814 /// \brief The current expression occurs within a braced-init-list within
815 /// an unevaluated operand. This is mostly like a regular unevaluated
816 /// context, except that we still instantiate constexpr functions that are
817 /// referenced here so that we can perform narrowing checks correctly.
820 /// \brief The current expression occurs within a discarded statement.
821 /// This behaves largely similarly to an unevaluated operand in preventing
822 /// definitions from being required, but not in other ways.
825 /// \brief The current expression occurs within an unevaluated
826 /// operand that unconditionally permits abstract references to
827 /// fields, such as a SIZE operator in MS-style inline assembly.
830 /// \brief The current context is "potentially evaluated" in C++11 terms,
831 /// but the expression is evaluated at compile-time (like the values of
832 /// cases in a switch statement).
835 /// \brief The current expression is potentially evaluated at run time,
836 /// which means that code may be generated to evaluate the value of the
837 /// expression at run time.
838 PotentiallyEvaluated,
840 /// \brief The current expression is potentially evaluated, but any
841 /// declarations referenced inside that expression are only used if
842 /// in fact the current expression is used.
844 /// This value is used when parsing default function arguments, for which
845 /// we would like to provide diagnostics (e.g., passing non-POD arguments
846 /// through varargs) but do not want to mark declarations as "referenced"
847 /// until the default argument is used.
848 PotentiallyEvaluatedIfUsed
851 /// \brief Data structure used to record current or nested
852 /// expression evaluation contexts.
853 struct ExpressionEvaluationContextRecord {
854 /// \brief The expression evaluation context.
855 ExpressionEvaluationContext Context;
857 /// \brief Whether the enclosing context needed a cleanup.
858 CleanupInfo ParentCleanup;
860 /// \brief Whether we are in a decltype expression.
863 /// \brief The number of active cleanup objects when we entered
864 /// this expression evaluation context.
865 unsigned NumCleanupObjects;
867 /// \brief The number of typos encountered during this expression evaluation
868 /// context (i.e. the number of TypoExprs created).
871 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
873 /// \brief The lambdas that are present within this context, if it
874 /// is indeed an unevaluated context.
875 SmallVector<LambdaExpr *, 2> Lambdas;
877 /// \brief The declaration that provides context for lambda expressions
878 /// and block literals if the normal declaration context does not
879 /// suffice, e.g., in a default function argument.
880 Decl *ManglingContextDecl;
882 /// \brief The context information used to mangle lambda expressions
883 /// and block literals within this context.
885 /// This mangling information is allocated lazily, since most contexts
886 /// do not have lambda expressions or block literals.
887 std::unique_ptr<MangleNumberingContext> MangleNumbering;
889 /// \brief If we are processing a decltype type, a set of call expressions
890 /// for which we have deferred checking the completeness of the return type.
891 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
893 /// \brief If we are processing a decltype type, a set of temporary binding
894 /// expressions for which we have deferred checking the destructor.
895 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
897 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
898 unsigned NumCleanupObjects,
899 CleanupInfo ParentCleanup,
900 Decl *ManglingContextDecl,
902 : Context(Context), ParentCleanup(ParentCleanup),
903 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
905 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
907 /// \brief Retrieve the mangling numbering context, used to consistently
908 /// number constructs like lambdas for mangling.
909 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
911 bool isUnevaluated() const {
912 return Context == ExpressionEvaluationContext::Unevaluated ||
913 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
914 Context == ExpressionEvaluationContext::UnevaluatedList;
916 bool isConstantEvaluated() const {
917 return Context == ExpressionEvaluationContext::ConstantEvaluated;
921 /// A stack of expression evaluation contexts.
922 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
924 /// \brief Compute the mangling number context for a lambda expression or
927 /// \param DC - The DeclContext containing the lambda expression or
929 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
930 /// associated with the context, if relevant.
931 MangleNumberingContext *getCurrentMangleNumberContext(
932 const DeclContext *DC,
933 Decl *&ManglingContextDecl);
936 /// SpecialMemberOverloadResult - The overloading result for a special member
939 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
940 /// integer are used to determine whether overload resolution succeeded.
941 class SpecialMemberOverloadResult {
950 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
953 SpecialMemberOverloadResult() : Pair() {}
954 SpecialMemberOverloadResult(CXXMethodDecl *MD)
955 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
957 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
958 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
960 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
961 void setKind(Kind K) { Pair.setInt(K); }
964 class SpecialMemberOverloadResultEntry
965 : public llvm::FastFoldingSetNode,
966 public SpecialMemberOverloadResult {
968 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
969 : FastFoldingSetNode(ID)
973 /// \brief A cache of special member function overload resolution results
975 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
977 /// \brief A cache of the flags available in enumerations with the flag_bits
979 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
981 /// \brief The kind of translation unit we are processing.
983 /// When we're processing a complete translation unit, Sema will perform
984 /// end-of-translation-unit semantic tasks (such as creating
985 /// initializers for tentative definitions in C) once parsing has
986 /// completed. Modules and precompiled headers perform different kinds of
988 TranslationUnitKind TUKind;
990 llvm::BumpPtrAllocator BumpAlloc;
992 /// \brief The number of SFINAE diagnostics that have been trapped.
993 unsigned NumSFINAEErrors;
995 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
996 UnparsedDefaultArgInstantiationsMap;
998 /// \brief A mapping from parameters with unparsed default arguments to the
999 /// set of instantiations of each parameter.
1001 /// This mapping is a temporary data structure used when parsing
1002 /// nested class templates or nested classes of class templates,
1003 /// where we might end up instantiating an inner class before the
1004 /// default arguments of its methods have been parsed.
1005 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1007 // Contains the locations of the beginning of unparsed default
1008 // argument locations.
1009 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1011 /// UndefinedInternals - all the used, undefined objects which require a
1012 /// definition in this translation unit.
1013 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1015 /// Obtain a sorted list of functions that are undefined but ODR-used.
1016 void getUndefinedButUsed(
1017 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1019 /// Retrieves list of suspicious delete-expressions that will be checked at
1020 /// the end of translation unit.
1021 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1022 getMismatchingDeleteExpressions() const;
1024 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1025 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1027 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1028 /// We need to maintain a list, since selectors can have differing signatures
1029 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1030 /// of selectors are "overloaded").
1031 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1032 /// methods inside categories with a particular selector.
1033 GlobalMethodPool MethodPool;
1035 /// Method selectors used in a \@selector expression. Used for implementation
1037 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1039 /// Kinds of C++ special members.
1040 enum CXXSpecialMember {
1041 CXXDefaultConstructor,
1050 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1052 /// The C++ special members which we are currently in the process of
1053 /// declaring. If this process recursively triggers the declaration of the
1054 /// same special member, we should act as if it is not yet declared.
1055 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1057 void ReadMethodPool(Selector Sel);
1058 void updateOutOfDateSelector(Selector Sel);
1060 /// Private Helper predicate to check for 'self'.
1061 bool isSelfExpr(Expr *RExpr);
1062 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1064 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1065 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1066 /// should not be used elsewhere.
1067 void EmitCurrentDiagnostic(unsigned DiagID);
1069 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1071 class FPContractStateRAII {
1073 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1074 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1078 FPOptions OldFPFeaturesState;
1081 void addImplicitTypedef(StringRef Name, QualType T);
1084 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1085 TranslationUnitKind TUKind = TU_Complete,
1086 CodeCompleteConsumer *CompletionConsumer = nullptr);
1089 /// \brief Perform initialization that occurs after the parser has been
1090 /// initialized but before it parses anything.
1093 const LangOptions &getLangOpts() const { return LangOpts; }
1094 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1095 FPOptions &getFPOptions() { return FPFeatures; }
1097 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1098 SourceManager &getSourceManager() const { return SourceMgr; }
1099 Preprocessor &getPreprocessor() const { return PP; }
1100 ASTContext &getASTContext() const { return Context; }
1101 ASTConsumer &getASTConsumer() const { return Consumer; }
1102 ASTMutationListener *getASTMutationListener() const;
1103 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1105 ///\brief Registers an external source. If an external source already exists,
1106 /// creates a multiplex external source and appends to it.
1108 ///\param[in] E - A non-null external sema source.
1110 void addExternalSource(ExternalSemaSource *E);
1112 void PrintStats() const;
1114 /// \brief Helper class that creates diagnostics with optional
1115 /// template instantiation stacks.
1117 /// This class provides a wrapper around the basic DiagnosticBuilder
1118 /// class that emits diagnostics. SemaDiagnosticBuilder is
1119 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1120 /// does) and, if the diagnostic comes from inside a template
1121 /// instantiation, printing the template instantiation stack as
1123 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1128 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1129 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1131 // This is a cunning lie. DiagnosticBuilder actually performs move
1132 // construction in its copy constructor (but due to varied uses, it's not
1133 // possible to conveniently express this as actual move construction). So
1134 // the default copy ctor here is fine, because the base class disables the
1135 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1136 // in that case anwyay.
1137 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1139 ~SemaDiagnosticBuilder() {
1140 // If we aren't active, there is nothing to do.
1141 if (!isActive()) return;
1143 // Otherwise, we need to emit the diagnostic. First flush the underlying
1144 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1145 // won't emit the diagnostic in its own destructor.
1147 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1148 // do its own needless checks to see if the diagnostic needs to be
1149 // emitted. However, because we take care to ensure that the builder
1150 // objects never escape, a sufficiently smart compiler will be able to
1151 // eliminate that code.
1155 // Dispatch to Sema to emit the diagnostic.
1156 SemaRef.EmitCurrentDiagnostic(DiagID);
1159 /// Teach operator<< to produce an object of the correct type.
1160 template<typename T>
1161 friend const SemaDiagnosticBuilder &operator<<(
1162 const SemaDiagnosticBuilder &Diag, const T &Value) {
1163 const DiagnosticBuilder &BaseDiag = Diag;
1169 /// \brief Emit a diagnostic.
1170 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1171 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1172 return SemaDiagnosticBuilder(DB, *this, DiagID);
1175 /// \brief Emit a partial diagnostic.
1176 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1178 /// \brief Build a partial diagnostic.
1179 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1181 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1183 /// \brief Get a string to suggest for zero-initialization of a type.
1185 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1186 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1188 /// \brief Calls \c Lexer::getLocForEndOfToken()
1189 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1191 /// \brief Retrieve the module loader associated with the preprocessor.
1192 ModuleLoader &getModuleLoader() const;
1194 void emitAndClearUnusedLocalTypedefWarnings();
1196 void ActOnEndOfTranslationUnit();
1198 void CheckDelegatingCtorCycles();
1200 Scope *getScopeForContext(DeclContext *Ctx);
1202 void PushFunctionScope();
1203 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1204 sema::LambdaScopeInfo *PushLambdaScope();
1206 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1207 /// is during Parsing. Currently it is used to pass on the depth
1208 /// when parsing generic lambda 'auto' parameters.
1209 void RecordParsingTemplateParameterDepth(unsigned Depth);
1211 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1213 CapturedRegionKind K);
1215 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1216 const Decl *D = nullptr,
1217 const BlockExpr *blkExpr = nullptr);
1219 sema::FunctionScopeInfo *getCurFunction() const {
1220 return FunctionScopes.back();
1223 sema::FunctionScopeInfo *getEnclosingFunction() const {
1224 if (FunctionScopes.empty())
1227 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1228 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1230 return FunctionScopes[e];
1235 template <typename ExprT>
1236 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1237 if (!isUnevaluatedContext())
1238 getCurFunction()->recordUseOfWeak(E, IsRead);
1241 void PushCompoundScope();
1242 void PopCompoundScope();
1244 sema::CompoundScopeInfo &getCurCompoundScope() const;
1246 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1248 /// \brief Retrieve the current block, if any.
1249 sema::BlockScopeInfo *getCurBlock();
1251 /// Retrieve the current lambda scope info, if any.
1252 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1253 /// lambda scope info ignoring all inner capturing scopes that are not
1255 sema::LambdaScopeInfo *
1256 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1258 /// \brief Retrieve the current generic lambda info, if any.
1259 sema::LambdaScopeInfo *getCurGenericLambda();
1261 /// \brief Retrieve the current captured region, if any.
1262 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1264 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1265 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1267 void ActOnComment(SourceRange Comment);
1269 //===--------------------------------------------------------------------===//
1270 // Type Analysis / Processing: SemaType.cpp.
1273 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1274 const DeclSpec *DS = nullptr);
1275 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1276 const DeclSpec *DS = nullptr);
1277 QualType BuildPointerType(QualType T,
1278 SourceLocation Loc, DeclarationName Entity);
1279 QualType BuildReferenceType(QualType T, bool LValueRef,
1280 SourceLocation Loc, DeclarationName Entity);
1281 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1282 Expr *ArraySize, unsigned Quals,
1283 SourceRange Brackets, DeclarationName Entity);
1284 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1285 SourceLocation AttrLoc);
1287 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1289 /// \brief Build a function type.
1291 /// This routine checks the function type according to C++ rules and
1292 /// under the assumption that the result type and parameter types have
1293 /// just been instantiated from a template. It therefore duplicates
1294 /// some of the behavior of GetTypeForDeclarator, but in a much
1295 /// simpler form that is only suitable for this narrow use case.
1297 /// \param T The return type of the function.
1299 /// \param ParamTypes The parameter types of the function. This array
1300 /// will be modified to account for adjustments to the types of the
1301 /// function parameters.
1303 /// \param Loc The location of the entity whose type involves this
1304 /// function type or, if there is no such entity, the location of the
1305 /// type that will have function type.
1307 /// \param Entity The name of the entity that involves the function
1310 /// \param EPI Extra information about the function type. Usually this will
1311 /// be taken from an existing function with the same prototype.
1313 /// \returns A suitable function type, if there are no errors. The
1314 /// unqualified type will always be a FunctionProtoType.
1315 /// Otherwise, returns a NULL type.
1316 QualType BuildFunctionType(QualType T,
1317 MutableArrayRef<QualType> ParamTypes,
1318 SourceLocation Loc, DeclarationName Entity,
1319 const FunctionProtoType::ExtProtoInfo &EPI);
1321 QualType BuildMemberPointerType(QualType T, QualType Class,
1323 DeclarationName Entity);
1324 QualType BuildBlockPointerType(QualType T,
1325 SourceLocation Loc, DeclarationName Entity);
1326 QualType BuildParenType(QualType T);
1327 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1328 QualType BuildReadPipeType(QualType T,
1329 SourceLocation Loc);
1330 QualType BuildWritePipeType(QualType T,
1331 SourceLocation Loc);
1333 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1334 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1335 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1336 TypeSourceInfo *ReturnTypeInfo);
1338 /// \brief Package the given type and TSI into a ParsedType.
1339 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1340 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1341 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1342 static QualType GetTypeFromParser(ParsedType Ty,
1343 TypeSourceInfo **TInfo = nullptr);
1344 CanThrowResult canThrow(const Expr *E);
1345 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1346 const FunctionProtoType *FPT);
1347 void UpdateExceptionSpec(FunctionDecl *FD,
1348 const FunctionProtoType::ExceptionSpecInfo &ESI);
1349 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1350 bool CheckDistantExceptionSpec(QualType T);
1351 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1352 bool CheckEquivalentExceptionSpec(
1353 const FunctionProtoType *Old, SourceLocation OldLoc,
1354 const FunctionProtoType *New, SourceLocation NewLoc);
1355 bool CheckEquivalentExceptionSpec(
1356 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1357 const FunctionProtoType *Old, SourceLocation OldLoc,
1358 const FunctionProtoType *New, SourceLocation NewLoc);
1359 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1360 const PartialDiagnostic &NestedDiagID,
1361 const PartialDiagnostic &NoteID,
1362 const FunctionProtoType *Superset,
1363 SourceLocation SuperLoc,
1364 const FunctionProtoType *Subset,
1365 SourceLocation SubLoc);
1366 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1367 const PartialDiagnostic &NoteID,
1368 const FunctionProtoType *Target,
1369 SourceLocation TargetLoc,
1370 const FunctionProtoType *Source,
1371 SourceLocation SourceLoc);
1373 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1375 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1376 /// in an Objective-C message declaration. Return the appropriate type.
1377 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1379 /// \brief Abstract class used to diagnose incomplete types.
1380 struct TypeDiagnoser {
1383 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1384 virtual ~TypeDiagnoser() {}
1387 static int getPrintable(int I) { return I; }
1388 static unsigned getPrintable(unsigned I) { return I; }
1389 static bool getPrintable(bool B) { return B; }
1390 static const char * getPrintable(const char *S) { return S; }
1391 static StringRef getPrintable(StringRef S) { return S; }
1392 static const std::string &getPrintable(const std::string &S) { return S; }
1393 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1396 static DeclarationName getPrintable(DeclarationName N) { return N; }
1397 static QualType getPrintable(QualType T) { return T; }
1398 static SourceRange getPrintable(SourceRange R) { return R; }
1399 static SourceRange getPrintable(SourceLocation L) { return L; }
1400 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1401 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1403 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1405 std::tuple<const Ts &...> Args;
1407 template <std::size_t... Is>
1408 void emit(const SemaDiagnosticBuilder &DB,
1409 llvm::index_sequence<Is...>) const {
1410 // Apply all tuple elements to the builder in order.
1411 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1416 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1417 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1418 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1421 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1422 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1423 emit(DB, llvm::index_sequence_for<Ts...>());
1429 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1430 TypeDiagnoser *Diagnoser);
1432 struct ModuleScope {
1433 clang::Module *Module;
1434 VisibleModuleSet OuterVisibleModules;
1436 /// The modules we're currently parsing.
1437 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1439 VisibleModuleSet VisibleModules;
1441 Module *CachedFakeTopLevelModule;
1444 /// \brief Get the module owning an entity.
1445 Module *getOwningModule(Decl *Entity);
1447 /// \brief Make a merged definition of an existing hidden definition \p ND
1448 /// visible at the specified location.
1449 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1451 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1453 /// Determine whether a declaration is visible to name lookup.
1454 bool isVisible(const NamedDecl *D) {
1455 return !D->isHidden() || isVisibleSlow(D);
1458 /// Determine whether any declaration of an entity is visible.
1460 hasVisibleDeclaration(const NamedDecl *D,
1461 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1462 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1464 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1465 llvm::SmallVectorImpl<Module *> *Modules);
1467 bool hasVisibleMergedDefinition(NamedDecl *Def);
1469 /// Determine if \p D has a visible definition. If not, suggest a declaration
1470 /// that should be made visible to expose the definition.
1471 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1472 bool OnlyNeedComplete = false);
1473 bool hasVisibleDefinition(const NamedDecl *D) {
1475 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1478 /// Determine if the template parameter \p D has a visible default argument.
1480 hasVisibleDefaultArgument(const NamedDecl *D,
1481 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1483 /// Determine if there is a visible declaration of \p D that is a member
1484 /// specialization declaration (as opposed to an instantiated declaration).
1485 bool hasVisibleMemberSpecialization(
1486 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1488 /// Determine if \p A and \p B are equivalent internal linkage declarations
1489 /// from different modules, and thus an ambiguity error can be downgraded to
1490 /// an extension warning.
1491 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1492 const NamedDecl *B);
1493 void diagnoseEquivalentInternalLinkageDeclarations(
1494 SourceLocation Loc, const NamedDecl *D,
1495 ArrayRef<const NamedDecl *> Equiv);
1497 bool isCompleteType(SourceLocation Loc, QualType T) {
1498 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1500 bool RequireCompleteType(SourceLocation Loc, QualType T,
1501 TypeDiagnoser &Diagnoser);
1502 bool RequireCompleteType(SourceLocation Loc, QualType T,
1505 template <typename... Ts>
1506 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1507 const Ts &...Args) {
1508 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1509 return RequireCompleteType(Loc, T, Diagnoser);
1512 void completeExprArrayBound(Expr *E);
1513 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1514 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1516 template <typename... Ts>
1517 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1518 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1519 return RequireCompleteExprType(E, Diagnoser);
1522 bool RequireLiteralType(SourceLocation Loc, QualType T,
1523 TypeDiagnoser &Diagnoser);
1524 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1526 template <typename... Ts>
1527 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1528 const Ts &...Args) {
1529 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1530 return RequireLiteralType(Loc, T, Diagnoser);
1533 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1534 const CXXScopeSpec &SS, QualType T);
1536 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1537 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1538 /// context, such as when building a type for decltype(auto).
1539 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1540 bool AsUnevaluated = true);
1541 QualType BuildUnaryTransformType(QualType BaseType,
1542 UnaryTransformType::UTTKind UKind,
1543 SourceLocation Loc);
1545 //===--------------------------------------------------------------------===//
1546 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1549 struct SkipBodyInfo {
1550 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1552 NamedDecl *Previous;
1555 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1557 void DiagnoseUseOfUnimplementedSelectors();
1559 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1561 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1562 Scope *S, CXXScopeSpec *SS = nullptr,
1563 bool isClassName = false, bool HasTrailingDot = false,
1564 ParsedType ObjectType = nullptr,
1565 bool IsCtorOrDtorName = false,
1566 bool WantNontrivialTypeSourceInfo = false,
1567 bool IsClassTemplateDeductionContext = true,
1568 IdentifierInfo **CorrectedII = nullptr);
1569 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1570 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1571 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1572 SourceLocation IILoc,
1575 ParsedType &SuggestedType,
1576 bool AllowClassTemplates = false);
1578 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1579 /// type name has failed in a dependent context. In these situations, we
1580 /// automatically form a DependentTypeName that will retry lookup in a related
1581 /// scope during instantiation.
1582 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1583 SourceLocation NameLoc,
1584 bool IsTemplateTypeArg);
1586 /// \brief Describes the result of the name lookup and resolution performed
1587 /// by \c ClassifyName().
1588 enum NameClassificationKind {
1594 NC_NestedNameSpecifier,
1600 class NameClassification {
1601 NameClassificationKind Kind;
1603 TemplateName Template;
1605 const IdentifierInfo *Keyword;
1607 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1610 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1612 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1614 NameClassification(const IdentifierInfo *Keyword)
1615 : Kind(NC_Keyword), Keyword(Keyword) { }
1617 static NameClassification Error() {
1618 return NameClassification(NC_Error);
1621 static NameClassification Unknown() {
1622 return NameClassification(NC_Unknown);
1625 static NameClassification NestedNameSpecifier() {
1626 return NameClassification(NC_NestedNameSpecifier);
1629 static NameClassification TypeTemplate(TemplateName Name) {
1630 NameClassification Result(NC_TypeTemplate);
1631 Result.Template = Name;
1635 static NameClassification VarTemplate(TemplateName Name) {
1636 NameClassification Result(NC_VarTemplate);
1637 Result.Template = Name;
1641 static NameClassification FunctionTemplate(TemplateName Name) {
1642 NameClassification Result(NC_FunctionTemplate);
1643 Result.Template = Name;
1647 NameClassificationKind getKind() const { return Kind; }
1649 ParsedType getType() const {
1650 assert(Kind == NC_Type);
1654 ExprResult getExpression() const {
1655 assert(Kind == NC_Expression);
1659 TemplateName getTemplateName() const {
1660 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1661 Kind == NC_VarTemplate);
1665 TemplateNameKind getTemplateNameKind() const {
1667 case NC_TypeTemplate:
1668 return TNK_Type_template;
1669 case NC_FunctionTemplate:
1670 return TNK_Function_template;
1671 case NC_VarTemplate:
1672 return TNK_Var_template;
1674 llvm_unreachable("unsupported name classification.");
1679 /// \brief Perform name lookup on the given name, classifying it based on
1680 /// the results of name lookup and the following token.
1682 /// This routine is used by the parser to resolve identifiers and help direct
1683 /// parsing. When the identifier cannot be found, this routine will attempt
1684 /// to correct the typo and classify based on the resulting name.
1686 /// \param S The scope in which we're performing name lookup.
1688 /// \param SS The nested-name-specifier that precedes the name.
1690 /// \param Name The identifier. If typo correction finds an alternative name,
1691 /// this pointer parameter will be updated accordingly.
1693 /// \param NameLoc The location of the identifier.
1695 /// \param NextToken The token following the identifier. Used to help
1696 /// disambiguate the name.
1698 /// \param IsAddressOfOperand True if this name is the operand of a unary
1699 /// address of ('&') expression, assuming it is classified as an
1702 /// \param CCC The correction callback, if typo correction is desired.
1704 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1705 SourceLocation NameLoc, const Token &NextToken,
1706 bool IsAddressOfOperand,
1707 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1709 /// Describes the detailed kind of a template name. Used in diagnostics.
1710 enum class TemplateNameKindForDiagnostics {
1715 TemplateTemplateParam,
1718 TemplateNameKindForDiagnostics
1719 getTemplateNameKindForDiagnostics(TemplateName Name);
1721 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1723 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1724 MultiTemplateParamsArg TemplateParameterLists);
1725 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1726 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1727 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1728 DeclarationName Name,
1729 SourceLocation Loc);
1731 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1732 SourceLocation FallbackLoc,
1733 SourceLocation ConstQualLoc = SourceLocation(),
1734 SourceLocation VolatileQualLoc = SourceLocation(),
1735 SourceLocation RestrictQualLoc = SourceLocation(),
1736 SourceLocation AtomicQualLoc = SourceLocation(),
1737 SourceLocation UnalignedQualLoc = SourceLocation());
1739 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1740 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1741 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1742 const LookupResult &R);
1743 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1744 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1745 const LookupResult &R);
1746 void CheckShadow(Scope *S, VarDecl *D);
1748 /// Warn if 'E', which is an expression that is about to be modified, refers
1749 /// to a shadowing declaration.
1750 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1752 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1755 /// Map of current shadowing declarations to shadowed declarations. Warn if
1756 /// it looks like the user is trying to modify the shadowing declaration.
1757 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1760 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1761 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1762 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1763 TypedefNameDecl *NewTD);
1764 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1765 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1766 TypeSourceInfo *TInfo,
1767 LookupResult &Previous);
1768 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1769 LookupResult &Previous, bool &Redeclaration);
1770 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1771 TypeSourceInfo *TInfo,
1772 LookupResult &Previous,
1773 MultiTemplateParamsArg TemplateParamLists,
1775 ArrayRef<BindingDecl *> Bindings = None);
1777 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1778 MultiTemplateParamsArg TemplateParamLists);
1779 // Returns true if the variable declaration is a redeclaration
1780 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1781 void CheckVariableDeclarationType(VarDecl *NewVD);
1782 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1784 void CheckCompleteVariableDeclaration(VarDecl *VD);
1785 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1786 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1788 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1789 TypeSourceInfo *TInfo,
1790 LookupResult &Previous,
1791 MultiTemplateParamsArg TemplateParamLists,
1793 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1795 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1796 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1798 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1799 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1800 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1801 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1802 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1803 // Returns true if the function declaration is a redeclaration
1804 bool CheckFunctionDeclaration(Scope *S,
1805 FunctionDecl *NewFD, LookupResult &Previous,
1806 bool IsMemberSpecialization);
1807 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1808 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1809 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1810 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1811 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1814 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1815 SourceLocation NameLoc, IdentifierInfo *Name,
1816 QualType T, TypeSourceInfo *TSInfo,
1818 void ActOnParamDefaultArgument(Decl *param,
1819 SourceLocation EqualLoc,
1821 void ActOnParamUnparsedDefaultArgument(Decl *param,
1822 SourceLocation EqualLoc,
1823 SourceLocation ArgLoc);
1824 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1825 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1826 SourceLocation EqualLoc);
1828 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1829 void ActOnUninitializedDecl(Decl *dcl);
1830 void ActOnInitializerError(Decl *Dcl);
1832 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1833 void ActOnCXXForRangeDecl(Decl *D);
1834 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1835 IdentifierInfo *Ident,
1836 ParsedAttributes &Attrs,
1837 SourceLocation AttrEnd);
1838 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1839 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1840 void FinalizeDeclaration(Decl *D);
1841 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1842 ArrayRef<Decl *> Group);
1843 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1845 /// Should be called on all declarations that might have attached
1846 /// documentation comments.
1847 void ActOnDocumentableDecl(Decl *D);
1848 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1850 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1851 SourceLocation LocAfterDecls);
1852 void CheckForFunctionRedefinition(
1853 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1854 SkipBodyInfo *SkipBody = nullptr);
1855 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1856 MultiTemplateParamsArg TemplateParamLists,
1857 SkipBodyInfo *SkipBody = nullptr);
1858 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1859 SkipBodyInfo *SkipBody = nullptr);
1860 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1861 bool isObjCMethodDecl(Decl *D) {
1862 return D && isa<ObjCMethodDecl>(D);
1865 /// \brief Determine whether we can delay parsing the body of a function or
1866 /// function template until it is used, assuming we don't care about emitting
1867 /// code for that function.
1869 /// This will be \c false if we may need the body of the function in the
1870 /// middle of parsing an expression (where it's impractical to switch to
1871 /// parsing a different function), for instance, if it's constexpr in C++11
1872 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1873 bool canDelayFunctionBody(const Declarator &D);
1875 /// \brief Determine whether we can skip parsing the body of a function
1876 /// definition, assuming we don't care about analyzing its body or emitting
1877 /// code for that function.
1879 /// This will be \c false only if we may need the body of the function in
1880 /// order to parse the rest of the program (for instance, if it is
1881 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1882 bool canSkipFunctionBody(Decl *D);
1884 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1885 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1886 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1887 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1888 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1890 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1891 /// attribute for which parsing is delayed.
1892 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1894 /// \brief Diagnose any unused parameters in the given sequence of
1895 /// ParmVarDecl pointers.
1896 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1898 /// \brief Diagnose whether the size of parameters or return value of a
1899 /// function or obj-c method definition is pass-by-value and larger than a
1900 /// specified threshold.
1902 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1903 QualType ReturnTy, NamedDecl *D);
1905 void DiagnoseInvalidJumps(Stmt *Body);
1906 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1907 SourceLocation AsmLoc,
1908 SourceLocation RParenLoc);
1910 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1911 Decl *ActOnEmptyDeclaration(Scope *S,
1912 AttributeList *AttrList,
1913 SourceLocation SemiLoc);
1915 enum class ModuleDeclKind {
1916 Module, ///< 'module X;'
1917 Partition, ///< 'module partition X;'
1918 Implementation, ///< 'module implementation X;'
1921 /// The parser has processed a module-declaration that begins the definition
1922 /// of a module interface or implementation.
1923 DeclGroupPtrTy ActOnModuleDecl(SourceLocation ModuleLoc, ModuleDeclKind MDK,
1926 /// \brief The parser has processed a module import declaration.
1928 /// \param AtLoc The location of the '@' symbol, if any.
1930 /// \param ImportLoc The location of the 'import' keyword.
1932 /// \param Path The module access path.
1933 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1936 /// \brief The parser has processed a module import translated from a
1937 /// #include or similar preprocessing directive.
1938 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1939 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1941 /// \brief The parsed has entered a submodule.
1942 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1943 /// \brief The parser has left a submodule.
1944 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1946 /// \brief Create an implicit import of the given module at the given
1947 /// source location, for error recovery, if possible.
1949 /// This routine is typically used when an entity found by name lookup
1950 /// is actually hidden within a module that we know about but the user
1951 /// has forgotten to import.
1952 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1955 /// Kinds of missing import. Note, the values of these enumerators correspond
1956 /// to %select values in diagnostics.
1957 enum class MissingImportKind {
1961 ExplicitSpecialization,
1962 PartialSpecialization
1965 /// \brief Diagnose that the specified declaration needs to be visible but
1966 /// isn't, and suggest a module import that would resolve the problem.
1967 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1968 MissingImportKind MIK, bool Recover = true);
1969 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1970 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1971 MissingImportKind MIK, bool Recover);
1973 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1974 SourceLocation LBraceLoc);
1975 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1976 SourceLocation RBraceLoc);
1978 /// \brief We've found a use of a templated declaration that would trigger an
1979 /// implicit instantiation. Check that any relevant explicit specializations
1980 /// and partial specializations are visible, and diagnose if not.
1981 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1983 /// \brief We've found a use of a template specialization that would select a
1984 /// partial specialization. Check that the partial specialization is visible,
1985 /// and diagnose if not.
1986 void checkPartialSpecializationVisibility(SourceLocation Loc,
1989 /// \brief Retrieve a suitable printing policy.
1990 PrintingPolicy getPrintingPolicy() const {
1991 return getPrintingPolicy(Context, PP);
1994 /// \brief Retrieve a suitable printing policy.
1995 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1996 const Preprocessor &PP);
1999 void ActOnPopScope(SourceLocation Loc, Scope *S);
2000 void ActOnTranslationUnitScope(Scope *S);
2002 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2003 RecordDecl *&AnonRecord);
2004 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2005 MultiTemplateParamsArg TemplateParams,
2006 bool IsExplicitInstantiation,
2007 RecordDecl *&AnonRecord);
2009 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2012 const PrintingPolicy &Policy);
2014 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2015 RecordDecl *Record);
2017 /// Common ways to introduce type names without a tag for use in diagnostics.
2018 /// Keep in sync with err_tag_reference_non_tag.
2027 NTK_TypeAliasTemplate,
2028 NTK_TemplateTemplateArgument,
2031 /// Given a non-tag type declaration, returns an enum useful for indicating
2032 /// what kind of non-tag type this is.
2033 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2035 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2036 TagTypeKind NewTag, bool isDefinition,
2037 SourceLocation NewTagLoc,
2038 const IdentifierInfo *Name);
2041 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2042 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2043 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2044 TUK_Friend // Friend declaration: 'friend struct foo;'
2047 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2048 SourceLocation KWLoc, CXXScopeSpec &SS,
2049 IdentifierInfo *Name, SourceLocation NameLoc,
2050 AttributeList *Attr, AccessSpecifier AS,
2051 SourceLocation ModulePrivateLoc,
2052 MultiTemplateParamsArg TemplateParameterLists,
2053 bool &OwnedDecl, bool &IsDependent,
2054 SourceLocation ScopedEnumKWLoc,
2055 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2056 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2058 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2059 unsigned TagSpec, SourceLocation TagLoc,
2061 IdentifierInfo *Name, SourceLocation NameLoc,
2062 AttributeList *Attr,
2063 MultiTemplateParamsArg TempParamLists);
2065 TypeResult ActOnDependentTag(Scope *S,
2068 const CXXScopeSpec &SS,
2069 IdentifierInfo *Name,
2070 SourceLocation TagLoc,
2071 SourceLocation NameLoc);
2073 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2074 IdentifierInfo *ClassName,
2075 SmallVectorImpl<Decl *> &Decls);
2076 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2077 Declarator &D, Expr *BitfieldWidth);
2079 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2080 Declarator &D, Expr *BitfieldWidth,
2081 InClassInitStyle InitStyle,
2082 AccessSpecifier AS);
2083 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2084 SourceLocation DeclStart,
2085 Declarator &D, Expr *BitfieldWidth,
2086 InClassInitStyle InitStyle,
2088 AttributeList *MSPropertyAttr);
2090 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2091 TypeSourceInfo *TInfo,
2092 RecordDecl *Record, SourceLocation Loc,
2093 bool Mutable, Expr *BitfieldWidth,
2094 InClassInitStyle InitStyle,
2095 SourceLocation TSSL,
2096 AccessSpecifier AS, NamedDecl *PrevDecl,
2097 Declarator *D = nullptr);
2099 bool CheckNontrivialField(FieldDecl *FD);
2100 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2101 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2102 bool Diagnose = false);
2103 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2104 void ActOnLastBitfield(SourceLocation DeclStart,
2105 SmallVectorImpl<Decl *> &AllIvarDecls);
2106 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2107 Declarator &D, Expr *BitfieldWidth,
2108 tok::ObjCKeywordKind visibility);
2110 // This is used for both record definitions and ObjC interface declarations.
2111 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2112 ArrayRef<Decl *> Fields,
2113 SourceLocation LBrac, SourceLocation RBrac,
2114 AttributeList *AttrList);
2116 /// ActOnTagStartDefinition - Invoked when we have entered the
2117 /// scope of a tag's definition (e.g., for an enumeration, class,
2118 /// struct, or union).
2119 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2121 typedef void *SkippedDefinitionContext;
2123 /// \brief Invoked when we enter a tag definition that we're skipping.
2124 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2126 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2128 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2129 /// C++ record definition's base-specifiers clause and are starting its
2130 /// member declarations.
2131 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2132 SourceLocation FinalLoc,
2133 bool IsFinalSpelledSealed,
2134 SourceLocation LBraceLoc);
2136 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2137 /// the definition of a tag (enumeration, class, struct, or union).
2138 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2139 SourceRange BraceRange);
2141 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2143 void ActOnObjCContainerFinishDefinition();
2145 /// \brief Invoked when we must temporarily exit the objective-c container
2146 /// scope for parsing/looking-up C constructs.
2148 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2149 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2150 void ActOnObjCReenterContainerContext(DeclContext *DC);
2152 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2153 /// error parsing the definition of a tag.
2154 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2156 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2157 EnumConstantDecl *LastEnumConst,
2158 SourceLocation IdLoc,
2161 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2162 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2163 QualType EnumUnderlyingTy,
2164 bool EnumUnderlyingIsImplicit,
2165 const EnumDecl *Prev);
2167 /// Determine whether the body of an anonymous enumeration should be skipped.
2168 /// \param II The name of the first enumerator.
2169 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2170 SourceLocation IILoc);
2172 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2173 SourceLocation IdLoc, IdentifierInfo *Id,
2174 AttributeList *Attrs,
2175 SourceLocation EqualLoc, Expr *Val);
2176 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2178 ArrayRef<Decl *> Elements,
2179 Scope *S, AttributeList *Attr);
2181 DeclContext *getContainingDC(DeclContext *DC);
2183 /// Set the current declaration context until it gets popped.
2184 void PushDeclContext(Scope *S, DeclContext *DC);
2185 void PopDeclContext();
2187 /// EnterDeclaratorContext - Used when we must lookup names in the context
2188 /// of a declarator's nested name specifier.
2189 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2190 void ExitDeclaratorContext(Scope *S);
2192 /// Push the parameters of D, which must be a function, into scope.
2193 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2194 void ActOnExitFunctionContext();
2196 DeclContext *getFunctionLevelDeclContext();
2198 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2199 /// to the function decl for the function being parsed. If we're currently
2200 /// in a 'block', this returns the containing context.
2201 FunctionDecl *getCurFunctionDecl();
2203 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2204 /// the method decl for the method being parsed. If we're currently
2205 /// in a 'block', this returns the containing context.
2206 ObjCMethodDecl *getCurMethodDecl();
2208 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2209 /// or C function we're in, otherwise return null. If we're currently
2210 /// in a 'block', this returns the containing context.
2211 NamedDecl *getCurFunctionOrMethodDecl();
2213 /// Add this decl to the scope shadowed decl chains.
2214 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2216 /// \brief Make the given externally-produced declaration visible at the
2217 /// top level scope.
2219 /// \param D The externally-produced declaration to push.
2221 /// \param Name The name of the externally-produced declaration.
2222 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2224 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2225 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2226 /// true if 'D' belongs to the given declaration context.
2228 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2229 /// enclosing namespace set of the context, rather than contained
2230 /// directly within it.
2231 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2232 bool AllowInlineNamespace = false);
2234 /// Finds the scope corresponding to the given decl context, if it
2235 /// happens to be an enclosing scope. Otherwise return NULL.
2236 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2238 /// Subroutines of ActOnDeclarator().
2239 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2240 TypeSourceInfo *TInfo);
2241 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2243 /// \brief Describes the kind of merge to perform for availability
2244 /// attributes (including "deprecated", "unavailable", and "availability").
2245 enum AvailabilityMergeKind {
2246 /// \brief Don't merge availability attributes at all.
2248 /// \brief Merge availability attributes for a redeclaration, which requires
2251 /// \brief Merge availability attributes for an override, which requires
2252 /// an exact match or a weakening of constraints.
2254 /// \brief Merge availability attributes for an implementation of
2255 /// a protocol requirement.
2256 AMK_ProtocolImplementation,
2259 /// Attribute merging methods. Return true if a new attribute was added.
2260 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2261 IdentifierInfo *Platform,
2263 VersionTuple Introduced,
2264 VersionTuple Deprecated,
2265 VersionTuple Obsoleted,
2268 bool IsStrict, StringRef Replacement,
2269 AvailabilityMergeKind AMK,
2270 unsigned AttrSpellingListIndex);
2271 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2272 TypeVisibilityAttr::VisibilityType Vis,
2273 unsigned AttrSpellingListIndex);
2274 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2275 VisibilityAttr::VisibilityType Vis,
2276 unsigned AttrSpellingListIndex);
2277 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2278 unsigned AttrSpellingListIndex, StringRef Uuid);
2279 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2280 unsigned AttrSpellingListIndex);
2281 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2282 unsigned AttrSpellingListIndex);
2284 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2285 unsigned AttrSpellingListIndex,
2286 MSInheritanceAttr::Spelling SemanticSpelling);
2287 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2288 IdentifierInfo *Format, int FormatIdx,
2289 int FirstArg, unsigned AttrSpellingListIndex);
2290 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2291 unsigned AttrSpellingListIndex);
2292 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2293 IdentifierInfo *Ident,
2294 unsigned AttrSpellingListIndex);
2295 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2296 unsigned AttrSpellingListIndex);
2297 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2298 unsigned AttrSpellingListIndex);
2299 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2300 IdentifierInfo *Ident,
2301 unsigned AttrSpellingListIndex);
2302 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2303 unsigned AttrSpellingListIndex);
2305 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2306 AvailabilityMergeKind AMK = AMK_Redeclaration);
2307 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2308 LookupResult &OldDecls);
2309 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2310 bool MergeTypeWithOld);
2311 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2312 Scope *S, bool MergeTypeWithOld);
2313 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2314 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2315 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2316 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2317 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2318 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2320 // AssignmentAction - This is used by all the assignment diagnostic functions
2321 // to represent what is actually causing the operation
2322 enum AssignmentAction {
2330 AA_Passing_CFAudited
2333 /// C++ Overloading.
2335 /// This is a legitimate overload: the existing declarations are
2336 /// functions or function templates with different signatures.
2339 /// This is not an overload because the signature exactly matches
2340 /// an existing declaration.
2343 /// This is not an overload because the lookup results contain a
2347 OverloadKind CheckOverload(Scope *S,
2349 const LookupResult &OldDecls,
2350 NamedDecl *&OldDecl,
2351 bool IsForUsingDecl);
2352 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2353 bool ConsiderCudaAttrs = true);
2355 /// \brief Checks availability of the function depending on the current
2356 /// function context.Inside an unavailable function,unavailability is ignored.
2358 /// \returns true if \p FD is unavailable and current context is inside
2359 /// an available function, false otherwise.
2360 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2362 ImplicitConversionSequence
2363 TryImplicitConversion(Expr *From, QualType ToType,
2364 bool SuppressUserConversions,
2366 bool InOverloadResolution,
2368 bool AllowObjCWritebackConversion);
2370 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2371 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2372 bool IsComplexPromotion(QualType FromType, QualType ToType);
2373 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2374 bool InOverloadResolution,
2375 QualType& ConvertedType, bool &IncompatibleObjC);
2376 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2377 QualType& ConvertedType, bool &IncompatibleObjC);
2378 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2379 QualType &ConvertedType);
2380 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2381 QualType& ConvertedType);
2382 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2383 const FunctionProtoType *NewType,
2384 unsigned *ArgPos = nullptr);
2385 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2386 QualType FromType, QualType ToType);
2388 void maybeExtendBlockObject(ExprResult &E);
2389 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2390 bool CheckPointerConversion(Expr *From, QualType ToType,
2392 CXXCastPath& BasePath,
2393 bool IgnoreBaseAccess,
2394 bool Diagnose = true);
2395 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2396 bool InOverloadResolution,
2397 QualType &ConvertedType);
2398 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2400 CXXCastPath &BasePath,
2401 bool IgnoreBaseAccess);
2402 bool IsQualificationConversion(QualType FromType, QualType ToType,
2403 bool CStyle, bool &ObjCLifetimeConversion);
2404 bool IsFunctionConversion(QualType FromType, QualType ToType,
2405 QualType &ResultTy);
2406 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2407 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2409 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2410 const VarDecl *NRVOCandidate,
2411 QualType ResultType,
2413 bool AllowNRVO = true);
2415 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2417 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2418 SourceLocation EqualLoc,
2420 bool TopLevelOfInitList = false,
2421 bool AllowExplicit = false);
2422 ExprResult PerformObjectArgumentInitialization(Expr *From,
2423 NestedNameSpecifier *Qualifier,
2424 NamedDecl *FoundDecl,
2425 CXXMethodDecl *Method);
2427 ExprResult PerformContextuallyConvertToBool(Expr *From);
2428 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2430 /// Contexts in which a converted constant expression is required.
2432 CCEK_CaseValue, ///< Expression in a case label.
2433 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2434 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2435 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2436 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2438 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2439 llvm::APSInt &Value, CCEKind CCE);
2440 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2441 APValue &Value, CCEKind CCE);
2443 /// \brief Abstract base class used to perform a contextual implicit
2444 /// conversion from an expression to any type passing a filter.
2445 class ContextualImplicitConverter {
2448 bool SuppressConversion;
2450 ContextualImplicitConverter(bool Suppress = false,
2451 bool SuppressConversion = false)
2452 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2454 /// \brief Determine whether the specified type is a valid destination type
2455 /// for this conversion.
2456 virtual bool match(QualType T) = 0;
2458 /// \brief Emits a diagnostic complaining that the expression does not have
2459 /// integral or enumeration type.
2460 virtual SemaDiagnosticBuilder
2461 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2463 /// \brief Emits a diagnostic when the expression has incomplete class type.
2464 virtual SemaDiagnosticBuilder
2465 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2467 /// \brief Emits a diagnostic when the only matching conversion function
2469 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2470 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2472 /// \brief Emits a note for the explicit conversion function.
2473 virtual SemaDiagnosticBuilder
2474 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2476 /// \brief Emits a diagnostic when there are multiple possible conversion
2478 virtual SemaDiagnosticBuilder
2479 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2481 /// \brief Emits a note for one of the candidate conversions.
2482 virtual SemaDiagnosticBuilder
2483 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2485 /// \brief Emits a diagnostic when we picked a conversion function
2486 /// (for cases when we are not allowed to pick a conversion function).
2487 virtual SemaDiagnosticBuilder diagnoseConversion(
2488 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2490 virtual ~ContextualImplicitConverter() {}
2493 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2494 bool AllowScopedEnumerations;
2497 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2498 bool Suppress, bool SuppressConversion)
2499 : ContextualImplicitConverter(Suppress, SuppressConversion),
2500 AllowScopedEnumerations(AllowScopedEnumerations) {}
2502 /// Match an integral or (possibly scoped) enumeration type.
2503 bool match(QualType T) override;
2505 SemaDiagnosticBuilder
2506 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2507 return diagnoseNotInt(S, Loc, T);
2510 /// \brief Emits a diagnostic complaining that the expression does not have
2511 /// integral or enumeration type.
2512 virtual SemaDiagnosticBuilder
2513 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2516 /// Perform a contextual implicit conversion.
2517 ExprResult PerformContextualImplicitConversion(
2518 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2521 enum ObjCSubscriptKind {
2526 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2528 // Note that LK_String is intentionally after the other literals, as
2529 // this is used for diagnostics logic.
2530 enum ObjCLiteralKind {
2539 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2541 ExprResult PerformObjectMemberConversion(Expr *From,
2542 NestedNameSpecifier *Qualifier,
2543 NamedDecl *FoundDecl,
2546 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2547 // TODO: make this is a typesafe union.
2548 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2549 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2551 void AddOverloadCandidate(FunctionDecl *Function,
2552 DeclAccessPair FoundDecl,
2553 ArrayRef<Expr *> Args,
2554 OverloadCandidateSet &CandidateSet,
2555 bool SuppressUserConversions = false,
2556 bool PartialOverloading = false,
2557 bool AllowExplicit = false,
2558 ConversionSequenceList EarlyConversions = None);
2559 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2560 ArrayRef<Expr *> Args,
2561 OverloadCandidateSet &CandidateSet,
2562 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2563 bool SuppressUserConversions = false,
2564 bool PartialOverloading = false);
2565 void AddMethodCandidate(DeclAccessPair FoundDecl,
2566 QualType ObjectType,
2567 Expr::Classification ObjectClassification,
2568 ArrayRef<Expr *> Args,
2569 OverloadCandidateSet& CandidateSet,
2570 bool SuppressUserConversion = false);
2571 void AddMethodCandidate(CXXMethodDecl *Method,
2572 DeclAccessPair FoundDecl,
2573 CXXRecordDecl *ActingContext, QualType ObjectType,
2574 Expr::Classification ObjectClassification,
2575 ArrayRef<Expr *> Args,
2576 OverloadCandidateSet& CandidateSet,
2577 bool SuppressUserConversions = false,
2578 bool PartialOverloading = false,
2579 ConversionSequenceList EarlyConversions = None);
2580 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2581 DeclAccessPair FoundDecl,
2582 CXXRecordDecl *ActingContext,
2583 TemplateArgumentListInfo *ExplicitTemplateArgs,
2584 QualType ObjectType,
2585 Expr::Classification ObjectClassification,
2586 ArrayRef<Expr *> Args,
2587 OverloadCandidateSet& CandidateSet,
2588 bool SuppressUserConversions = false,
2589 bool PartialOverloading = false);
2590 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2591 DeclAccessPair FoundDecl,
2592 TemplateArgumentListInfo *ExplicitTemplateArgs,
2593 ArrayRef<Expr *> Args,
2594 OverloadCandidateSet& CandidateSet,
2595 bool SuppressUserConversions = false,
2596 bool PartialOverloading = false);
2597 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2598 ArrayRef<QualType> ParamTypes,
2599 ArrayRef<Expr *> Args,
2600 OverloadCandidateSet &CandidateSet,
2601 ConversionSequenceList &Conversions,
2602 bool SuppressUserConversions,
2603 CXXRecordDecl *ActingContext = nullptr,
2604 QualType ObjectType = QualType(),
2605 Expr::Classification
2606 ObjectClassification = {});
2607 void AddConversionCandidate(CXXConversionDecl *Conversion,
2608 DeclAccessPair FoundDecl,
2609 CXXRecordDecl *ActingContext,
2610 Expr *From, QualType ToType,
2611 OverloadCandidateSet& CandidateSet,
2612 bool AllowObjCConversionOnExplicit);
2613 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2614 DeclAccessPair FoundDecl,
2615 CXXRecordDecl *ActingContext,
2616 Expr *From, QualType ToType,
2617 OverloadCandidateSet &CandidateSet,
2618 bool AllowObjCConversionOnExplicit);
2619 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2620 DeclAccessPair FoundDecl,
2621 CXXRecordDecl *ActingContext,
2622 const FunctionProtoType *Proto,
2623 Expr *Object, ArrayRef<Expr *> Args,
2624 OverloadCandidateSet& CandidateSet);
2625 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2626 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2627 OverloadCandidateSet& CandidateSet,
2628 SourceRange OpRange = SourceRange());
2629 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2630 ArrayRef<Expr *> Args,
2631 OverloadCandidateSet& CandidateSet,
2632 bool IsAssignmentOperator = false,
2633 unsigned NumContextualBoolArguments = 0);
2634 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2635 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2636 OverloadCandidateSet& CandidateSet);
2637 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2639 ArrayRef<Expr *> Args,
2640 TemplateArgumentListInfo *ExplicitTemplateArgs,
2641 OverloadCandidateSet& CandidateSet,
2642 bool PartialOverloading = false);
2644 // Emit as a 'note' the specific overload candidate
2645 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2646 QualType DestType = QualType(),
2647 bool TakingAddress = false);
2649 // Emit as a series of 'note's all template and non-templates identified by
2650 // the expression Expr
2651 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2652 bool TakingAddress = false);
2654 /// Check the enable_if expressions on the given function. Returns the first
2655 /// failing attribute, or NULL if they were all successful.
2656 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2657 bool MissingImplicitThis = false);
2659 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2660 /// non-ArgDependent DiagnoseIfAttrs.
2662 /// Argument-dependent diagnose_if attributes should be checked each time a
2663 /// function is used as a direct callee of a function call.
2665 /// Returns true if any errors were emitted.
2666 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2667 const Expr *ThisArg,
2668 ArrayRef<const Expr *> Args,
2669 SourceLocation Loc);
2671 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2672 /// ArgDependent DiagnoseIfAttrs.
2674 /// Argument-independent diagnose_if attributes should be checked on every use
2677 /// Returns true if any errors were emitted.
2678 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2679 SourceLocation Loc);
2681 /// Returns whether the given function's address can be taken or not,
2682 /// optionally emitting a diagnostic if the address can't be taken.
2684 /// Returns false if taking the address of the function is illegal.
2685 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2686 bool Complain = false,
2687 SourceLocation Loc = SourceLocation());
2689 // [PossiblyAFunctionType] --> [Return]
2690 // NonFunctionType --> NonFunctionType
2692 // R (*)(A) --> R (A)
2693 // R (&)(A) --> R (A)
2694 // R (S::*)(A) --> R (A)
2695 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2698 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2699 QualType TargetType,
2701 DeclAccessPair &Found,
2702 bool *pHadMultipleCandidates = nullptr);
2705 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2706 DeclAccessPair &FoundResult);
2708 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2711 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2712 bool Complain = false,
2713 DeclAccessPair *Found = nullptr);
2715 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2716 ExprResult &SrcExpr,
2717 bool DoFunctionPointerConverion = false,
2718 bool Complain = false,
2719 SourceRange OpRangeForComplaining = SourceRange(),
2720 QualType DestTypeForComplaining = QualType(),
2721 unsigned DiagIDForComplaining = 0);
2724 Expr *FixOverloadedFunctionReference(Expr *E,
2725 DeclAccessPair FoundDecl,
2727 ExprResult FixOverloadedFunctionReference(ExprResult,
2728 DeclAccessPair FoundDecl,
2731 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2732 ArrayRef<Expr *> Args,
2733 OverloadCandidateSet &CandidateSet,
2734 bool PartialOverloading = false);
2736 // An enum used to represent the different possible results of building a
2737 // range-based for loop.
2738 enum ForRangeStatus {
2740 FRS_NoViableFunction,
2741 FRS_DiagnosticIssued
2744 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2745 SourceLocation RangeLoc,
2746 const DeclarationNameInfo &NameInfo,
2747 LookupResult &MemberLookup,
2748 OverloadCandidateSet *CandidateSet,
2749 Expr *Range, ExprResult *CallExpr);
2751 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2752 UnresolvedLookupExpr *ULE,
2753 SourceLocation LParenLoc,
2755 SourceLocation RParenLoc,
2757 bool AllowTypoCorrection=true,
2758 bool CalleesAddressIsTaken=false);
2760 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2761 MultiExprArg Args, SourceLocation RParenLoc,
2762 OverloadCandidateSet *CandidateSet,
2763 ExprResult *Result);
2765 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2766 UnaryOperatorKind Opc,
2767 const UnresolvedSetImpl &Fns,
2770 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2771 BinaryOperatorKind Opc,
2772 const UnresolvedSetImpl &Fns,
2773 Expr *LHS, Expr *RHS);
2775 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2776 SourceLocation RLoc,
2777 Expr *Base,Expr *Idx);
2780 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2781 SourceLocation LParenLoc,
2783 SourceLocation RParenLoc);
2785 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2787 SourceLocation RParenLoc);
2789 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2790 SourceLocation OpLoc,
2791 bool *NoArrowOperatorFound = nullptr);
2793 /// CheckCallReturnType - Checks that a call expression's return type is
2794 /// complete. Returns true on failure. The location passed in is the location
2795 /// that best represents the call.
2796 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2797 CallExpr *CE, FunctionDecl *FD);
2799 /// Helpers for dealing with blocks and functions.
2800 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2801 bool CheckParameterNames);
2802 void CheckCXXDefaultArguments(FunctionDecl *FD);
2803 void CheckExtraCXXDefaultArguments(Declarator &D);
2804 Scope *getNonFieldDeclScope(Scope *S);
2806 /// \name Name lookup
2808 /// These routines provide name lookup that is used during semantic
2809 /// analysis to resolve the various kinds of names (identifiers,
2810 /// overloaded operator names, constructor names, etc.) into zero or
2811 /// more declarations within a particular scope. The major entry
2812 /// points are LookupName, which performs unqualified name lookup,
2813 /// and LookupQualifiedName, which performs qualified name lookup.
2815 /// All name lookup is performed based on some specific criteria,
2816 /// which specify what names will be visible to name lookup and how
2817 /// far name lookup should work. These criteria are important both
2818 /// for capturing language semantics (certain lookups will ignore
2819 /// certain names, for example) and for performance, since name
2820 /// lookup is often a bottleneck in the compilation of C++. Name
2821 /// lookup criteria is specified via the LookupCriteria enumeration.
2823 /// The results of name lookup can vary based on the kind of name
2824 /// lookup performed, the current language, and the translation
2825 /// unit. In C, for example, name lookup will either return nothing
2826 /// (no entity found) or a single declaration. In C++, name lookup
2827 /// can additionally refer to a set of overloaded functions or
2828 /// result in an ambiguity. All of the possible results of name
2829 /// lookup are captured by the LookupResult class, which provides
2830 /// the ability to distinguish among them.
2833 /// @brief Describes the kind of name lookup to perform.
2834 enum LookupNameKind {
2835 /// Ordinary name lookup, which finds ordinary names (functions,
2836 /// variables, typedefs, etc.) in C and most kinds of names
2837 /// (functions, variables, members, types, etc.) in C++.
2838 LookupOrdinaryName = 0,
2839 /// Tag name lookup, which finds the names of enums, classes,
2840 /// structs, and unions.
2842 /// Label name lookup.
2844 /// Member name lookup, which finds the names of
2845 /// class/struct/union members.
2847 /// Look up of an operator name (e.g., operator+) for use with
2848 /// operator overloading. This lookup is similar to ordinary name
2849 /// lookup, but will ignore any declarations that are class members.
2851 /// Look up of a name that precedes the '::' scope resolution
2852 /// operator in C++. This lookup completely ignores operator, object,
2853 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2854 LookupNestedNameSpecifierName,
2855 /// Look up a namespace name within a C++ using directive or
2856 /// namespace alias definition, ignoring non-namespace names (C++
2857 /// [basic.lookup.udir]p1).
2858 LookupNamespaceName,
2859 /// Look up all declarations in a scope with the given name,
2860 /// including resolved using declarations. This is appropriate
2861 /// for checking redeclarations for a using declaration.
2862 LookupUsingDeclName,
2863 /// Look up an ordinary name that is going to be redeclared as a
2864 /// name with linkage. This lookup ignores any declarations that
2865 /// are outside of the current scope unless they have linkage. See
2866 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2867 LookupRedeclarationWithLinkage,
2868 /// Look up a friend of a local class. This lookup does not look
2869 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2870 LookupLocalFriendName,
2871 /// Look up the name of an Objective-C protocol.
2872 LookupObjCProtocolName,
2873 /// Look up implicit 'self' parameter of an objective-c method.
2874 LookupObjCImplicitSelfParam,
2875 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2876 LookupOMPReductionName,
2877 /// \brief Look up any declaration with any name.
2881 /// \brief Specifies whether (or how) name lookup is being performed for a
2882 /// redeclaration (vs. a reference).
2883 enum RedeclarationKind {
2884 /// \brief The lookup is a reference to this name that is not for the
2885 /// purpose of redeclaring the name.
2886 NotForRedeclaration = 0,
2887 /// \brief The lookup results will be used for redeclaration of a name,
2888 /// if an entity by that name already exists.
2892 /// \brief The possible outcomes of name lookup for a literal operator.
2893 enum LiteralOperatorLookupResult {
2894 /// \brief The lookup resulted in an error.
2896 /// \brief The lookup found a single 'cooked' literal operator, which
2897 /// expects a normal literal to be built and passed to it.
2899 /// \brief The lookup found a single 'raw' literal operator, which expects
2900 /// a string literal containing the spelling of the literal token.
2902 /// \brief The lookup found an overload set of literal operator templates,
2903 /// which expect the characters of the spelling of the literal token to be
2904 /// passed as a non-type template argument pack.
2906 /// \brief The lookup found an overload set of literal operator templates,
2907 /// which expect the character type and characters of the spelling of the
2908 /// string literal token to be passed as template arguments.
2912 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2913 CXXSpecialMember SM,
2920 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2921 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2922 TypoRecoveryCallback;
2925 bool CppLookupName(LookupResult &R, Scope *S);
2927 struct TypoExprState {
2928 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2929 TypoDiagnosticGenerator DiagHandler;
2930 TypoRecoveryCallback RecoveryHandler;
2932 TypoExprState(TypoExprState &&other) noexcept;
2933 TypoExprState &operator=(TypoExprState &&other) noexcept;
2936 /// \brief The set of unhandled TypoExprs and their associated state.
2937 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2939 /// \brief Creates a new TypoExpr AST node.
2940 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2941 TypoDiagnosticGenerator TDG,
2942 TypoRecoveryCallback TRC);
2944 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2946 // The boolean value will be true to indicate that the namespace was loaded
2947 // from an AST/PCH file, or false otherwise.
2948 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2950 /// \brief Whether we have already loaded known namespaces from an extenal
2952 bool LoadedExternalKnownNamespaces;
2954 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2955 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2956 /// should be skipped entirely.
2957 std::unique_ptr<TypoCorrectionConsumer>
2958 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2959 Sema::LookupNameKind LookupKind, Scope *S,
2961 std::unique_ptr<CorrectionCandidateCallback> CCC,
2962 DeclContext *MemberContext, bool EnteringContext,
2963 const ObjCObjectPointerType *OPT,
2964 bool ErrorRecovery);
2967 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2969 /// \brief Clears the state of the given TypoExpr.
2970 void clearDelayedTypo(TypoExpr *TE);
2972 /// \brief Look up a name, looking for a single declaration. Return
2973 /// null if the results were absent, ambiguous, or overloaded.
2975 /// It is preferable to use the elaborated form and explicitly handle
2976 /// ambiguity and overloaded.
2977 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2979 LookupNameKind NameKind,
2980 RedeclarationKind Redecl
2981 = NotForRedeclaration);
2982 bool LookupName(LookupResult &R, Scope *S,
2983 bool AllowBuiltinCreation = false);
2984 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2985 bool InUnqualifiedLookup = false);
2986 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2988 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2989 bool AllowBuiltinCreation = false,
2990 bool EnteringContext = false);
2991 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2992 RedeclarationKind Redecl
2993 = NotForRedeclaration);
2994 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2996 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2997 QualType T1, QualType T2,
2998 UnresolvedSetImpl &Functions);
3000 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3001 SourceLocation GnuLabelLoc = SourceLocation());
3003 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3004 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3005 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3007 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3008 bool RValueThis, unsigned ThisQuals);
3009 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3011 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3012 bool RValueThis, unsigned ThisQuals);
3013 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3015 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3016 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3017 ArrayRef<QualType> ArgTys,
3020 bool AllowStringTemplate);
3021 bool isKnownName(StringRef name);
3023 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3024 ArrayRef<Expr *> Args, ADLResult &Functions);
3026 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3027 VisibleDeclConsumer &Consumer,
3028 bool IncludeGlobalScope = true);
3029 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3030 VisibleDeclConsumer &Consumer,
3031 bool IncludeGlobalScope = true);
3033 enum CorrectTypoKind {
3034 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3035 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3038 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3039 Sema::LookupNameKind LookupKind,
3040 Scope *S, CXXScopeSpec *SS,
3041 std::unique_ptr<CorrectionCandidateCallback> CCC,
3042 CorrectTypoKind Mode,
3043 DeclContext *MemberContext = nullptr,
3044 bool EnteringContext = false,
3045 const ObjCObjectPointerType *OPT = nullptr,
3046 bool RecordFailure = true);
3048 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3049 Sema::LookupNameKind LookupKind, Scope *S,
3051 std::unique_ptr<CorrectionCandidateCallback> CCC,
3052 TypoDiagnosticGenerator TDG,
3053 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3054 DeclContext *MemberContext = nullptr,
3055 bool EnteringContext = false,
3056 const ObjCObjectPointerType *OPT = nullptr);
3058 /// \brief Process any TypoExprs in the given Expr and its children,
3059 /// generating diagnostics as appropriate and returning a new Expr if there
3060 /// were typos that were all successfully corrected and ExprError if one or
3061 /// more typos could not be corrected.
3063 /// \param E The Expr to check for TypoExprs.
3065 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3068 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3069 /// it is an acceptable/usable result from a single combination of typo
3070 /// corrections. As long as the filter returns ExprError, different
3071 /// combinations of corrections will be tried until all are exhausted.
3073 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3074 llvm::function_ref<ExprResult(Expr *)> Filter =
3075 [](Expr *E) -> ExprResult { return E; });
3078 CorrectDelayedTyposInExpr(Expr *E,
3079 llvm::function_ref<ExprResult(Expr *)> Filter) {
3080 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3084 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3085 llvm::function_ref<ExprResult(Expr *)> Filter =
3086 [](Expr *E) -> ExprResult { return E; }) {
3087 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3091 CorrectDelayedTyposInExpr(ExprResult ER,
3092 llvm::function_ref<ExprResult(Expr *)> Filter) {
3093 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3096 void diagnoseTypo(const TypoCorrection &Correction,
3097 const PartialDiagnostic &TypoDiag,
3098 bool ErrorRecovery = true);
3100 void diagnoseTypo(const TypoCorrection &Correction,
3101 const PartialDiagnostic &TypoDiag,
3102 const PartialDiagnostic &PrevNote,
3103 bool ErrorRecovery = true);
3105 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3106 ArrayRef<Expr *> Args,
3107 AssociatedNamespaceSet &AssociatedNamespaces,
3108 AssociatedClassSet &AssociatedClasses);
3110 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3111 bool ConsiderLinkage, bool AllowInlineNamespace);
3113 void DiagnoseAmbiguousLookup(LookupResult &Result);
3116 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3117 SourceLocation IdLoc,
3118 bool TypoCorrection = false);
3119 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3120 Scope *S, bool ForRedeclaration,
3121 SourceLocation Loc);
3122 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3124 void AddKnownFunctionAttributes(FunctionDecl *FD);
3126 // More parsing and symbol table subroutines.
3128 void ProcessPragmaWeak(Scope *S, Decl *D);
3129 // Decl attributes - this routine is the top level dispatcher.
3130 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3131 // Helper for delayed proccessing of attributes.
3132 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3133 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3134 bool IncludeCXX11Attributes = true);
3135 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3136 const AttributeList *AttrList);
3138 void checkUnusedDeclAttributes(Declarator &D);
3140 /// Determine if type T is a valid subject for a nonnull and similar
3141 /// attributes. By default, we look through references (the behavior used by
3142 /// nonnull), but if the second parameter is true, then we treat a reference
3144 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3146 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3147 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3148 const FunctionDecl *FD = nullptr);
3149 bool CheckNoReturnAttr(const AttributeList &attr);
3150 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3151 unsigned ArgNum, StringRef &Str,
3152 SourceLocation *ArgLocation = nullptr);
3153 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3154 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3155 bool checkMSInheritanceAttrOnDefinition(
3156 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3157 MSInheritanceAttr::Spelling SemanticSpelling);
3159 void CheckAlignasUnderalignment(Decl *D);
3161 /// Adjust the calling convention of a method to be the ABI default if it
3162 /// wasn't specified explicitly. This handles method types formed from
3163 /// function type typedefs and typename template arguments.
3164 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3165 SourceLocation Loc);
3167 // Check if there is an explicit attribute, but only look through parens.
3168 // The intent is to look for an attribute on the current declarator, but not
3169 // one that came from a typedef.
3170 bool hasExplicitCallingConv(QualType &T);
3172 /// Get the outermost AttributedType node that sets a calling convention.
3173 /// Valid types should not have multiple attributes with different CCs.
3174 const AttributedType *getCallingConvAttributedType(QualType T) const;
3176 /// Check whether a nullability type specifier can be added to the given
3179 /// \param type The type to which the nullability specifier will be
3180 /// added. On success, this type will be updated appropriately.
3182 /// \param nullability The nullability specifier to add.
3184 /// \param nullabilityLoc The location of the nullability specifier.
3186 /// \param isContextSensitive Whether this nullability specifier was
3187 /// written as a context-sensitive keyword (in an Objective-C
3188 /// method) or an Objective-C property attribute, rather than as an
3189 /// underscored type specifier.
3191 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3192 /// array type (e.g., because it will decay to a pointer).
3194 /// \returns true if nullability cannot be applied, false otherwise.
3195 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3196 SourceLocation nullabilityLoc,
3197 bool isContextSensitive,
3198 bool allowArrayTypes);
3200 /// \brief Stmt attributes - this routine is the top level dispatcher.
3201 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3204 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3205 ObjCMethodDecl *MethodDecl,
3206 bool IsProtocolMethodDecl);
3208 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3209 ObjCMethodDecl *Overridden,
3210 bool IsProtocolMethodDecl);
3212 /// WarnExactTypedMethods - This routine issues a warning if method
3213 /// implementation declaration matches exactly that of its declaration.
3214 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3215 ObjCMethodDecl *MethodDecl,
3216 bool IsProtocolMethodDecl);
3218 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3220 /// CheckImplementationIvars - This routine checks if the instance variables
3221 /// listed in the implelementation match those listed in the interface.
3222 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3223 ObjCIvarDecl **Fields, unsigned nIvars,
3224 SourceLocation Loc);
3226 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3227 /// remains unimplemented in the class or category \@implementation.
3228 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3229 ObjCContainerDecl* IDecl,
3230 bool IncompleteImpl = false);
3232 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3233 /// which must be implemented by this implementation.
3234 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3235 ObjCContainerDecl *CDecl,
3236 bool SynthesizeProperties);
3238 /// Diagnose any null-resettable synthesized setters.
3239 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3241 /// DefaultSynthesizeProperties - This routine default synthesizes all
3242 /// properties which must be synthesized in the class's \@implementation.
3243 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3244 ObjCInterfaceDecl *IDecl);
3245 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3247 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3248 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3249 /// declared in class 'IFace'.
3250 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3251 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3253 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3254 /// backs the property is not used in the property's accessor.
3255 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3256 const ObjCImplementationDecl *ImplD);
3258 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3259 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3260 /// It also returns ivar's property on success.
3261 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3262 const ObjCPropertyDecl *&PDecl) const;
3264 /// Called by ActOnProperty to handle \@property declarations in
3265 /// class extensions.
3266 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3267 SourceLocation AtLoc,
3268 SourceLocation LParenLoc,
3269 FieldDeclarator &FD,
3271 SourceLocation GetterNameLoc,
3273 SourceLocation SetterNameLoc,
3274 const bool isReadWrite,
3275 unsigned &Attributes,
3276 const unsigned AttributesAsWritten,
3278 TypeSourceInfo *TSI,
3279 tok::ObjCKeywordKind MethodImplKind);
3281 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3282 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3283 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3284 ObjCContainerDecl *CDecl,
3285 SourceLocation AtLoc,
3286 SourceLocation LParenLoc,
3287 FieldDeclarator &FD,
3289 SourceLocation GetterNameLoc,
3291 SourceLocation SetterNameLoc,
3292 const bool isReadWrite,
3293 const unsigned Attributes,
3294 const unsigned AttributesAsWritten,
3296 TypeSourceInfo *TSI,
3297 tok::ObjCKeywordKind MethodImplKind,
3298 DeclContext *lexicalDC = nullptr);
3300 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3301 /// warning) when atomic property has one but not the other user-declared
3302 /// setter or getter.
3303 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3304 ObjCInterfaceDecl* IDecl);
3306 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3308 void DiagnoseMissingDesignatedInitOverrides(
3309 const ObjCImplementationDecl *ImplD,
3310 const ObjCInterfaceDecl *IFD);
3312 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3314 enum MethodMatchStrategy {
3319 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3320 /// true, or false, accordingly.
3321 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3322 const ObjCMethodDecl *PrevMethod,
3323 MethodMatchStrategy strategy = MMS_strict);
3325 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3326 /// or protocol against those declared in their implementations.
3327 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3328 const SelectorSet &ClsMap,
3329 SelectorSet &InsMapSeen,
3330 SelectorSet &ClsMapSeen,
3331 ObjCImplDecl* IMPDecl,
3332 ObjCContainerDecl* IDecl,
3333 bool &IncompleteImpl,
3334 bool ImmediateClass,
3335 bool WarnCategoryMethodImpl=false);
3337 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3338 /// category matches with those implemented in its primary class and
3339 /// warns each time an exact match is found.
3340 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3342 /// \brief Add the given method to the list of globally-known methods.
3343 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3346 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3347 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3348 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3350 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3351 /// optionally warns if there are multiple signatures.
3352 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3353 bool receiverIdOrClass,
3357 /// \brief - Returns instance or factory methods in global method pool for
3358 /// given selector. It checks the desired kind first, if none is found, and
3359 /// parameter checkTheOther is set, it then checks the other kind. If no such
3360 /// method or only one method is found, function returns false; otherwise, it
3363 CollectMultipleMethodsInGlobalPool(Selector Sel,
3364 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3365 bool InstanceFirst, bool CheckTheOther,
3366 const ObjCObjectType *TypeBound = nullptr);
3369 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3370 SourceRange R, bool receiverIdOrClass,
3371 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3374 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3375 Selector Sel, SourceRange R,
3376 bool receiverIdOrClass);
3379 /// \brief - Returns a selector which best matches given argument list or
3380 /// nullptr if none could be found
3381 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3383 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3386 /// \brief Record the typo correction failure and return an empty correction.
3387 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3388 bool RecordFailure = true) {
3390 TypoCorrectionFailures[Typo].insert(TypoLoc);
3391 return TypoCorrection();
3395 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3396 /// unit are added to a global pool. This allows us to efficiently associate
3397 /// a selector with a method declaraation for purposes of typechecking
3398 /// messages sent to "id" (where the class of the object is unknown).
3399 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3400 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3403 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3404 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3405 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3408 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3410 void AddAnyMethodToGlobalPool(Decl *D);
3412 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3413 /// there are multiple signatures.
3414 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3415 bool receiverIdOrClass=false) {
3416 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3420 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3421 /// there are multiple signatures.
3422 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3423 bool receiverIdOrClass=false) {
3424 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3428 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3429 QualType ObjectType=QualType());
3430 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3432 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3434 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3436 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3437 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3439 //===--------------------------------------------------------------------===//
3440 // Statement Parsing Callbacks: SemaStmt.cpp.
3444 FullExprArg() : E(nullptr) { }
3445 FullExprArg(Sema &actions) : E(nullptr) { }
3447 ExprResult release() {
3451 Expr *get() const { return E; }
3453 Expr *operator->() {
3458 // FIXME: No need to make the entire Sema class a friend when it's just
3459 // Sema::MakeFullExpr that needs access to the constructor below.
3462 explicit FullExprArg(Expr *expr) : E(expr) {}
3467 FullExprArg MakeFullExpr(Expr *Arg) {
3468 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3470 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3471 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3473 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3475 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3476 /*DiscardedValue*/ true);
3477 return FullExprArg(FE.get());
3480 StmtResult ActOnExprStmt(ExprResult Arg);
3481 StmtResult ActOnExprStmtError();
3483 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3484 bool HasLeadingEmptyMacro = false);
3486 void ActOnStartOfCompoundStmt();
3487 void ActOnFinishOfCompoundStmt();
3488 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3489 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3491 /// \brief A RAII object to enter scope of a compound statement.
3492 class CompoundScopeRAII {
3494 CompoundScopeRAII(Sema &S): S(S) {
3495 S.ActOnStartOfCompoundStmt();
3498 ~CompoundScopeRAII() {
3499 S.ActOnFinishOfCompoundStmt();
3506 /// An RAII helper that pops function a function scope on exit.
3507 struct FunctionScopeRAII {
3510 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3511 ~FunctionScopeRAII() {
3513 S.PopFunctionScopeInfo();
3515 void disable() { Active = false; }
3518 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3519 SourceLocation StartLoc,
3520 SourceLocation EndLoc);
3521 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3522 StmtResult ActOnForEachLValueExpr(Expr *E);
3523 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3524 SourceLocation DotDotDotLoc, Expr *RHSVal,
3525 SourceLocation ColonLoc);
3526 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3528 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3529 SourceLocation ColonLoc,
3530 Stmt *SubStmt, Scope *CurScope);
3531 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3532 SourceLocation ColonLoc, Stmt *SubStmt);
3534 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3535 ArrayRef<const Attr*> Attrs,
3538 class ConditionResult;
3539 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3541 ConditionResult Cond, Stmt *ThenVal,
3542 SourceLocation ElseLoc, Stmt *ElseVal);
3543 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3545 ConditionResult Cond, Stmt *ThenVal,
3546 SourceLocation ElseLoc, Stmt *ElseVal);
3547 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3549 ConditionResult Cond);
3550 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3551 Stmt *Switch, Stmt *Body);
3552 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3554 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3555 SourceLocation WhileLoc, SourceLocation CondLParen,
3556 Expr *Cond, SourceLocation CondRParen);
3558 StmtResult ActOnForStmt(SourceLocation ForLoc,
3559 SourceLocation LParenLoc,
3561 ConditionResult Second,
3563 SourceLocation RParenLoc,
3565 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3567 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3568 Stmt *First, Expr *collection,
3569 SourceLocation RParenLoc);
3570 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3572 enum BuildForRangeKind {
3573 /// Initial building of a for-range statement.
3575 /// Instantiation or recovery rebuild of a for-range statement. Don't
3576 /// attempt any typo-correction.
3578 /// Determining whether a for-range statement could be built. Avoid any
3579 /// unnecessary or irreversible actions.
3583 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3584 SourceLocation CoawaitLoc,
3586 SourceLocation ColonLoc, Expr *Collection,
3587 SourceLocation RParenLoc,
3588 BuildForRangeKind Kind);
3589 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3590 SourceLocation CoawaitLoc,
3591 SourceLocation ColonLoc,
3592 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3593 Expr *Cond, Expr *Inc,
3595 SourceLocation RParenLoc,
3596 BuildForRangeKind Kind);
3597 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3599 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3600 SourceLocation LabelLoc,
3601 LabelDecl *TheDecl);
3602 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3603 SourceLocation StarLoc,
3605 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3606 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3608 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3609 CapturedRegionKind Kind, unsigned NumParams);
3610 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3611 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3612 CapturedRegionKind Kind,
3613 ArrayRef<CapturedParamNameType> Params);
3614 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3615 void ActOnCapturedRegionError();
3616 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3618 unsigned NumParams);
3619 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3620 bool AllowParamOrMoveConstructible);
3621 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3622 bool AllowParamOrMoveConstructible);
3624 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3626 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3627 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3629 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3630 bool IsVolatile, unsigned NumOutputs,
3631 unsigned NumInputs, IdentifierInfo **Names,
3632 MultiExprArg Constraints, MultiExprArg Exprs,
3633 Expr *AsmString, MultiExprArg Clobbers,
3634 SourceLocation RParenLoc);
3636 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3637 SourceLocation TemplateKWLoc,
3639 llvm::InlineAsmIdentifierInfo &Info,
3640 bool IsUnevaluatedContext);
3641 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3642 unsigned &Offset, SourceLocation AsmLoc);
3643 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3644 llvm::InlineAsmIdentifierInfo &Info,
3645 SourceLocation AsmLoc);
3646 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3647 ArrayRef<Token> AsmToks,
3648 StringRef AsmString,
3649 unsigned NumOutputs, unsigned NumInputs,
3650 ArrayRef<StringRef> Constraints,
3651 ArrayRef<StringRef> Clobbers,
3652 ArrayRef<Expr*> Exprs,
3653 SourceLocation EndLoc);
3654 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3655 SourceLocation Location,
3658 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3659 SourceLocation StartLoc,
3660 SourceLocation IdLoc, IdentifierInfo *Id,
3661 bool Invalid = false);
3663 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3665 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3666 Decl *Parm, Stmt *Body);
3668 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3670 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3671 MultiStmtArg Catch, Stmt *Finally);
3673 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3674 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3676 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3678 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3682 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3684 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3685 SourceLocation StartLoc,
3686 SourceLocation IdLoc,
3687 IdentifierInfo *Id);
3689 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3691 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3692 Decl *ExDecl, Stmt *HandlerBlock);
3693 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3694 ArrayRef<Stmt *> Handlers);
3696 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3697 SourceLocation TryLoc, Stmt *TryBlock,
3699 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3702 void ActOnStartSEHFinallyBlock();
3703 void ActOnAbortSEHFinallyBlock();
3704 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3705 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3707 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3709 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3711 /// \brief If it's a file scoped decl that must warn if not used, keep track
3713 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3715 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3716 /// whose result is unused, warn.
3717 void DiagnoseUnusedExprResult(const Stmt *S);
3718 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3719 void DiagnoseUnusedDecl(const NamedDecl *ND);
3721 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3722 /// statement as a \p Body, and it is located on the same line.
3724 /// This helps prevent bugs due to typos, such as:
3727 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3731 /// Warn if a for/while loop statement \p S, which is followed by
3732 /// \p PossibleBody, has a suspicious null statement as a body.
3733 void DiagnoseEmptyLoopBody(const Stmt *S,
3734 const Stmt *PossibleBody);
3736 /// Warn if a value is moved to itself.
3737 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3738 SourceLocation OpLoc);
3740 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3742 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3743 SourceLocation Loc);
3745 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3746 return DelayedDiagnostics.push(pool);
3748 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3750 typedef ProcessingContextState ParsingClassState;
3751 ParsingClassState PushParsingClass() {
3752 return DelayedDiagnostics.pushUndelayed();
3754 void PopParsingClass(ParsingClassState state) {
3755 DelayedDiagnostics.popUndelayed(state);
3758 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3760 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3761 StringRef Message, SourceLocation Loc,
3762 const ObjCInterfaceDecl *UnknownObjCClass,
3763 const ObjCPropertyDecl *ObjCProperty,
3764 bool ObjCPropertyAccess);
3766 bool makeUnavailableInSystemHeader(SourceLocation loc,
3767 UnavailableAttr::ImplicitReason reason);
3769 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3770 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3772 //===--------------------------------------------------------------------===//
3773 // Expression Parsing Callbacks: SemaExpr.cpp.
3775 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3776 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3777 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3778 bool ObjCPropertyAccess=false);
3779 void NoteDeletedFunction(FunctionDecl *FD);
3780 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3781 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3782 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3783 ObjCMethodDecl *Getter,
3784 SourceLocation Loc);
3785 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3786 ArrayRef<Expr *> Args);
3788 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3789 Decl *LambdaContextDecl = nullptr,
3790 bool IsDecltype = false);
3791 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3792 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3793 ReuseLambdaContextDecl_t,
3794 bool IsDecltype = false);
3795 void PopExpressionEvaluationContext();
3797 void DiscardCleanupsInEvaluationContext();
3799 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3800 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3802 ExprResult ActOnConstantExpression(ExprResult Res);
3804 // Functions for marking a declaration referenced. These functions also
3805 // contain the relevant logic for marking if a reference to a function or
3806 // variable is an odr-use (in the C++11 sense). There are separate variants
3807 // for expressions referring to a decl; these exist because odr-use marking
3808 // needs to be delayed for some constant variables when we build one of the
3809 // named expressions.
3811 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3812 // should usually be true. This only needs to be set to false if the lack of
3813 // odr-use cannot be determined from the current context (for instance,
3814 // because the name denotes a virtual function and was written without an
3815 // explicit nested-name-specifier).
3816 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3817 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3818 bool MightBeOdrUse = true);
3819 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3820 void MarkDeclRefReferenced(DeclRefExpr *E);
3821 void MarkMemberReferenced(MemberExpr *E);
3823 void UpdateMarkingForLValueToRValue(Expr *E);
3824 void CleanupVarDeclMarking();
3826 enum TryCaptureKind {
3827 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3830 /// \brief Try to capture the given variable.
3832 /// \param Var The variable to capture.
3834 /// \param Loc The location at which the capture occurs.
3836 /// \param Kind The kind of capture, which may be implicit (for either a
3837 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3839 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3840 /// an explicit lambda capture.
3842 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3843 /// captures or diagnose errors. If false, this routine merely check whether
3844 /// the capture can occur without performing the capture itself or complaining
3845 /// if the variable cannot be captured.
3847 /// \param CaptureType Will be set to the type of the field used to capture
3848 /// this variable in the innermost block or lambda. Only valid when the
3849 /// variable can be captured.
3851 /// \param DeclRefType Will be set to the type of a reference to the capture
3852 /// from within the current scope. Only valid when the variable can be
3855 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3856 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3857 /// This is useful when enclosing lambdas must speculatively capture
3858 /// variables that may or may not be used in certain specializations of
3859 /// a nested generic lambda.
3861 /// \returns true if an error occurred (i.e., the variable cannot be
3862 /// captured) and false if the capture succeeded.
3863 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3864 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3865 QualType &CaptureType,
3866 QualType &DeclRefType,
3867 const unsigned *const FunctionScopeIndexToStopAt);
3869 /// \brief Try to capture the given variable.
3870 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3871 TryCaptureKind Kind = TryCapture_Implicit,
3872 SourceLocation EllipsisLoc = SourceLocation());
3874 /// \brief Checks if the variable must be captured.
3875 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3877 /// \brief Given a variable, determine the type that a reference to that
3878 /// variable will have in the given scope.
3879 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3881 /// Mark all of the declarations referenced within a particular AST node as
3882 /// referenced. Used when template instantiation instantiates a non-dependent
3883 /// type -- entities referenced by the type are now referenced.
3884 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3885 void MarkDeclarationsReferencedInExpr(Expr *E,
3886 bool SkipLocalVariables = false);
3888 /// \brief Try to recover by turning the given expression into a
3889 /// call. Returns true if recovery was attempted or an error was
3890 /// emitted; this may also leave the ExprResult invalid.
3891 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3892 bool ForceComplain = false,
3893 bool (*IsPlausibleResult)(QualType) = nullptr);
3895 /// \brief Figure out if an expression could be turned into a call.
3896 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3897 UnresolvedSetImpl &NonTemplateOverloads);
3899 /// \brief Conditionally issue a diagnostic based on the current
3900 /// evaluation context.
3902 /// \param Statement If Statement is non-null, delay reporting the
3903 /// diagnostic until the function body is parsed, and then do a basic
3904 /// reachability analysis to determine if the statement is reachable.
3905 /// If it is unreachable, the diagnostic will not be emitted.
3906 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3907 const PartialDiagnostic &PD);
3909 // Primary Expressions.
3910 SourceRange getExprRange(Expr *E) const;
3912 ExprResult ActOnIdExpression(
3913 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3914 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3915 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3916 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3918 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3919 TemplateArgumentListInfo &Buffer,
3920 DeclarationNameInfo &NameInfo,
3921 const TemplateArgumentListInfo *&TemplateArgs);
3924 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3925 std::unique_ptr<CorrectionCandidateCallback> CCC,
3926 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3927 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3929 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3931 bool AllowBuiltinCreation=false);
3933 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3934 SourceLocation TemplateKWLoc,
3935 const DeclarationNameInfo &NameInfo,
3936 bool isAddressOfOperand,
3937 const TemplateArgumentListInfo *TemplateArgs);
3939 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3942 const CXXScopeSpec *SS = nullptr);
3944 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3945 const DeclarationNameInfo &NameInfo,
3946 const CXXScopeSpec *SS = nullptr,
3947 NamedDecl *FoundD = nullptr,
3948 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3950 BuildAnonymousStructUnionMemberReference(
3951 const CXXScopeSpec &SS,
3952 SourceLocation nameLoc,
3953 IndirectFieldDecl *indirectField,
3954 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3955 Expr *baseObjectExpr = nullptr,
3956 SourceLocation opLoc = SourceLocation());
3958 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3959 SourceLocation TemplateKWLoc,
3961 const TemplateArgumentListInfo *TemplateArgs,
3963 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3964 SourceLocation TemplateKWLoc,
3966 const TemplateArgumentListInfo *TemplateArgs,
3967 bool IsDefiniteInstance,
3969 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3970 const LookupResult &R,
3971 bool HasTrailingLParen);
3974 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3975 const DeclarationNameInfo &NameInfo,
3976 bool IsAddressOfOperand, const Scope *S,
3977 TypeSourceInfo **RecoveryTSI = nullptr);
3979 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3980 SourceLocation TemplateKWLoc,
3981 const DeclarationNameInfo &NameInfo,
3982 const TemplateArgumentListInfo *TemplateArgs);
3984 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3987 bool AcceptInvalidDecl = false);
3988 ExprResult BuildDeclarationNameExpr(
3989 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3990 NamedDecl *FoundD = nullptr,
3991 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3992 bool AcceptInvalidDecl = false);
3994 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3995 DeclarationNameInfo &SuffixInfo,
3996 ArrayRef<Expr *> Args,
3997 SourceLocation LitEndLoc,
3998 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4000 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4001 PredefinedExpr::IdentType IT);
4002 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4003 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4005 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4007 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4008 ExprResult ActOnCharacterConstant(const Token &Tok,
4009 Scope *UDLScope = nullptr);
4010 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4011 ExprResult ActOnParenListExpr(SourceLocation L,
4015 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4016 /// fragments (e.g. "foo" "bar" L"baz").
4017 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4018 Scope *UDLScope = nullptr);
4020 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4021 SourceLocation DefaultLoc,
4022 SourceLocation RParenLoc,
4023 Expr *ControllingExpr,
4024 ArrayRef<ParsedType> ArgTypes,
4025 ArrayRef<Expr *> ArgExprs);
4026 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4027 SourceLocation DefaultLoc,
4028 SourceLocation RParenLoc,
4029 Expr *ControllingExpr,
4030 ArrayRef<TypeSourceInfo *> Types,
4031 ArrayRef<Expr *> Exprs);
4033 // Binary/Unary Operators. 'Tok' is the token for the operator.
4034 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4036 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4037 UnaryOperatorKind Opc, Expr *Input);
4038 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4039 tok::TokenKind Op, Expr *Input);
4041 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4043 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4044 SourceLocation OpLoc,
4045 UnaryExprOrTypeTrait ExprKind,
4047 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4048 UnaryExprOrTypeTrait ExprKind);
4050 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4051 UnaryExprOrTypeTrait ExprKind,
4052 bool IsType, void *TyOrEx,
4053 SourceRange ArgRange);
4055 ExprResult CheckPlaceholderExpr(Expr *E);
4056 bool CheckVecStepExpr(Expr *E);
4058 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4059 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4060 SourceRange ExprRange,
4061 UnaryExprOrTypeTrait ExprKind);
4062 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4063 SourceLocation OpLoc,
4064 IdentifierInfo &Name,
4065 SourceLocation NameLoc,
4066 SourceLocation RParenLoc);
4067 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4068 tok::TokenKind Kind, Expr *Input);
4070 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4071 Expr *Idx, SourceLocation RLoc);
4072 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4073 Expr *Idx, SourceLocation RLoc);
4074 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4075 Expr *LowerBound, SourceLocation ColonLoc,
4076 Expr *Length, SourceLocation RBLoc);
4078 // This struct is for use by ActOnMemberAccess to allow
4079 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4080 // changing the access operator from a '.' to a '->' (to see if that is the
4081 // change needed to fix an error about an unknown member, e.g. when the class
4082 // defines a custom operator->).
4083 struct ActOnMemberAccessExtraArgs {
4089 ExprResult BuildMemberReferenceExpr(
4090 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4091 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4092 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4093 const TemplateArgumentListInfo *TemplateArgs,
4095 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4098 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4099 bool IsArrow, const CXXScopeSpec &SS,
4100 SourceLocation TemplateKWLoc,
4101 NamedDecl *FirstQualifierInScope, LookupResult &R,
4102 const TemplateArgumentListInfo *TemplateArgs,
4104 bool SuppressQualifierCheck = false,
4105 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4107 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4108 SourceLocation OpLoc,
4109 const CXXScopeSpec &SS, FieldDecl *Field,
4110 DeclAccessPair FoundDecl,
4111 const DeclarationNameInfo &MemberNameInfo);
4113 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4115 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4116 const CXXScopeSpec &SS,
4117 const LookupResult &R);
4119 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4120 bool IsArrow, SourceLocation OpLoc,
4121 const CXXScopeSpec &SS,
4122 SourceLocation TemplateKWLoc,
4123 NamedDecl *FirstQualifierInScope,
4124 const DeclarationNameInfo &NameInfo,
4125 const TemplateArgumentListInfo *TemplateArgs);
4127 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4128 SourceLocation OpLoc,
4129 tok::TokenKind OpKind,
4131 SourceLocation TemplateKWLoc,
4132 UnqualifiedId &Member,
4135 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4136 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4137 FunctionDecl *FDecl,
4138 const FunctionProtoType *Proto,
4139 ArrayRef<Expr *> Args,
4140 SourceLocation RParenLoc,
4141 bool ExecConfig = false);
4142 void CheckStaticArrayArgument(SourceLocation CallLoc,
4144 const Expr *ArgExpr);
4146 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4147 /// This provides the location of the left/right parens and a list of comma
4149 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4150 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4151 Expr *ExecConfig = nullptr,
4152 bool IsExecConfig = false);
4153 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4154 SourceLocation LParenLoc,
4155 ArrayRef<Expr *> Arg,
4156 SourceLocation RParenLoc,
4157 Expr *Config = nullptr,
4158 bool IsExecConfig = false);
4160 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4161 MultiExprArg ExecConfig,
4162 SourceLocation GGGLoc);
4164 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4165 Declarator &D, ParsedType &Ty,
4166 SourceLocation RParenLoc, Expr *CastExpr);
4167 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4169 SourceLocation RParenLoc,
4171 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4173 /// \brief Build an altivec or OpenCL literal.
4174 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4175 SourceLocation RParenLoc, Expr *E,
4176 TypeSourceInfo *TInfo);
4178 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4180 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4182 SourceLocation RParenLoc,
4185 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4186 TypeSourceInfo *TInfo,
4187 SourceLocation RParenLoc,
4190 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4191 MultiExprArg InitArgList,
4192 SourceLocation RBraceLoc);
4194 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4200 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4203 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4204 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4205 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4206 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4207 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4208 Expr *LHSExpr, Expr *RHSExpr);
4210 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4212 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4213 /// in the case of a the GNU conditional expr extension.
4214 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4215 SourceLocation ColonLoc,
4216 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4218 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4219 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4220 LabelDecl *TheDecl);
4222 void ActOnStartStmtExpr();
4223 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4224 SourceLocation RPLoc); // "({..})"
4225 void ActOnStmtExprError();
4227 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4228 struct OffsetOfComponent {
4229 SourceLocation LocStart, LocEnd;
4230 bool isBrackets; // true if [expr], false if .ident
4232 IdentifierInfo *IdentInfo;
4237 /// __builtin_offsetof(type, a.b[123][456].c)
4238 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4239 TypeSourceInfo *TInfo,
4240 ArrayRef<OffsetOfComponent> Components,
4241 SourceLocation RParenLoc);
4242 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4243 SourceLocation BuiltinLoc,
4244 SourceLocation TypeLoc,
4245 ParsedType ParsedArgTy,
4246 ArrayRef<OffsetOfComponent> Components,
4247 SourceLocation RParenLoc);
4249 // __builtin_choose_expr(constExpr, expr1, expr2)
4250 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4251 Expr *CondExpr, Expr *LHSExpr,
4252 Expr *RHSExpr, SourceLocation RPLoc);
4254 // __builtin_va_arg(expr, type)
4255 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4256 SourceLocation RPLoc);
4257 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4258 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4261 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4263 bool CheckCaseExpression(Expr *E);
4265 /// \brief Describes the result of an "if-exists" condition check.
4266 enum IfExistsResult {
4267 /// \brief The symbol exists.
4270 /// \brief The symbol does not exist.
4273 /// \brief The name is a dependent name, so the results will differ
4274 /// from one instantiation to the next.
4277 /// \brief An error occurred.
4282 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4283 const DeclarationNameInfo &TargetNameInfo);
4286 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4287 bool IsIfExists, CXXScopeSpec &SS,
4288 UnqualifiedId &Name);
4290 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4292 NestedNameSpecifierLoc QualifierLoc,
4293 DeclarationNameInfo NameInfo,
4295 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4297 CXXScopeSpec &SS, UnqualifiedId &Name,
4300 //===------------------------- "Block" Extension ------------------------===//
4302 /// ActOnBlockStart - This callback is invoked when a block literal is
4304 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4306 /// ActOnBlockArguments - This callback allows processing of block arguments.
4307 /// If there are no arguments, this is still invoked.
4308 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4311 /// ActOnBlockError - If there is an error parsing a block, this callback
4312 /// is invoked to pop the information about the block from the action impl.
4313 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4315 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4316 /// literal was successfully completed. ^(int x){...}
4317 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4320 //===---------------------------- Clang Extensions ----------------------===//
4322 /// __builtin_convertvector(...)
4323 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4324 SourceLocation BuiltinLoc,
4325 SourceLocation RParenLoc);
4327 //===---------------------------- OpenCL Features -----------------------===//
4329 /// __builtin_astype(...)
4330 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4331 SourceLocation BuiltinLoc,
4332 SourceLocation RParenLoc);
4334 //===---------------------------- C++ Features --------------------------===//
4336 // Act on C++ namespaces
4337 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4338 SourceLocation NamespaceLoc,
4339 SourceLocation IdentLoc,
4340 IdentifierInfo *Ident,
4341 SourceLocation LBrace,
4342 AttributeList *AttrList,
4343 UsingDirectiveDecl * &UsingDecl);
4344 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4346 NamespaceDecl *getStdNamespace() const;
4347 NamespaceDecl *getOrCreateStdNamespace();
4349 NamespaceDecl *lookupStdExperimentalNamespace();
4351 CXXRecordDecl *getStdBadAlloc() const;
4352 EnumDecl *getStdAlignValT() const;
4354 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4355 /// it is and Element is not NULL, assigns the element type to Element.
4356 bool isStdInitializerList(QualType Ty, QualType *Element);
4358 /// \brief Looks for the std::initializer_list template and instantiates it
4359 /// with Element, or emits an error if it's not found.
4361 /// \returns The instantiated template, or null on error.
4362 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4364 /// \brief Determine whether Ctor is an initializer-list constructor, as
4365 /// defined in [dcl.init.list]p2.
4366 bool isInitListConstructor(const FunctionDecl *Ctor);
4368 Decl *ActOnUsingDirective(Scope *CurScope,
4369 SourceLocation UsingLoc,
4370 SourceLocation NamespcLoc,
4372 SourceLocation IdentLoc,
4373 IdentifierInfo *NamespcName,
4374 AttributeList *AttrList);
4376 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4378 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4379 SourceLocation NamespaceLoc,
4380 SourceLocation AliasLoc,
4381 IdentifierInfo *Alias,
4383 SourceLocation IdentLoc,
4384 IdentifierInfo *Ident);
4386 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4387 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4388 const LookupResult &PreviousDecls,
4389 UsingShadowDecl *&PrevShadow);
4390 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4392 UsingShadowDecl *PrevDecl);
4394 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4395 bool HasTypenameKeyword,
4396 const CXXScopeSpec &SS,
4397 SourceLocation NameLoc,
4398 const LookupResult &Previous);
4399 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4401 const CXXScopeSpec &SS,
4402 const DeclarationNameInfo &NameInfo,
4403 SourceLocation NameLoc);
4405 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4406 SourceLocation UsingLoc,
4407 bool HasTypenameKeyword,
4408 SourceLocation TypenameLoc,
4410 DeclarationNameInfo NameInfo,
4411 SourceLocation EllipsisLoc,
4412 AttributeList *AttrList,
4413 bool IsInstantiation);
4414 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4415 ArrayRef<NamedDecl *> Expansions);
4417 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4419 /// Given a derived-class using shadow declaration for a constructor and the
4420 /// correspnding base class constructor, find or create the implicit
4421 /// synthesized derived class constructor to use for this initialization.
4422 CXXConstructorDecl *
4423 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4424 ConstructorUsingShadowDecl *DerivedShadow);
4426 Decl *ActOnUsingDeclaration(Scope *CurScope,
4428 SourceLocation UsingLoc,
4429 SourceLocation TypenameLoc,
4431 UnqualifiedId &Name,
4432 SourceLocation EllipsisLoc,
4433 AttributeList *AttrList);
4434 Decl *ActOnAliasDeclaration(Scope *CurScope,
4436 MultiTemplateParamsArg TemplateParams,
4437 SourceLocation UsingLoc,
4438 UnqualifiedId &Name,
4439 AttributeList *AttrList,
4441 Decl *DeclFromDeclSpec);
4443 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4444 /// including handling of its default argument expressions.
4446 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4448 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4449 NamedDecl *FoundDecl,
4450 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4451 bool HadMultipleCandidates, bool IsListInitialization,
4452 bool IsStdInitListInitialization,
4453 bool RequiresZeroInit, unsigned ConstructKind,
4454 SourceRange ParenRange);
4456 /// Build a CXXConstructExpr whose constructor has already been resolved if
4457 /// it denotes an inherited constructor.
4459 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4460 CXXConstructorDecl *Constructor, bool Elidable,
4462 bool HadMultipleCandidates, bool IsListInitialization,
4463 bool IsStdInitListInitialization,
4464 bool RequiresZeroInit, unsigned ConstructKind,
4465 SourceRange ParenRange);
4467 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4468 // the constructor can be elidable?
4470 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4471 NamedDecl *FoundDecl,
4472 CXXConstructorDecl *Constructor, bool Elidable,
4473 MultiExprArg Exprs, bool HadMultipleCandidates,
4474 bool IsListInitialization,
4475 bool IsStdInitListInitialization, bool RequiresZeroInit,
4476 unsigned ConstructKind, SourceRange ParenRange);
4478 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4481 /// Instantiate or parse a C++ default argument expression as necessary.
4482 /// Return true on error.
4483 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4484 ParmVarDecl *Param);
4486 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4487 /// the default expr if needed.
4488 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4490 ParmVarDecl *Param);
4492 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4493 /// constructed variable.
4494 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4496 /// \brief Helper class that collects exception specifications for
4497 /// implicitly-declared special member functions.
4498 class ImplicitExceptionSpecification {
4499 // Pointer to allow copying
4501 // We order exception specifications thus:
4502 // noexcept is the most restrictive, but is only used in C++11.
4503 // throw() comes next.
4504 // Then a throw(collected exceptions)
4505 // Finally no specification, which is expressed as noexcept(false).
4506 // throw(...) is used instead if any called function uses it.
4507 ExceptionSpecificationType ComputedEST;
4508 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4509 SmallVector<QualType, 4> Exceptions;
4511 void ClearExceptions() {
4512 ExceptionsSeen.clear();
4517 explicit ImplicitExceptionSpecification(Sema &Self)
4518 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4519 if (!Self.getLangOpts().CPlusPlus11)
4520 ComputedEST = EST_DynamicNone;
4523 /// \brief Get the computed exception specification type.
4524 ExceptionSpecificationType getExceptionSpecType() const {
4525 assert(ComputedEST != EST_ComputedNoexcept &&
4526 "noexcept(expr) should not be a possible result");
4530 /// \brief The number of exceptions in the exception specification.
4531 unsigned size() const { return Exceptions.size(); }
4533 /// \brief The set of exceptions in the exception specification.
4534 const QualType *data() const { return Exceptions.data(); }
4536 /// \brief Integrate another called method into the collected data.
4537 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4539 /// \brief Integrate an invoked expression into the collected data.
4540 void CalledExpr(Expr *E);
4542 /// \brief Overwrite an EPI's exception specification with this
4543 /// computed exception specification.
4544 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4545 FunctionProtoType::ExceptionSpecInfo ESI;
4546 ESI.Type = getExceptionSpecType();
4547 if (ESI.Type == EST_Dynamic) {
4548 ESI.Exceptions = Exceptions;
4549 } else if (ESI.Type == EST_None) {
4550 /// C++11 [except.spec]p14:
4551 /// The exception-specification is noexcept(false) if the set of
4552 /// potential exceptions of the special member function contains "any"
4553 ESI.Type = EST_ComputedNoexcept;
4554 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4555 tok::kw_false).get();
4561 /// \brief Determine what sort of exception specification a defaulted
4562 /// copy constructor of a class will have.
4563 ImplicitExceptionSpecification
4564 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4567 /// \brief Determine what sort of exception specification a defaulted
4568 /// default constructor of a class will have, and whether the parameter
4570 ImplicitExceptionSpecification
4571 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4573 /// \brief Determine what sort of exception specification a defautled
4574 /// copy assignment operator of a class will have, and whether the
4575 /// parameter will be const.
4576 ImplicitExceptionSpecification
4577 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4579 /// \brief Determine what sort of exception specification a defaulted move
4580 /// constructor of a class will have.
4581 ImplicitExceptionSpecification
4582 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4584 /// \brief Determine what sort of exception specification a defaulted move
4585 /// assignment operator of a class will have.
4586 ImplicitExceptionSpecification
4587 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4589 /// \brief Determine what sort of exception specification a defaulted
4590 /// destructor of a class will have.
4591 ImplicitExceptionSpecification
4592 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4594 /// \brief Determine what sort of exception specification an inheriting
4595 /// constructor of a class will have.
4596 ImplicitExceptionSpecification
4597 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4598 CXXConstructorDecl *CD);
4600 /// \brief Evaluate the implicit exception specification for a defaulted
4601 /// special member function.
4602 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4604 /// \brief Check the given exception-specification and update the
4605 /// exception specification information with the results.
4606 void checkExceptionSpecification(bool IsTopLevel,
4607 ExceptionSpecificationType EST,
4608 ArrayRef<ParsedType> DynamicExceptions,
4609 ArrayRef<SourceRange> DynamicExceptionRanges,
4611 SmallVectorImpl<QualType> &Exceptions,
4612 FunctionProtoType::ExceptionSpecInfo &ESI);
4614 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4615 /// parse an exception specification to work around a libstdc++ bug.
4616 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4618 /// \brief Add an exception-specification to the given member function
4619 /// (or member function template). The exception-specification was parsed
4620 /// after the method itself was declared.
4621 void actOnDelayedExceptionSpecification(Decl *Method,
4622 ExceptionSpecificationType EST,
4623 SourceRange SpecificationRange,
4624 ArrayRef<ParsedType> DynamicExceptions,
4625 ArrayRef<SourceRange> DynamicExceptionRanges,
4626 Expr *NoexceptExpr);
4628 class InheritedConstructorInfo;
4630 /// \brief Determine if a special member function should have a deleted
4631 /// definition when it is defaulted.
4632 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4633 InheritedConstructorInfo *ICI = nullptr,
4634 bool Diagnose = false);
4636 /// \brief Declare the implicit default constructor for the given class.
4638 /// \param ClassDecl The class declaration into which the implicit
4639 /// default constructor will be added.
4641 /// \returns The implicitly-declared default constructor.
4642 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4643 CXXRecordDecl *ClassDecl);
4645 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4646 /// defining this constructor as the default constructor.
4647 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4648 CXXConstructorDecl *Constructor);
4650 /// \brief Declare the implicit destructor for the given class.
4652 /// \param ClassDecl The class declaration into which the implicit
4653 /// destructor will be added.
4655 /// \returns The implicitly-declared destructor.
4656 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4658 /// DefineImplicitDestructor - Checks for feasibility of
4659 /// defining this destructor as the default destructor.
4660 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4661 CXXDestructorDecl *Destructor);
4663 /// \brief Build an exception spec for destructors that don't have one.
4665 /// C++11 says that user-defined destructors with no exception spec get one
4666 /// that looks as if the destructor was implicitly declared.
4667 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4668 CXXDestructorDecl *Destructor);
4670 /// \brief Define the specified inheriting constructor.
4671 void DefineInheritingConstructor(SourceLocation UseLoc,
4672 CXXConstructorDecl *Constructor);
4674 /// \brief Declare the implicit copy constructor for the given class.
4676 /// \param ClassDecl The class declaration into which the implicit
4677 /// copy constructor will be added.
4679 /// \returns The implicitly-declared copy constructor.
4680 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4682 /// DefineImplicitCopyConstructor - Checks for feasibility of
4683 /// defining this constructor as the copy constructor.
4684 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4685 CXXConstructorDecl *Constructor);
4687 /// \brief Declare the implicit move constructor for the given class.
4689 /// \param ClassDecl The Class declaration into which the implicit
4690 /// move constructor will be added.
4692 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4694 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4696 /// DefineImplicitMoveConstructor - Checks for feasibility of
4697 /// defining this constructor as the move constructor.
4698 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4699 CXXConstructorDecl *Constructor);
4701 /// \brief Declare the implicit copy assignment operator for the given class.
4703 /// \param ClassDecl The class declaration into which the implicit
4704 /// copy assignment operator will be added.
4706 /// \returns The implicitly-declared copy assignment operator.
4707 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4709 /// \brief Defines an implicitly-declared copy assignment operator.
4710 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4711 CXXMethodDecl *MethodDecl);
4713 /// \brief Declare the implicit move assignment operator for the given class.
4715 /// \param ClassDecl The Class declaration into which the implicit
4716 /// move assignment operator will be added.
4718 /// \returns The implicitly-declared move assignment operator, or NULL if it
4719 /// wasn't declared.
4720 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4722 /// \brief Defines an implicitly-declared move assignment operator.
4723 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4724 CXXMethodDecl *MethodDecl);
4726 /// \brief Force the declaration of any implicitly-declared members of this
4728 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4730 /// \brief Check a completed declaration of an implicit special member.
4731 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4733 /// \brief Determine whether the given function is an implicitly-deleted
4734 /// special member function.
4735 bool isImplicitlyDeleted(FunctionDecl *FD);
4737 /// \brief Check whether 'this' shows up in the type of a static member
4738 /// function after the (naturally empty) cv-qualifier-seq would be.
4740 /// \returns true if an error occurred.
4741 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4743 /// \brief Whether this' shows up in the exception specification of a static
4744 /// member function.
4745 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4747 /// \brief Check whether 'this' shows up in the attributes of the given
4748 /// static member function.
4750 /// \returns true if an error occurred.
4751 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4753 /// MaybeBindToTemporary - If the passed in expression has a record type with
4754 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4755 /// it simply returns the passed in expression.
4756 ExprResult MaybeBindToTemporary(Expr *E);
4758 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4759 MultiExprArg ArgsPtr,
4761 SmallVectorImpl<Expr*> &ConvertedArgs,
4762 bool AllowExplicit = false,
4763 bool IsListInitialization = false);
4765 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4766 SourceLocation NameLoc,
4767 IdentifierInfo &Name);
4769 ParsedType getDestructorName(SourceLocation TildeLoc,
4770 IdentifierInfo &II, SourceLocation NameLoc,
4771 Scope *S, CXXScopeSpec &SS,
4772 ParsedType ObjectType,
4773 bool EnteringContext);
4775 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4776 ParsedType ObjectType);
4778 // Checks that reinterpret casts don't have undefined behavior.
4779 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4780 bool IsDereference, SourceRange Range);
4782 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4783 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4784 tok::TokenKind Kind,
4785 SourceLocation LAngleBracketLoc,
4787 SourceLocation RAngleBracketLoc,
4788 SourceLocation LParenLoc,
4790 SourceLocation RParenLoc);
4792 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4793 tok::TokenKind Kind,
4796 SourceRange AngleBrackets,
4797 SourceRange Parens);
4799 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4800 SourceLocation TypeidLoc,
4801 TypeSourceInfo *Operand,
4802 SourceLocation RParenLoc);
4803 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4804 SourceLocation TypeidLoc,
4806 SourceLocation RParenLoc);
4808 /// ActOnCXXTypeid - Parse typeid( something ).
4809 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4810 SourceLocation LParenLoc, bool isType,
4812 SourceLocation RParenLoc);
4814 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4815 SourceLocation TypeidLoc,
4816 TypeSourceInfo *Operand,
4817 SourceLocation RParenLoc);
4818 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4819 SourceLocation TypeidLoc,
4821 SourceLocation RParenLoc);
4823 /// ActOnCXXUuidof - Parse __uuidof( something ).
4824 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4825 SourceLocation LParenLoc, bool isType,
4827 SourceLocation RParenLoc);
4829 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4830 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4831 tok::TokenKind Operator,
4832 SourceLocation EllipsisLoc, Expr *RHS,
4833 SourceLocation RParenLoc);
4834 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4835 BinaryOperatorKind Operator,
4836 SourceLocation EllipsisLoc, Expr *RHS,
4837 SourceLocation RParenLoc);
4838 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4839 BinaryOperatorKind Operator);
4841 //// ActOnCXXThis - Parse 'this' pointer.
4842 ExprResult ActOnCXXThis(SourceLocation loc);
4844 /// \brief Try to retrieve the type of the 'this' pointer.
4846 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4847 QualType getCurrentThisType();
4849 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4850 /// current context not being a non-static member function. In such cases,
4851 /// this provides the type used for 'this'.
4852 QualType CXXThisTypeOverride;
4854 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4855 /// to be used, with the given qualifiers on the current class type.
4856 class CXXThisScopeRAII {
4858 QualType OldCXXThisTypeOverride;
4862 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4863 /// using the given declaration (which is either a class template or a
4864 /// class) along with the given qualifiers.
4865 /// along with the qualifiers placed on '*this'.
4866 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4867 bool Enabled = true);
4869 ~CXXThisScopeRAII();
4872 /// \brief Make sure the value of 'this' is actually available in the current
4873 /// context, if it is a potentially evaluated context.
4875 /// \param Loc The location at which the capture of 'this' occurs.
4877 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4880 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4881 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4882 /// This is useful when enclosing lambdas must speculatively capture
4883 /// 'this' that may or may not be used in certain specializations of
4884 /// a nested generic lambda (depending on whether the name resolves to
4885 /// a non-static member function or a static function).
4886 /// \return returns 'true' if failed, 'false' if success.
4887 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4888 bool BuildAndDiagnose = true,
4889 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4890 bool ByCopy = false);
4892 /// \brief Determine whether the given type is the type of *this that is used
4893 /// outside of the body of a member function for a type that is currently
4895 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4897 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4898 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4901 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4902 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4905 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4906 SourceLocation AtLoc, SourceLocation RParen);
4908 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4909 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4911 //// ActOnCXXThrow - Parse throw expressions.
4912 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4913 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4914 bool IsThrownVarInScope);
4915 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4917 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4918 /// Can be interpreted either as function-style casting ("int(x)")
4919 /// or class type construction ("ClassType(x,y,z)")
4920 /// or creation of a value-initialized type ("int()").
4921 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4922 SourceLocation LParenLoc,
4924 SourceLocation RParenLoc);
4926 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4927 SourceLocation LParenLoc,
4929 SourceLocation RParenLoc);
4931 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4932 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4933 SourceLocation PlacementLParen,
4934 MultiExprArg PlacementArgs,
4935 SourceLocation PlacementRParen,
4936 SourceRange TypeIdParens, Declarator &D,
4938 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4939 SourceLocation PlacementLParen,
4940 MultiExprArg PlacementArgs,
4941 SourceLocation PlacementRParen,
4942 SourceRange TypeIdParens,
4944 TypeSourceInfo *AllocTypeInfo,
4946 SourceRange DirectInitRange,
4949 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4951 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4952 bool UseGlobal, QualType AllocType, bool IsArray,
4953 bool &PassAlignment, MultiExprArg PlaceArgs,
4954 FunctionDecl *&OperatorNew,
4955 FunctionDecl *&OperatorDelete);
4956 void DeclareGlobalNewDelete();
4957 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4958 ArrayRef<QualType> Params);
4960 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4961 DeclarationName Name, FunctionDecl* &Operator,
4962 bool Diagnose = true);
4963 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4964 bool CanProvideSize,
4966 DeclarationName Name);
4967 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4970 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4971 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4972 bool UseGlobal, bool ArrayForm,
4974 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4975 bool IsDelete, bool CallCanBeVirtual,
4976 bool WarnOnNonAbstractTypes,
4977 SourceLocation DtorLoc);
4979 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4980 Expr *Operand, SourceLocation RParen);
4981 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4982 SourceLocation RParen);
4984 /// \brief Parsed one of the type trait support pseudo-functions.
4985 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4986 ArrayRef<ParsedType> Args,
4987 SourceLocation RParenLoc);
4988 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4989 ArrayRef<TypeSourceInfo *> Args,
4990 SourceLocation RParenLoc);
4992 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
4993 /// pseudo-functions.
4994 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4995 SourceLocation KWLoc,
4998 SourceLocation RParen);
5000 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5001 SourceLocation KWLoc,
5002 TypeSourceInfo *TSInfo,
5004 SourceLocation RParen);
5006 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5007 /// pseudo-functions.
5008 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5009 SourceLocation KWLoc,
5011 SourceLocation RParen);
5013 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5014 SourceLocation KWLoc,
5016 SourceLocation RParen);
5018 ExprResult ActOnStartCXXMemberReference(Scope *S,
5020 SourceLocation OpLoc,
5021 tok::TokenKind OpKind,
5022 ParsedType &ObjectType,
5023 bool &MayBePseudoDestructor);
5025 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5026 SourceLocation OpLoc,
5027 tok::TokenKind OpKind,
5028 const CXXScopeSpec &SS,
5029 TypeSourceInfo *ScopeType,
5030 SourceLocation CCLoc,
5031 SourceLocation TildeLoc,
5032 PseudoDestructorTypeStorage DestroyedType);
5034 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5035 SourceLocation OpLoc,
5036 tok::TokenKind OpKind,
5038 UnqualifiedId &FirstTypeName,
5039 SourceLocation CCLoc,
5040 SourceLocation TildeLoc,
5041 UnqualifiedId &SecondTypeName);
5043 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5044 SourceLocation OpLoc,
5045 tok::TokenKind OpKind,
5046 SourceLocation TildeLoc,
5047 const DeclSpec& DS);
5049 /// MaybeCreateExprWithCleanups - If the current full-expression
5050 /// requires any cleanups, surround it with a ExprWithCleanups node.
5051 /// Otherwise, just returns the passed-in expression.
5052 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5053 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5054 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5056 MaterializeTemporaryExpr *
5057 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5058 bool BoundToLvalueReference);
5060 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5061 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5062 : SourceLocation());
5064 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5065 bool DiscardedValue = false,
5066 bool IsConstexpr = false,
5067 bool IsLambdaInitCaptureInitializer = false);
5068 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5070 // Marks SS invalid if it represents an incomplete type.
5071 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5073 DeclContext *computeDeclContext(QualType T);
5074 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5075 bool EnteringContext = false);
5076 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5077 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5079 /// \brief The parser has parsed a global nested-name-specifier '::'.
5081 /// \param CCLoc The location of the '::'.
5083 /// \param SS The nested-name-specifier, which will be updated in-place
5084 /// to reflect the parsed nested-name-specifier.
5086 /// \returns true if an error occurred, false otherwise.
5087 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5089 /// \brief The parser has parsed a '__super' nested-name-specifier.
5091 /// \param SuperLoc The location of the '__super' keyword.
5093 /// \param ColonColonLoc The location of the '::'.
5095 /// \param SS The nested-name-specifier, which will be updated in-place
5096 /// to reflect the parsed nested-name-specifier.
5098 /// \returns true if an error occurred, false otherwise.
5099 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5100 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5102 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5103 bool *CanCorrect = nullptr);
5104 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5106 /// \brief Keeps information about an identifier in a nested-name-spec.
5108 struct NestedNameSpecInfo {
5109 /// \brief The type of the object, if we're parsing nested-name-specifier in
5110 /// a member access expression.
5111 ParsedType ObjectType;
5113 /// \brief The identifier preceding the '::'.
5114 IdentifierInfo *Identifier;
5116 /// \brief The location of the identifier.
5117 SourceLocation IdentifierLoc;
5119 /// \brief The location of the '::'.
5120 SourceLocation CCLoc;
5122 /// \brief Creates info object for the most typical case.
5123 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5124 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5125 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5126 CCLoc(ColonColonLoc) {
5129 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5130 SourceLocation ColonColonLoc, QualType ObjectType)
5131 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5132 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5136 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5137 NestedNameSpecInfo &IdInfo);
5139 bool BuildCXXNestedNameSpecifier(Scope *S,
5140 NestedNameSpecInfo &IdInfo,
5141 bool EnteringContext,
5143 NamedDecl *ScopeLookupResult,
5144 bool ErrorRecoveryLookup,
5145 bool *IsCorrectedToColon = nullptr,
5146 bool OnlyNamespace = false);
5148 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5150 /// \param S The scope in which this nested-name-specifier occurs.
5152 /// \param IdInfo Parser information about an identifier in the
5153 /// nested-name-spec.
5155 /// \param EnteringContext Whether we're entering the context nominated by
5156 /// this nested-name-specifier.
5158 /// \param SS The nested-name-specifier, which is both an input
5159 /// parameter (the nested-name-specifier before this type) and an
5160 /// output parameter (containing the full nested-name-specifier,
5161 /// including this new type).
5163 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5164 /// error recovery. In this case do not emit error message.
5166 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5167 /// are allowed. The bool value pointed by this parameter is set to 'true'
5168 /// if the identifier is treated as if it was followed by ':', not '::'.
5170 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5172 /// \returns true if an error occurred, false otherwise.
5173 bool ActOnCXXNestedNameSpecifier(Scope *S,
5174 NestedNameSpecInfo &IdInfo,
5175 bool EnteringContext,
5177 bool ErrorRecoveryLookup = false,
5178 bool *IsCorrectedToColon = nullptr,
5179 bool OnlyNamespace = false);
5181 ExprResult ActOnDecltypeExpression(Expr *E);
5183 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5185 SourceLocation ColonColonLoc);
5187 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5188 NestedNameSpecInfo &IdInfo,
5189 bool EnteringContext);
5191 /// \brief The parser has parsed a nested-name-specifier
5192 /// 'template[opt] template-name < template-args >::'.
5194 /// \param S The scope in which this nested-name-specifier occurs.
5196 /// \param SS The nested-name-specifier, which is both an input
5197 /// parameter (the nested-name-specifier before this type) and an
5198 /// output parameter (containing the full nested-name-specifier,
5199 /// including this new type).
5201 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5202 /// \param TemplateName the template name.
5203 /// \param TemplateNameLoc The location of the template name.
5204 /// \param LAngleLoc The location of the opening angle bracket ('<').
5205 /// \param TemplateArgs The template arguments.
5206 /// \param RAngleLoc The location of the closing angle bracket ('>').
5207 /// \param CCLoc The location of the '::'.
5209 /// \param EnteringContext Whether we're entering the context of the
5210 /// nested-name-specifier.
5213 /// \returns true if an error occurred, false otherwise.
5214 bool ActOnCXXNestedNameSpecifier(Scope *S,
5216 SourceLocation TemplateKWLoc,
5217 TemplateTy TemplateName,
5218 SourceLocation TemplateNameLoc,
5219 SourceLocation LAngleLoc,
5220 ASTTemplateArgsPtr TemplateArgs,
5221 SourceLocation RAngleLoc,
5222 SourceLocation CCLoc,
5223 bool EnteringContext);
5225 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5226 /// that the parser can use later to reconstruct the given
5227 /// nested-name-specifier.
5229 /// \param SS A nested-name-specifier.
5231 /// \returns A pointer containing all of the information in the
5232 /// nested-name-specifier \p SS.
5233 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5235 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5236 /// the nested-name-specifier structure.
5238 /// \param Annotation The annotation pointer, produced by
5239 /// \c SaveNestedNameSpecifierAnnotation().
5241 /// \param AnnotationRange The source range corresponding to the annotation.
5243 /// \param SS The nested-name-specifier that will be updated with the contents
5244 /// of the annotation pointer.
5245 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5246 SourceRange AnnotationRange,
5249 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5251 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5252 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5253 /// After this method is called, according to [C++ 3.4.3p3], names should be
5254 /// looked up in the declarator-id's scope, until the declarator is parsed and
5255 /// ActOnCXXExitDeclaratorScope is called.
5256 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5257 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5259 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5260 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5261 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5262 /// Used to indicate that names should revert to being looked up in the
5264 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5266 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5267 /// initializer for the declaration 'Dcl'.
5268 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5269 /// static data member of class X, names should be looked up in the scope of
5271 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5273 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5274 /// initializer for the declaration 'Dcl'.
5275 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5277 /// \brief Create a new lambda closure type.
5278 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5279 TypeSourceInfo *Info,
5280 bool KnownDependent,
5281 LambdaCaptureDefault CaptureDefault);
5283 /// \brief Start the definition of a lambda expression.
5284 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5285 SourceRange IntroducerRange,
5286 TypeSourceInfo *MethodType,
5287 SourceLocation EndLoc,
5288 ArrayRef<ParmVarDecl *> Params,
5289 bool IsConstexprSpecified);
5291 /// \brief Endow the lambda scope info with the relevant properties.
5292 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5293 CXXMethodDecl *CallOperator,
5294 SourceRange IntroducerRange,
5295 LambdaCaptureDefault CaptureDefault,
5296 SourceLocation CaptureDefaultLoc,
5297 bool ExplicitParams,
5298 bool ExplicitResultType,
5301 /// \brief Perform initialization analysis of the init-capture and perform
5302 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5303 /// not being used to initialize a reference.
5304 ParsedType actOnLambdaInitCaptureInitialization(
5305 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5306 LambdaCaptureInitKind InitKind, Expr *&Init) {
5307 return ParsedType::make(buildLambdaInitCaptureInitialization(
5308 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5310 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5312 bool DirectInit, Expr *&Init);
5314 /// \brief Create a dummy variable within the declcontext of the lambda's
5315 /// call operator, for name lookup purposes for a lambda init capture.
5317 /// CodeGen handles emission of lambda captures, ignoring these dummy
5318 /// variables appropriately.
5319 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5320 QualType InitCaptureType,
5322 unsigned InitStyle, Expr *Init);
5324 /// \brief Build the implicit field for an init-capture.
5325 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5327 /// \brief Note that we have finished the explicit captures for the
5329 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5331 /// \brief Introduce the lambda parameters into scope.
5332 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5334 /// \brief Deduce a block or lambda's return type based on the return
5335 /// statements present in the body.
5336 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5338 /// ActOnStartOfLambdaDefinition - This is called just before we start
5339 /// parsing the body of a lambda; it analyzes the explicit captures and
5340 /// arguments, and sets up various data-structures for the body of the
5342 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5343 Declarator &ParamInfo, Scope *CurScope);
5345 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5346 /// is invoked to pop the information about the lambda.
5347 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5348 bool IsInstantiation = false);
5350 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5351 /// was successfully completed.
5352 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5355 /// \brief Does copying/destroying the captured variable have side effects?
5356 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5358 /// \brief Diagnose if an explicit lambda capture is unused.
5359 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5361 /// \brief Complete a lambda-expression having processed and attached the
5363 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5364 sema::LambdaScopeInfo *LSI);
5366 /// \brief Define the "body" of the conversion from a lambda object to a
5367 /// function pointer.
5369 /// This routine doesn't actually define a sensible body; rather, it fills
5370 /// in the initialization expression needed to copy the lambda object into
5371 /// the block, and IR generation actually generates the real body of the
5372 /// block pointer conversion.
5373 void DefineImplicitLambdaToFunctionPointerConversion(
5374 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5376 /// \brief Define the "body" of the conversion from a lambda object to a
5379 /// This routine doesn't actually define a sensible body; rather, it fills
5380 /// in the initialization expression needed to copy the lambda object into
5381 /// the block, and IR generation actually generates the real body of the
5382 /// block pointer conversion.
5383 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5384 CXXConversionDecl *Conv);
5386 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5387 SourceLocation ConvLocation,
5388 CXXConversionDecl *Conv,
5391 // ParseObjCStringLiteral - Parse Objective-C string literals.
5392 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5393 ArrayRef<Expr *> Strings);
5395 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5397 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5398 /// numeric literal expression. Type of the expression will be "NSNumber *"
5399 /// or "id" if NSNumber is unavailable.
5400 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5401 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5403 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5405 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5406 /// '@' prefixed parenthesized expression. The type of the expression will
5407 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5408 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5409 /// "const char *" or C structure with attribute 'objc_boxable'.
5410 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5412 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5414 ObjCMethodDecl *getterMethod,
5415 ObjCMethodDecl *setterMethod);
5417 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5418 MutableArrayRef<ObjCDictionaryElement> Elements);
5420 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5421 TypeSourceInfo *EncodedTypeInfo,
5422 SourceLocation RParenLoc);
5423 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5424 CXXConversionDecl *Method,
5425 bool HadMultipleCandidates);
5427 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5428 SourceLocation EncodeLoc,
5429 SourceLocation LParenLoc,
5431 SourceLocation RParenLoc);
5433 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5434 ExprResult ParseObjCSelectorExpression(Selector Sel,
5435 SourceLocation AtLoc,
5436 SourceLocation SelLoc,
5437 SourceLocation LParenLoc,
5438 SourceLocation RParenLoc,
5439 bool WarnMultipleSelectors);
5441 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5442 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5443 SourceLocation AtLoc,
5444 SourceLocation ProtoLoc,
5445 SourceLocation LParenLoc,
5446 SourceLocation ProtoIdLoc,
5447 SourceLocation RParenLoc);
5449 //===--------------------------------------------------------------------===//
5452 Decl *ActOnStartLinkageSpecification(Scope *S,
5453 SourceLocation ExternLoc,
5455 SourceLocation LBraceLoc);
5456 Decl *ActOnFinishLinkageSpecification(Scope *S,
5458 SourceLocation RBraceLoc);
5461 //===--------------------------------------------------------------------===//
5464 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5465 const CXXScopeSpec *SS = nullptr);
5466 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5468 bool ActOnAccessSpecifier(AccessSpecifier Access,
5469 SourceLocation ASLoc,
5470 SourceLocation ColonLoc,
5471 AttributeList *Attrs = nullptr);
5473 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5475 MultiTemplateParamsArg TemplateParameterLists,
5476 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5477 InClassInitStyle InitStyle);
5479 void ActOnStartCXXInClassMemberInitializer();
5480 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5481 SourceLocation EqualLoc,
5484 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5487 IdentifierInfo *MemberOrBase,
5488 ParsedType TemplateTypeTy,
5490 SourceLocation IdLoc,
5491 SourceLocation LParenLoc,
5492 ArrayRef<Expr *> Args,
5493 SourceLocation RParenLoc,
5494 SourceLocation EllipsisLoc);
5496 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5499 IdentifierInfo *MemberOrBase,
5500 ParsedType TemplateTypeTy,
5502 SourceLocation IdLoc,
5504 SourceLocation EllipsisLoc);
5506 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5509 IdentifierInfo *MemberOrBase,
5510 ParsedType TemplateTypeTy,
5512 SourceLocation IdLoc,
5514 SourceLocation EllipsisLoc);
5516 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5518 SourceLocation IdLoc);
5520 MemInitResult BuildBaseInitializer(QualType BaseType,
5521 TypeSourceInfo *BaseTInfo,
5523 CXXRecordDecl *ClassDecl,
5524 SourceLocation EllipsisLoc);
5526 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5528 CXXRecordDecl *ClassDecl);
5530 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5531 CXXCtorInitializer *Initializer);
5533 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5534 ArrayRef<CXXCtorInitializer *> Initializers = None);
5536 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5539 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5540 /// mark all the non-trivial destructors of its members and bases as
5542 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5543 CXXRecordDecl *Record);
5545 /// \brief The list of classes whose vtables have been used within
5546 /// this translation unit, and the source locations at which the
5547 /// first use occurred.
5548 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5550 /// \brief The list of vtables that are required but have not yet been
5552 SmallVector<VTableUse, 16> VTableUses;
5554 /// \brief The set of classes whose vtables have been used within
5555 /// this translation unit, and a bit that will be true if the vtable is
5556 /// required to be emitted (otherwise, it should be emitted only if needed
5557 /// by code generation).
5558 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5560 /// \brief Load any externally-stored vtable uses.
5561 void LoadExternalVTableUses();
5563 /// \brief Note that the vtable for the given class was used at the
5565 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5566 bool DefinitionRequired = false);
5568 /// \brief Mark the exception specifications of all virtual member functions
5569 /// in the given class as needed.
5570 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5571 const CXXRecordDecl *RD);
5573 /// MarkVirtualMembersReferenced - Will mark all members of the given
5574 /// CXXRecordDecl referenced.
5575 void MarkVirtualMembersReferenced(SourceLocation Loc,
5576 const CXXRecordDecl *RD);
5578 /// \brief Define all of the vtables that have been used in this
5579 /// translation unit and reference any virtual members used by those
5582 /// \returns true if any work was done, false otherwise.
5583 bool DefineUsedVTables();
5585 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5587 void ActOnMemInitializers(Decl *ConstructorDecl,
5588 SourceLocation ColonLoc,
5589 ArrayRef<CXXCtorInitializer*> MemInits,
5592 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5593 /// ensure that referenceDLLExportedClassMethods is called some point later
5594 /// when all outer classes of Class are complete.
5595 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5597 void referenceDLLExportedClassMethods();
5599 void propagateDLLAttrToBaseClassTemplate(
5600 CXXRecordDecl *Class, Attr *ClassAttr,
5601 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5602 SourceLocation BaseLoc);
5604 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5605 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5607 SourceLocation LBrac,
5608 SourceLocation RBrac,
5609 AttributeList *AttrList);
5610 void ActOnFinishCXXMemberDecls();
5611 void ActOnFinishCXXNonNestedClass(Decl *D);
5613 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5614 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5615 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5616 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5617 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5618 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5619 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5620 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5621 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5622 CachedTokens &Toks);
5623 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5624 bool IsInsideALocalClassWithinATemplateFunction();
5626 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5628 Expr *AssertMessageExpr,
5629 SourceLocation RParenLoc);
5630 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5632 StringLiteral *AssertMessageExpr,
5633 SourceLocation RParenLoc,
5636 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5637 SourceLocation FriendLoc,
5638 TypeSourceInfo *TSInfo);
5639 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5640 MultiTemplateParamsArg TemplateParams);
5641 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5642 MultiTemplateParamsArg TemplateParams);
5644 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5646 void CheckConstructor(CXXConstructorDecl *Constructor);
5647 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5649 bool CheckDestructor(CXXDestructorDecl *Destructor);
5650 void CheckConversionDeclarator(Declarator &D, QualType &R,
5652 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5653 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5655 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5657 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5658 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5659 const FunctionProtoType *T);
5660 void CheckDelayedMemberExceptionSpecs();
5662 //===--------------------------------------------------------------------===//
5663 // C++ Derived Classes
5666 /// ActOnBaseSpecifier - Parsed a base specifier
5667 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5668 SourceRange SpecifierRange,
5669 bool Virtual, AccessSpecifier Access,
5670 TypeSourceInfo *TInfo,
5671 SourceLocation EllipsisLoc);
5673 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5674 SourceRange SpecifierRange,
5675 ParsedAttributes &Attrs,
5676 bool Virtual, AccessSpecifier Access,
5677 ParsedType basetype,
5678 SourceLocation BaseLoc,
5679 SourceLocation EllipsisLoc);
5681 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5682 MutableArrayRef<CXXBaseSpecifier *> Bases);
5683 void ActOnBaseSpecifiers(Decl *ClassDecl,
5684 MutableArrayRef<CXXBaseSpecifier *> Bases);
5686 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5687 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5688 CXXBasePaths &Paths);
5690 // FIXME: I don't like this name.
5691 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5693 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5694 SourceLocation Loc, SourceRange Range,
5695 CXXCastPath *BasePath = nullptr,
5696 bool IgnoreAccess = false);
5697 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5698 unsigned InaccessibleBaseID,
5699 unsigned AmbigiousBaseConvID,
5700 SourceLocation Loc, SourceRange Range,
5701 DeclarationName Name,
5702 CXXCastPath *BasePath,
5703 bool IgnoreAccess = false);
5705 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5707 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5708 const CXXMethodDecl *Old);
5710 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5711 /// covariant, according to C++ [class.virtual]p5.
5712 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5713 const CXXMethodDecl *Old);
5715 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5716 /// spec is a subset of base spec.
5717 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5718 const CXXMethodDecl *Old);
5720 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5722 /// CheckOverrideControl - Check C++11 override control semantics.
5723 void CheckOverrideControl(NamedDecl *D);
5725 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5726 /// not used in the declaration of an overriding method.
5727 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5729 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5730 /// overrides a virtual member function marked 'final', according to
5731 /// C++11 [class.virtual]p4.
5732 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5733 const CXXMethodDecl *Old);
5736 //===--------------------------------------------------------------------===//
5737 // C++ Access Control
5747 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5748 NamedDecl *PrevMemberDecl,
5749 AccessSpecifier LexicalAS);
5751 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5752 DeclAccessPair FoundDecl);
5753 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5754 DeclAccessPair FoundDecl);
5755 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5756 SourceRange PlacementRange,
5757 CXXRecordDecl *NamingClass,
5758 DeclAccessPair FoundDecl,
5759 bool Diagnose = true);
5760 AccessResult CheckConstructorAccess(SourceLocation Loc,
5761 CXXConstructorDecl *D,
5762 DeclAccessPair FoundDecl,
5763 const InitializedEntity &Entity,
5764 bool IsCopyBindingRefToTemp = false);
5765 AccessResult CheckConstructorAccess(SourceLocation Loc,
5766 CXXConstructorDecl *D,
5767 DeclAccessPair FoundDecl,
5768 const InitializedEntity &Entity,
5769 const PartialDiagnostic &PDiag);
5770 AccessResult CheckDestructorAccess(SourceLocation Loc,
5771 CXXDestructorDecl *Dtor,
5772 const PartialDiagnostic &PDiag,
5773 QualType objectType = QualType());
5774 AccessResult CheckFriendAccess(NamedDecl *D);
5775 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5776 CXXRecordDecl *NamingClass,
5777 DeclAccessPair Found);
5778 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5781 DeclAccessPair FoundDecl);
5782 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5783 DeclAccessPair FoundDecl);
5784 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5785 QualType Base, QualType Derived,
5786 const CXXBasePath &Path,
5788 bool ForceCheck = false,
5789 bool ForceUnprivileged = false);
5790 void CheckLookupAccess(const LookupResult &R);
5791 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5792 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5793 AccessSpecifier access,
5794 QualType objectType);
5796 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5797 const MultiLevelTemplateArgumentList &TemplateArgs);
5798 void PerformDependentDiagnostics(const DeclContext *Pattern,
5799 const MultiLevelTemplateArgumentList &TemplateArgs);
5801 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5803 /// \brief When true, access checking violations are treated as SFINAE
5804 /// failures rather than hard errors.
5805 bool AccessCheckingSFINAE;
5807 enum AbstractDiagSelID {
5811 AbstractVariableType,
5814 AbstractSynthesizedIvarType,
5818 bool isAbstractType(SourceLocation Loc, QualType T);
5819 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5820 TypeDiagnoser &Diagnoser);
5821 template <typename... Ts>
5822 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5823 const Ts &...Args) {
5824 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5825 return RequireNonAbstractType(Loc, T, Diagnoser);
5828 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5830 //===--------------------------------------------------------------------===//
5831 // C++ Overloaded Operators [C++ 13.5]
5834 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5836 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5838 //===--------------------------------------------------------------------===//
5839 // C++ Templates [C++ 14]
5841 void FilterAcceptableTemplateNames(LookupResult &R,
5842 bool AllowFunctionTemplates = true);
5843 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5844 bool AllowFunctionTemplates = true);
5846 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5847 QualType ObjectType, bool EnteringContext,
5848 bool &MemberOfUnknownSpecialization);
5850 TemplateNameKind isTemplateName(Scope *S,
5852 bool hasTemplateKeyword,
5853 UnqualifiedId &Name,
5854 ParsedType ObjectType,
5855 bool EnteringContext,
5856 TemplateTy &Template,
5857 bool &MemberOfUnknownSpecialization);
5859 /// Determine whether a particular identifier might be the name in a C++1z
5860 /// deduction-guide declaration.
5861 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5862 SourceLocation NameLoc,
5863 ParsedTemplateTy *Template = nullptr);
5865 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5866 SourceLocation IILoc,
5868 const CXXScopeSpec *SS,
5869 TemplateTy &SuggestedTemplate,
5870 TemplateNameKind &SuggestedKind);
5872 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5873 NamedDecl *Instantiation,
5874 bool InstantiatedFromMember,
5875 const NamedDecl *Pattern,
5876 const NamedDecl *PatternDef,
5877 TemplateSpecializationKind TSK,
5878 bool Complain = true);
5880 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5881 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5883 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5884 SourceLocation EllipsisLoc,
5885 SourceLocation KeyLoc,
5886 IdentifierInfo *ParamName,
5887 SourceLocation ParamNameLoc,
5888 unsigned Depth, unsigned Position,
5889 SourceLocation EqualLoc,
5890 ParsedType DefaultArg);
5892 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5893 SourceLocation Loc);
5894 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5896 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5899 SourceLocation EqualLoc,
5901 Decl *ActOnTemplateTemplateParameter(Scope *S,
5902 SourceLocation TmpLoc,
5903 TemplateParameterList *Params,
5904 SourceLocation EllipsisLoc,
5905 IdentifierInfo *ParamName,
5906 SourceLocation ParamNameLoc,
5909 SourceLocation EqualLoc,
5910 ParsedTemplateArgument DefaultArg);
5912 TemplateParameterList *
5913 ActOnTemplateParameterList(unsigned Depth,
5914 SourceLocation ExportLoc,
5915 SourceLocation TemplateLoc,
5916 SourceLocation LAngleLoc,
5917 ArrayRef<Decl *> Params,
5918 SourceLocation RAngleLoc,
5919 Expr *RequiresClause);
5921 /// \brief The context in which we are checking a template parameter list.
5922 enum TemplateParamListContext {
5925 TPC_FunctionTemplate,
5926 TPC_ClassTemplateMember,
5927 TPC_FriendClassTemplate,
5928 TPC_FriendFunctionTemplate,
5929 TPC_FriendFunctionTemplateDefinition,
5930 TPC_TypeAliasTemplate
5933 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5934 TemplateParameterList *OldParams,
5935 TemplateParamListContext TPC);
5936 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5937 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5938 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5939 ArrayRef<TemplateParameterList *> ParamLists,
5940 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5942 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5943 SourceLocation KWLoc, CXXScopeSpec &SS,
5944 IdentifierInfo *Name, SourceLocation NameLoc,
5945 AttributeList *Attr,
5946 TemplateParameterList *TemplateParams,
5948 SourceLocation ModulePrivateLoc,
5949 SourceLocation FriendLoc,
5950 unsigned NumOuterTemplateParamLists,
5951 TemplateParameterList **OuterTemplateParamLists,
5952 SkipBodyInfo *SkipBody = nullptr);
5954 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5956 SourceLocation Loc);
5958 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5959 TemplateArgumentListInfo &Out);
5961 void NoteAllFoundTemplates(TemplateName Name);
5963 QualType CheckTemplateIdType(TemplateName Template,
5964 SourceLocation TemplateLoc,
5965 TemplateArgumentListInfo &TemplateArgs);
5968 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5969 TemplateTy Template, IdentifierInfo *TemplateII,
5970 SourceLocation TemplateIILoc,
5971 SourceLocation LAngleLoc,
5972 ASTTemplateArgsPtr TemplateArgs,
5973 SourceLocation RAngleLoc,
5974 bool IsCtorOrDtorName = false,
5975 bool IsClassName = false);
5977 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5978 /// such as \c class T::template apply<U>.
5979 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5980 TypeSpecifierType TagSpec,
5981 SourceLocation TagLoc,
5983 SourceLocation TemplateKWLoc,
5984 TemplateTy TemplateD,
5985 SourceLocation TemplateLoc,
5986 SourceLocation LAngleLoc,
5987 ASTTemplateArgsPtr TemplateArgsIn,
5988 SourceLocation RAngleLoc);
5990 DeclResult ActOnVarTemplateSpecialization(
5991 Scope *S, Declarator &D, TypeSourceInfo *DI,
5992 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5993 StorageClass SC, bool IsPartialSpecialization);
5995 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5996 SourceLocation TemplateLoc,
5997 SourceLocation TemplateNameLoc,
5998 const TemplateArgumentListInfo &TemplateArgs);
6000 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6001 const DeclarationNameInfo &NameInfo,
6002 VarTemplateDecl *Template,
6003 SourceLocation TemplateLoc,
6004 const TemplateArgumentListInfo *TemplateArgs);
6006 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6007 SourceLocation TemplateKWLoc,
6010 const TemplateArgumentListInfo *TemplateArgs);
6012 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6013 SourceLocation TemplateKWLoc,
6014 const DeclarationNameInfo &NameInfo,
6015 const TemplateArgumentListInfo *TemplateArgs);
6017 TemplateNameKind ActOnDependentTemplateName(
6018 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6019 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6020 TemplateTy &Template, bool AllowInjectedClassName = false);
6023 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6024 SourceLocation KWLoc,
6025 SourceLocation ModulePrivateLoc,
6026 TemplateIdAnnotation &TemplateId,
6027 AttributeList *Attr,
6028 MultiTemplateParamsArg TemplateParameterLists,
6029 SkipBodyInfo *SkipBody = nullptr);
6031 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6032 TemplateDecl *PrimaryTemplate,
6033 unsigned NumExplicitArgs,
6034 ArrayRef<TemplateArgument> Args);
6035 void CheckTemplatePartialSpecialization(
6036 ClassTemplatePartialSpecializationDecl *Partial);
6037 void CheckTemplatePartialSpecialization(
6038 VarTemplatePartialSpecializationDecl *Partial);
6040 Decl *ActOnTemplateDeclarator(Scope *S,
6041 MultiTemplateParamsArg TemplateParameterLists,
6045 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6046 TemplateSpecializationKind NewTSK,
6047 NamedDecl *PrevDecl,
6048 TemplateSpecializationKind PrevTSK,
6049 SourceLocation PrevPtOfInstantiation,
6052 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6053 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6054 LookupResult &Previous);
6056 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6057 TemplateArgumentListInfo *ExplicitTemplateArgs,
6058 LookupResult &Previous);
6059 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6062 ActOnExplicitInstantiation(Scope *S,
6063 SourceLocation ExternLoc,
6064 SourceLocation TemplateLoc,
6066 SourceLocation KWLoc,
6067 const CXXScopeSpec &SS,
6068 TemplateTy Template,
6069 SourceLocation TemplateNameLoc,
6070 SourceLocation LAngleLoc,
6071 ASTTemplateArgsPtr TemplateArgs,
6072 SourceLocation RAngleLoc,
6073 AttributeList *Attr);
6076 ActOnExplicitInstantiation(Scope *S,
6077 SourceLocation ExternLoc,
6078 SourceLocation TemplateLoc,
6080 SourceLocation KWLoc,
6082 IdentifierInfo *Name,
6083 SourceLocation NameLoc,
6084 AttributeList *Attr);
6086 DeclResult ActOnExplicitInstantiation(Scope *S,
6087 SourceLocation ExternLoc,
6088 SourceLocation TemplateLoc,
6092 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6093 SourceLocation TemplateLoc,
6094 SourceLocation RAngleLoc,
6096 SmallVectorImpl<TemplateArgument>
6098 bool &HasDefaultArg);
6100 /// \brief Specifies the context in which a particular template
6101 /// argument is being checked.
6102 enum CheckTemplateArgumentKind {
6103 /// \brief The template argument was specified in the code or was
6104 /// instantiated with some deduced template arguments.
6107 /// \brief The template argument was deduced via template argument
6111 /// \brief The template argument was deduced from an array bound
6112 /// via template argument deduction.
6113 CTAK_DeducedFromArrayBound
6116 bool CheckTemplateArgument(NamedDecl *Param,
6117 TemplateArgumentLoc &Arg,
6118 NamedDecl *Template,
6119 SourceLocation TemplateLoc,
6120 SourceLocation RAngleLoc,
6121 unsigned ArgumentPackIndex,
6122 SmallVectorImpl<TemplateArgument> &Converted,
6123 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6125 /// \brief Check that the given template arguments can be be provided to
6126 /// the given template, converting the arguments along the way.
6128 /// \param Template The template to which the template arguments are being
6131 /// \param TemplateLoc The location of the template name in the source.
6133 /// \param TemplateArgs The list of template arguments. If the template is
6134 /// a template template parameter, this function may extend the set of
6135 /// template arguments to also include substituted, defaulted template
6138 /// \param PartialTemplateArgs True if the list of template arguments is
6139 /// intentionally partial, e.g., because we're checking just the initial
6140 /// set of template arguments.
6142 /// \param Converted Will receive the converted, canonicalized template
6145 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6146 /// contain the converted forms of the template arguments as written.
6147 /// Otherwise, \p TemplateArgs will not be modified.
6149 /// \returns true if an error occurred, false otherwise.
6150 bool CheckTemplateArgumentList(TemplateDecl *Template,
6151 SourceLocation TemplateLoc,
6152 TemplateArgumentListInfo &TemplateArgs,
6153 bool PartialTemplateArgs,
6154 SmallVectorImpl<TemplateArgument> &Converted,
6155 bool UpdateArgsWithConversions = true);
6157 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6158 TemplateArgumentLoc &Arg,
6159 SmallVectorImpl<TemplateArgument> &Converted);
6161 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6162 TypeSourceInfo *Arg);
6163 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6164 QualType InstantiatedParamType, Expr *Arg,
6165 TemplateArgument &Converted,
6166 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6167 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6168 TemplateArgumentLoc &Arg,
6169 unsigned ArgumentPackIndex);
6172 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6174 SourceLocation Loc);
6176 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6177 SourceLocation Loc);
6179 /// \brief Enumeration describing how template parameter lists are compared
6181 enum TemplateParameterListEqualKind {
6182 /// \brief We are matching the template parameter lists of two templates
6183 /// that might be redeclarations.
6186 /// template<typename T> struct X;
6187 /// template<typename T> struct X;
6191 /// \brief We are matching the template parameter lists of two template
6192 /// template parameters as part of matching the template parameter lists
6193 /// of two templates that might be redeclarations.
6196 /// template<template<int I> class TT> struct X;
6197 /// template<template<int Value> class Other> struct X;
6199 TPL_TemplateTemplateParmMatch,
6201 /// \brief We are matching the template parameter lists of a template
6202 /// template argument against the template parameter lists of a template
6203 /// template parameter.
6206 /// template<template<int Value> class Metafun> struct X;
6207 /// template<int Value> struct integer_c;
6208 /// X<integer_c> xic;
6210 TPL_TemplateTemplateArgumentMatch
6213 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6214 TemplateParameterList *Old,
6216 TemplateParameterListEqualKind Kind,
6217 SourceLocation TemplateArgLoc
6218 = SourceLocation());
6220 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6222 /// \brief Called when the parser has parsed a C++ typename
6223 /// specifier, e.g., "typename T::type".
6225 /// \param S The scope in which this typename type occurs.
6226 /// \param TypenameLoc the location of the 'typename' keyword
6227 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6228 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6229 /// \param IdLoc the location of the identifier.
6231 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6232 const CXXScopeSpec &SS, const IdentifierInfo &II,
6233 SourceLocation IdLoc);
6235 /// \brief Called when the parser has parsed a C++ typename
6236 /// specifier that ends in a template-id, e.g.,
6237 /// "typename MetaFun::template apply<T1, T2>".
6239 /// \param S The scope in which this typename type occurs.
6240 /// \param TypenameLoc the location of the 'typename' keyword
6241 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6242 /// \param TemplateLoc the location of the 'template' keyword, if any.
6243 /// \param TemplateName The template name.
6244 /// \param TemplateII The identifier used to name the template.
6245 /// \param TemplateIILoc The location of the template name.
6246 /// \param LAngleLoc The location of the opening angle bracket ('<').
6247 /// \param TemplateArgs The template arguments.
6248 /// \param RAngleLoc The location of the closing angle bracket ('>').
6250 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6251 const CXXScopeSpec &SS,
6252 SourceLocation TemplateLoc,
6253 TemplateTy TemplateName,
6254 IdentifierInfo *TemplateII,
6255 SourceLocation TemplateIILoc,
6256 SourceLocation LAngleLoc,
6257 ASTTemplateArgsPtr TemplateArgs,
6258 SourceLocation RAngleLoc);
6260 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6261 SourceLocation KeywordLoc,
6262 NestedNameSpecifierLoc QualifierLoc,
6263 const IdentifierInfo &II,
6264 SourceLocation IILoc);
6266 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6268 DeclarationName Name);
6269 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6271 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6272 bool RebuildTemplateParamsInCurrentInstantiation(
6273 TemplateParameterList *Params);
6276 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6277 const TemplateArgumentList &Args);
6280 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6281 const TemplateArgument *Args,
6284 //===--------------------------------------------------------------------===//
6285 // C++ Variadic Templates (C++0x [temp.variadic])
6286 //===--------------------------------------------------------------------===//
6288 /// Determine whether an unexpanded parameter pack might be permitted in this
6289 /// location. Useful for error recovery.
6290 bool isUnexpandedParameterPackPermitted();
6292 /// \brief The context in which an unexpanded parameter pack is
6293 /// being diagnosed.
6295 /// Note that the values of this enumeration line up with the first
6296 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6297 enum UnexpandedParameterPackContext {
6298 /// \brief An arbitrary expression.
6299 UPPC_Expression = 0,
6301 /// \brief The base type of a class type.
6304 /// \brief The type of an arbitrary declaration.
6305 UPPC_DeclarationType,
6307 /// \brief The type of a data member.
6308 UPPC_DataMemberType,
6310 /// \brief The size of a bit-field.
6313 /// \brief The expression in a static assertion.
6314 UPPC_StaticAssertExpression,
6316 /// \brief The fixed underlying type of an enumeration.
6317 UPPC_FixedUnderlyingType,
6319 /// \brief The enumerator value.
6320 UPPC_EnumeratorValue,
6322 /// \brief A using declaration.
6323 UPPC_UsingDeclaration,
6325 /// \brief A friend declaration.
6326 UPPC_FriendDeclaration,
6328 /// \brief A declaration qualifier.
6329 UPPC_DeclarationQualifier,
6331 /// \brief An initializer.
6334 /// \brief A default argument.
6335 UPPC_DefaultArgument,
6337 /// \brief The type of a non-type template parameter.
6338 UPPC_NonTypeTemplateParameterType,
6340 /// \brief The type of an exception.
6343 /// \brief Partial specialization.
6344 UPPC_PartialSpecialization,
6346 /// \brief Microsoft __if_exists.
6349 /// \brief Microsoft __if_not_exists.
6352 /// \brief Lambda expression.
6355 /// \brief Block expression,
6359 /// \brief Diagnose unexpanded parameter packs.
6361 /// \param Loc The location at which we should emit the diagnostic.
6363 /// \param UPPC The context in which we are diagnosing unexpanded
6364 /// parameter packs.
6366 /// \param Unexpanded the set of unexpanded parameter packs.
6368 /// \returns true if an error occurred, false otherwise.
6369 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6370 UnexpandedParameterPackContext UPPC,
6371 ArrayRef<UnexpandedParameterPack> Unexpanded);
6373 /// \brief If the given type contains an unexpanded parameter pack,
6374 /// diagnose the error.
6376 /// \param Loc The source location where a diagnostc should be emitted.
6378 /// \param T The type that is being checked for unexpanded parameter
6381 /// \returns true if an error occurred, false otherwise.
6382 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6383 UnexpandedParameterPackContext UPPC);
6385 /// \brief If the given expression contains an unexpanded parameter
6386 /// pack, diagnose the error.
6388 /// \param E The expression that is being checked for unexpanded
6389 /// parameter packs.
6391 /// \returns true if an error occurred, false otherwise.
6392 bool DiagnoseUnexpandedParameterPack(Expr *E,
6393 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6395 /// \brief If the given nested-name-specifier contains an unexpanded
6396 /// parameter pack, diagnose the error.
6398 /// \param SS The nested-name-specifier that is being checked for
6399 /// unexpanded parameter packs.
6401 /// \returns true if an error occurred, false otherwise.
6402 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6403 UnexpandedParameterPackContext UPPC);
6405 /// \brief If the given name contains an unexpanded parameter pack,
6406 /// diagnose the error.
6408 /// \param NameInfo The name (with source location information) that
6409 /// is being checked for unexpanded parameter packs.
6411 /// \returns true if an error occurred, false otherwise.
6412 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6413 UnexpandedParameterPackContext UPPC);
6415 /// \brief If the given template name contains an unexpanded parameter pack,
6416 /// diagnose the error.
6418 /// \param Loc The location of the template name.
6420 /// \param Template The template name that is being checked for unexpanded
6421 /// parameter packs.
6423 /// \returns true if an error occurred, false otherwise.
6424 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6425 TemplateName Template,
6426 UnexpandedParameterPackContext UPPC);
6428 /// \brief If the given template argument contains an unexpanded parameter
6429 /// pack, diagnose the error.
6431 /// \param Arg The template argument that is being checked for unexpanded
6432 /// parameter packs.
6434 /// \returns true if an error occurred, false otherwise.
6435 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6436 UnexpandedParameterPackContext UPPC);
6438 /// \brief Collect the set of unexpanded parameter packs within the given
6439 /// template argument.
6441 /// \param Arg The template argument that will be traversed to find
6442 /// unexpanded parameter packs.
6443 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6444 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6446 /// \brief Collect the set of unexpanded parameter packs within the given
6447 /// template argument.
6449 /// \param Arg The template argument that will be traversed to find
6450 /// unexpanded parameter packs.
6451 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6452 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6454 /// \brief Collect the set of unexpanded parameter packs within the given
6457 /// \param T The type that will be traversed to find
6458 /// unexpanded parameter packs.
6459 void collectUnexpandedParameterPacks(QualType T,
6460 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6462 /// \brief Collect the set of unexpanded parameter packs within the given
6465 /// \param TL The type that will be traversed to find
6466 /// unexpanded parameter packs.
6467 void collectUnexpandedParameterPacks(TypeLoc TL,
6468 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6470 /// \brief Collect the set of unexpanded parameter packs within the given
6471 /// nested-name-specifier.
6473 /// \param NNS The nested-name-specifier that will be traversed to find
6474 /// unexpanded parameter packs.
6475 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6476 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6478 /// \brief Collect the set of unexpanded parameter packs within the given
6481 /// \param NameInfo The name that will be traversed to find
6482 /// unexpanded parameter packs.
6483 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6484 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6486 /// \brief Invoked when parsing a template argument followed by an
6487 /// ellipsis, which creates a pack expansion.
6489 /// \param Arg The template argument preceding the ellipsis, which
6490 /// may already be invalid.
6492 /// \param EllipsisLoc The location of the ellipsis.
6493 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6494 SourceLocation EllipsisLoc);
6496 /// \brief Invoked when parsing a type followed by an ellipsis, which
6497 /// creates a pack expansion.
6499 /// \param Type The type preceding the ellipsis, which will become
6500 /// the pattern of the pack expansion.
6502 /// \param EllipsisLoc The location of the ellipsis.
6503 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6505 /// \brief Construct a pack expansion type from the pattern of the pack
6507 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6508 SourceLocation EllipsisLoc,
6509 Optional<unsigned> NumExpansions);
6511 /// \brief Construct a pack expansion type from the pattern of the pack
6513 QualType CheckPackExpansion(QualType Pattern,
6514 SourceRange PatternRange,
6515 SourceLocation EllipsisLoc,
6516 Optional<unsigned> NumExpansions);
6518 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6519 /// creates a pack expansion.
6521 /// \param Pattern The expression preceding the ellipsis, which will become
6522 /// the pattern of the pack expansion.
6524 /// \param EllipsisLoc The location of the ellipsis.
6525 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6527 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6528 /// creates a pack expansion.
6530 /// \param Pattern The expression preceding the ellipsis, which will become
6531 /// the pattern of the pack expansion.
6533 /// \param EllipsisLoc The location of the ellipsis.
6534 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6535 Optional<unsigned> NumExpansions);
6537 /// \brief Determine whether we could expand a pack expansion with the
6538 /// given set of parameter packs into separate arguments by repeatedly
6539 /// transforming the pattern.
6541 /// \param EllipsisLoc The location of the ellipsis that identifies the
6544 /// \param PatternRange The source range that covers the entire pattern of
6545 /// the pack expansion.
6547 /// \param Unexpanded The set of unexpanded parameter packs within the
6550 /// \param ShouldExpand Will be set to \c true if the transformer should
6551 /// expand the corresponding pack expansions into separate arguments. When
6552 /// set, \c NumExpansions must also be set.
6554 /// \param RetainExpansion Whether the caller should add an unexpanded
6555 /// pack expansion after all of the expanded arguments. This is used
6556 /// when extending explicitly-specified template argument packs per
6557 /// C++0x [temp.arg.explicit]p9.
6559 /// \param NumExpansions The number of separate arguments that will be in
6560 /// the expanded form of the corresponding pack expansion. This is both an
6561 /// input and an output parameter, which can be set by the caller if the
6562 /// number of expansions is known a priori (e.g., due to a prior substitution)
6563 /// and will be set by the callee when the number of expansions is known.
6564 /// The callee must set this value when \c ShouldExpand is \c true; it may
6565 /// set this value in other cases.
6567 /// \returns true if an error occurred (e.g., because the parameter packs
6568 /// are to be instantiated with arguments of different lengths), false
6569 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6571 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6572 SourceRange PatternRange,
6573 ArrayRef<UnexpandedParameterPack> Unexpanded,
6574 const MultiLevelTemplateArgumentList &TemplateArgs,
6576 bool &RetainExpansion,
6577 Optional<unsigned> &NumExpansions);
6579 /// \brief Determine the number of arguments in the given pack expansion
6582 /// This routine assumes that the number of arguments in the expansion is
6583 /// consistent across all of the unexpanded parameter packs in its pattern.
6585 /// Returns an empty Optional if the type can't be expanded.
6586 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6587 const MultiLevelTemplateArgumentList &TemplateArgs);
6589 /// \brief Determine whether the given declarator contains any unexpanded
6590 /// parameter packs.
6592 /// This routine is used by the parser to disambiguate function declarators
6593 /// with an ellipsis prior to the ')', e.g.,
6599 /// To determine whether we have an (unnamed) function parameter pack or
6600 /// a variadic function.
6602 /// \returns true if the declarator contains any unexpanded parameter packs,
6603 /// false otherwise.
6604 bool containsUnexpandedParameterPacks(Declarator &D);
6606 /// \brief Returns the pattern of the pack expansion for a template argument.
6608 /// \param OrigLoc The template argument to expand.
6610 /// \param Ellipsis Will be set to the location of the ellipsis.
6612 /// \param NumExpansions Will be set to the number of expansions that will
6613 /// be generated from this pack expansion, if known a priori.
6614 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6615 TemplateArgumentLoc OrigLoc,
6616 SourceLocation &Ellipsis,
6617 Optional<unsigned> &NumExpansions) const;
6619 /// Given a template argument that contains an unexpanded parameter pack, but
6620 /// which has already been substituted, attempt to determine the number of
6621 /// elements that will be produced once this argument is fully-expanded.
6623 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6624 /// avoid actually expanding the pack where possible.
6625 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6627 //===--------------------------------------------------------------------===//
6628 // C++ Template Argument Deduction (C++ [temp.deduct])
6629 //===--------------------------------------------------------------------===//
6631 /// Adjust the type \p ArgFunctionType to match the calling convention,
6632 /// noreturn, and optionally the exception specification of \p FunctionType.
6633 /// Deduction often wants to ignore these properties when matching function
6635 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6636 bool AdjustExceptionSpec = false);
6638 /// \brief Describes the result of template argument deduction.
6640 /// The TemplateDeductionResult enumeration describes the result of
6641 /// template argument deduction, as returned from
6642 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6643 /// structure provides additional information about the results of
6644 /// template argument deduction, e.g., the deduced template argument
6645 /// list (if successful) or the specific template parameters or
6646 /// deduced arguments that were involved in the failure.
6647 enum TemplateDeductionResult {
6648 /// \brief Template argument deduction was successful.
6650 /// \brief The declaration was invalid; do nothing.
6652 /// \brief Template argument deduction exceeded the maximum template
6653 /// instantiation depth (which has already been diagnosed).
6654 TDK_InstantiationDepth,
6655 /// \brief Template argument deduction did not deduce a value
6656 /// for every template parameter.
6658 /// \brief Template argument deduction produced inconsistent
6659 /// deduced values for the given template parameter.
6661 /// \brief Template argument deduction failed due to inconsistent
6662 /// cv-qualifiers on a template parameter type that would
6663 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6664 /// but were given a non-const "X".
6666 /// \brief Substitution of the deduced template argument values
6667 /// resulted in an error.
6668 TDK_SubstitutionFailure,
6669 /// \brief After substituting deduced template arguments, a dependent
6670 /// parameter type did not match the corresponding argument.
6671 TDK_DeducedMismatch,
6672 /// \brief After substituting deduced template arguments, an element of
6673 /// a dependent parameter type did not match the corresponding element
6674 /// of the corresponding argument (when deducing from an initializer list).
6675 TDK_DeducedMismatchNested,
6676 /// \brief A non-depnedent component of the parameter did not match the
6677 /// corresponding component of the argument.
6678 TDK_NonDeducedMismatch,
6679 /// \brief When performing template argument deduction for a function
6680 /// template, there were too many call arguments.
6681 TDK_TooManyArguments,
6682 /// \brief When performing template argument deduction for a function
6683 /// template, there were too few call arguments.
6684 TDK_TooFewArguments,
6685 /// \brief The explicitly-specified template arguments were not valid
6686 /// template arguments for the given template.
6687 TDK_InvalidExplicitArguments,
6688 /// \brief Checking non-dependent argument conversions failed.
6689 TDK_NonDependentConversionFailure,
6690 /// \brief Deduction failed; that's all we know.
6691 TDK_MiscellaneousDeductionFailure,
6692 /// \brief CUDA Target attributes do not match.
6693 TDK_CUDATargetMismatch
6696 TemplateDeductionResult
6697 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6698 const TemplateArgumentList &TemplateArgs,
6699 sema::TemplateDeductionInfo &Info);
6701 TemplateDeductionResult
6702 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6703 const TemplateArgumentList &TemplateArgs,
6704 sema::TemplateDeductionInfo &Info);
6706 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6707 FunctionTemplateDecl *FunctionTemplate,
6708 TemplateArgumentListInfo &ExplicitTemplateArgs,
6709 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6710 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6711 sema::TemplateDeductionInfo &Info);
6713 /// brief A function argument from which we performed template argument
6714 // deduction for a call.
6715 struct OriginalCallArg {
6716 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6717 unsigned ArgIdx, QualType OriginalArgType)
6718 : OriginalParamType(OriginalParamType),
6719 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6720 OriginalArgType(OriginalArgType) {}
6722 QualType OriginalParamType;
6723 bool DecomposedParam;
6725 QualType OriginalArgType;
6728 TemplateDeductionResult FinishTemplateArgumentDeduction(
6729 FunctionTemplateDecl *FunctionTemplate,
6730 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6731 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6732 sema::TemplateDeductionInfo &Info,
6733 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6734 bool PartialOverloading = false,
6735 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6737 TemplateDeductionResult DeduceTemplateArguments(
6738 FunctionTemplateDecl *FunctionTemplate,
6739 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6740 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6741 bool PartialOverloading,
6742 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6744 TemplateDeductionResult
6745 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6746 TemplateArgumentListInfo *ExplicitTemplateArgs,
6747 QualType ArgFunctionType,
6748 FunctionDecl *&Specialization,
6749 sema::TemplateDeductionInfo &Info,
6750 bool IsAddressOfFunction = false);
6752 TemplateDeductionResult
6753 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6755 CXXConversionDecl *&Specialization,
6756 sema::TemplateDeductionInfo &Info);
6758 TemplateDeductionResult
6759 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6760 TemplateArgumentListInfo *ExplicitTemplateArgs,
6761 FunctionDecl *&Specialization,
6762 sema::TemplateDeductionInfo &Info,
6763 bool IsAddressOfFunction = false);
6765 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6766 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6767 /// \brief Substitute Replacement for auto in TypeWithAuto
6768 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6769 QualType Replacement);
6770 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6771 /// \p Replacement. This does not retain any \c auto type sugar.
6772 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6774 /// \brief Result type of DeduceAutoType.
6775 enum DeduceAutoResult {
6778 DAR_FailedAlreadyDiagnosed
6782 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6783 Optional<unsigned> DependentDeductionDepth = None);
6785 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6786 Optional<unsigned> DependentDeductionDepth = None);
6787 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6788 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6789 bool Diagnose = true);
6791 /// \brief Declare implicit deduction guides for a class template if we've
6792 /// not already done so.
6793 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6794 SourceLocation Loc);
6796 QualType DeduceTemplateSpecializationFromInitializer(
6797 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6798 const InitializationKind &Kind, MultiExprArg Init);
6800 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6801 QualType Type, TypeSourceInfo *TSI,
6802 SourceRange Range, bool DirectInit,
6805 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6807 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6808 SourceLocation ReturnLoc,
6809 Expr *&RetExpr, AutoType *AT);
6811 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6812 FunctionTemplateDecl *FT2,
6814 TemplatePartialOrderingContext TPOC,
6815 unsigned NumCallArguments1,
6816 unsigned NumCallArguments2);
6817 UnresolvedSetIterator
6818 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6819 TemplateSpecCandidateSet &FailedCandidates,
6821 const PartialDiagnostic &NoneDiag,
6822 const PartialDiagnostic &AmbigDiag,
6823 const PartialDiagnostic &CandidateDiag,
6824 bool Complain = true, QualType TargetType = QualType());
6826 ClassTemplatePartialSpecializationDecl *
6827 getMoreSpecializedPartialSpecialization(
6828 ClassTemplatePartialSpecializationDecl *PS1,
6829 ClassTemplatePartialSpecializationDecl *PS2,
6830 SourceLocation Loc);
6832 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6833 sema::TemplateDeductionInfo &Info);
6835 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6836 VarTemplatePartialSpecializationDecl *PS1,
6837 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6839 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6840 sema::TemplateDeductionInfo &Info);
6842 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6843 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6845 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6848 llvm::SmallBitVector &Used);
6849 void MarkDeducedTemplateParameters(
6850 const FunctionTemplateDecl *FunctionTemplate,
6851 llvm::SmallBitVector &Deduced) {
6852 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6854 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6855 const FunctionTemplateDecl *FunctionTemplate,
6856 llvm::SmallBitVector &Deduced);
6858 //===--------------------------------------------------------------------===//
6859 // C++ Template Instantiation
6862 MultiLevelTemplateArgumentList
6863 getTemplateInstantiationArgs(NamedDecl *D,
6864 const TemplateArgumentList *Innermost = nullptr,
6865 bool RelativeToPrimary = false,
6866 const FunctionDecl *Pattern = nullptr);
6868 /// A context in which code is being synthesized (where a source location
6869 /// alone is not sufficient to identify the context). This covers template
6870 /// instantiation and various forms of implicitly-generated functions.
6871 struct CodeSynthesisContext {
6872 /// \brief The kind of template instantiation we are performing
6873 enum SynthesisKind {
6874 /// We are instantiating a template declaration. The entity is
6875 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6876 TemplateInstantiation,
6878 /// We are instantiating a default argument for a template
6879 /// parameter. The Entity is the template parameter whose argument is
6880 /// being instantiated, the Template is the template, and the
6881 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6883 DefaultTemplateArgumentInstantiation,
6885 /// We are instantiating a default argument for a function.
6886 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6887 /// provides the template arguments as specified.
6888 DefaultFunctionArgumentInstantiation,
6890 /// We are substituting explicit template arguments provided for
6891 /// a function template. The entity is a FunctionTemplateDecl.
6892 ExplicitTemplateArgumentSubstitution,
6894 /// We are substituting template argument determined as part of
6895 /// template argument deduction for either a class template
6896 /// partial specialization or a function template. The
6897 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6899 DeducedTemplateArgumentSubstitution,
6901 /// We are substituting prior template arguments into a new
6902 /// template parameter. The template parameter itself is either a
6903 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6904 PriorTemplateArgumentSubstitution,
6906 /// We are checking the validity of a default template argument that
6907 /// has been used when naming a template-id.
6908 DefaultTemplateArgumentChecking,
6910 /// We are instantiating the exception specification for a function
6911 /// template which was deferred until it was needed.
6912 ExceptionSpecInstantiation,
6914 /// We are declaring an implicit special member function.
6915 DeclaringSpecialMember,
6918 /// \brief Was the enclosing context a non-instantiation SFINAE context?
6919 bool SavedInNonInstantiationSFINAEContext;
6921 /// \brief The point of instantiation or synthesis within the source code.
6922 SourceLocation PointOfInstantiation;
6924 /// \brief The entity that is being synthesized.
6927 /// \brief The template (or partial specialization) in which we are
6928 /// performing the instantiation, for substitutions of prior template
6930 NamedDecl *Template;
6932 /// \brief The list of template arguments we are substituting, if they
6933 /// are not part of the entity.
6934 const TemplateArgument *TemplateArgs;
6936 // FIXME: Wrap this union around more members, or perhaps store the
6937 // kind-specific members in the RAII object owning the context.
6939 /// \brief The number of template arguments in TemplateArgs.
6940 unsigned NumTemplateArgs;
6942 /// \brief The special member being declared or defined.
6943 CXXSpecialMember SpecialMember;
6946 ArrayRef<TemplateArgument> template_arguments() const {
6947 assert(Kind != DeclaringSpecialMember);
6948 return {TemplateArgs, NumTemplateArgs};
6951 /// \brief The template deduction info object associated with the
6952 /// substitution or checking of explicit or deduced template arguments.
6953 sema::TemplateDeductionInfo *DeductionInfo;
6955 /// \brief The source range that covers the construct that cause
6956 /// the instantiation, e.g., the template-id that causes a class
6957 /// template instantiation.
6958 SourceRange InstantiationRange;
6960 CodeSynthesisContext()
6961 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
6962 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6964 /// \brief Determines whether this template is an actual instantiation
6965 /// that should be counted toward the maximum instantiation depth.
6966 bool isInstantiationRecord() const;
6969 /// \brief List of active code synthesis contexts.
6971 /// This vector is treated as a stack. As synthesis of one entity requires
6972 /// synthesis of another, additional contexts are pushed onto the stack.
6973 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
6975 /// Specializations whose definitions are currently being instantiated.
6976 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
6978 /// Non-dependent types used in templates that have already been instantiated
6979 /// by some template instantiation.
6980 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
6982 /// \brief Extra modules inspected when performing a lookup during a template
6983 /// instantiation. Computed lazily.
6984 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
6986 /// \brief Cache of additional modules that should be used for name lookup
6987 /// within the current template instantiation. Computed lazily; use
6988 /// getLookupModules() to get a complete set.
6989 llvm::DenseSet<Module*> LookupModulesCache;
6991 /// \brief Get the set of additional modules that should be checked during
6992 /// name lookup. A module and its imports become visible when instanting a
6993 /// template defined within it.
6994 llvm::DenseSet<Module*> &getLookupModules();
6996 /// \brief Map from the most recent declaration of a namespace to the most
6997 /// recent visible declaration of that namespace.
6998 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7000 /// \brief Whether we are in a SFINAE context that is not associated with
7001 /// template instantiation.
7003 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7004 /// of a template instantiation or template argument deduction.
7005 bool InNonInstantiationSFINAEContext;
7007 /// \brief The number of \p CodeSynthesisContexts that are not template
7008 /// instantiations and, therefore, should not be counted as part of the
7009 /// instantiation depth.
7011 /// When the instantiation depth reaches the user-configurable limit
7012 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7013 // FIXME: Should we have a similar limit for other forms of synthesis?
7014 unsigned NonInstantiationEntries;
7016 /// \brief The depth of the context stack at the point when the most recent
7017 /// error or warning was produced.
7019 /// This value is used to suppress printing of redundant context stacks
7020 /// when there are multiple errors or warnings in the same instantiation.
7021 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7022 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7024 /// \brief The current index into pack expansion arguments that will be
7025 /// used for substitution of parameter packs.
7027 /// The pack expansion index will be -1 to indicate that parameter packs
7028 /// should be instantiated as themselves. Otherwise, the index specifies
7029 /// which argument within the parameter pack will be used for substitution.
7030 int ArgumentPackSubstitutionIndex;
7032 /// \brief RAII object used to change the argument pack substitution index
7033 /// within a \c Sema object.
7035 /// See \c ArgumentPackSubstitutionIndex for more information.
7036 class ArgumentPackSubstitutionIndexRAII {
7038 int OldSubstitutionIndex;
7041 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7042 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7043 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7046 ~ArgumentPackSubstitutionIndexRAII() {
7047 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7051 friend class ArgumentPackSubstitutionRAII;
7053 /// \brief For each declaration that involved template argument deduction, the
7054 /// set of diagnostics that were suppressed during that template argument
7057 /// FIXME: Serialize this structure to the AST file.
7058 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7059 SuppressedDiagnosticsMap;
7060 SuppressedDiagnosticsMap SuppressedDiagnostics;
7062 /// \brief A stack object to be created when performing template
7065 /// Construction of an object of type \c InstantiatingTemplate
7066 /// pushes the current instantiation onto the stack of active
7067 /// instantiations. If the size of this stack exceeds the maximum
7068 /// number of recursive template instantiations, construction
7069 /// produces an error and evaluates true.
7071 /// Destruction of this object will pop the named instantiation off
7073 struct InstantiatingTemplate {
7074 /// \brief Note that we are instantiating a class template,
7075 /// function template, variable template, alias template,
7076 /// or a member thereof.
7077 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7079 SourceRange InstantiationRange = SourceRange());
7081 struct ExceptionSpecification {};
7082 /// \brief Note that we are instantiating an exception specification
7083 /// of a function template.
7084 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7085 FunctionDecl *Entity, ExceptionSpecification,
7086 SourceRange InstantiationRange = SourceRange());
7088 /// \brief Note that we are instantiating a default argument in a
7090 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7091 TemplateParameter Param, TemplateDecl *Template,
7092 ArrayRef<TemplateArgument> TemplateArgs,
7093 SourceRange InstantiationRange = SourceRange());
7095 /// \brief Note that we are substituting either explicitly-specified or
7096 /// deduced template arguments during function template argument deduction.
7097 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7098 FunctionTemplateDecl *FunctionTemplate,
7099 ArrayRef<TemplateArgument> TemplateArgs,
7100 CodeSynthesisContext::SynthesisKind Kind,
7101 sema::TemplateDeductionInfo &DeductionInfo,
7102 SourceRange InstantiationRange = SourceRange());
7104 /// \brief Note that we are instantiating as part of template
7105 /// argument deduction for a class template declaration.
7106 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7107 TemplateDecl *Template,
7108 ArrayRef<TemplateArgument> TemplateArgs,
7109 sema::TemplateDeductionInfo &DeductionInfo,
7110 SourceRange InstantiationRange = SourceRange());
7112 /// \brief Note that we are instantiating as part of template
7113 /// argument deduction for a class template partial
7115 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7116 ClassTemplatePartialSpecializationDecl *PartialSpec,
7117 ArrayRef<TemplateArgument> TemplateArgs,
7118 sema::TemplateDeductionInfo &DeductionInfo,
7119 SourceRange InstantiationRange = SourceRange());
7121 /// \brief Note that we are instantiating as part of template
7122 /// argument deduction for a variable template partial
7124 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7125 VarTemplatePartialSpecializationDecl *PartialSpec,
7126 ArrayRef<TemplateArgument> TemplateArgs,
7127 sema::TemplateDeductionInfo &DeductionInfo,
7128 SourceRange InstantiationRange = SourceRange());
7130 /// \brief Note that we are instantiating a default argument for a function
7132 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7134 ArrayRef<TemplateArgument> TemplateArgs,
7135 SourceRange InstantiationRange = SourceRange());
7137 /// \brief Note that we are substituting prior template arguments into a
7138 /// non-type parameter.
7139 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7140 NamedDecl *Template,
7141 NonTypeTemplateParmDecl *Param,
7142 ArrayRef<TemplateArgument> TemplateArgs,
7143 SourceRange InstantiationRange);
7145 /// \brief Note that we are substituting prior template arguments into a
7146 /// template template parameter.
7147 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7148 NamedDecl *Template,
7149 TemplateTemplateParmDecl *Param,
7150 ArrayRef<TemplateArgument> TemplateArgs,
7151 SourceRange InstantiationRange);
7153 /// \brief Note that we are checking the default template argument
7154 /// against the template parameter for a given template-id.
7155 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7156 TemplateDecl *Template,
7158 ArrayRef<TemplateArgument> TemplateArgs,
7159 SourceRange InstantiationRange);
7162 /// \brief Note that we have finished instantiating this template.
7165 ~InstantiatingTemplate() { Clear(); }
7167 /// \brief Determines whether we have exceeded the maximum
7168 /// recursive template instantiations.
7169 bool isInvalid() const { return Invalid; }
7171 /// \brief Determine whether we are already instantiating this
7172 /// specialization in some surrounding active instantiation.
7173 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7178 bool AlreadyInstantiating;
7179 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7180 SourceRange InstantiationRange);
7182 InstantiatingTemplate(
7183 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7184 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7185 Decl *Entity, NamedDecl *Template = nullptr,
7186 ArrayRef<TemplateArgument> TemplateArgs = None,
7187 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7189 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7191 InstantiatingTemplate&
7192 operator=(const InstantiatingTemplate&) = delete;
7195 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7196 void popCodeSynthesisContext();
7198 /// Determine whether we are currently performing template instantiation.
7199 bool inTemplateInstantiation() const {
7200 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7203 void PrintContextStack() {
7204 if (!CodeSynthesisContexts.empty() &&
7205 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7206 PrintInstantiationStack();
7207 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7210 void PrintInstantiationStack();
7212 /// \brief Determines whether we are currently in a context where
7213 /// template argument substitution failures are not considered
7216 /// \returns An empty \c Optional if we're not in a SFINAE context.
7217 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7218 /// template-deduction context object, which can be used to capture
7219 /// diagnostics that will be suppressed.
7220 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7222 /// \brief Determines whether we are currently in a context that
7223 /// is not evaluated as per C++ [expr] p5.
7224 bool isUnevaluatedContext() const {
7225 assert(!ExprEvalContexts.empty() &&
7226 "Must be in an expression evaluation context");
7227 return ExprEvalContexts.back().isUnevaluated();
7230 /// \brief RAII class used to determine whether SFINAE has
7231 /// trapped any errors that occur during template argument
7235 unsigned PrevSFINAEErrors;
7236 bool PrevInNonInstantiationSFINAEContext;
7237 bool PrevAccessCheckingSFINAE;
7240 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7241 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7242 PrevInNonInstantiationSFINAEContext(
7243 SemaRef.InNonInstantiationSFINAEContext),
7244 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7246 if (!SemaRef.isSFINAEContext())
7247 SemaRef.InNonInstantiationSFINAEContext = true;
7248 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7252 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7253 SemaRef.InNonInstantiationSFINAEContext
7254 = PrevInNonInstantiationSFINAEContext;
7255 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7258 /// \brief Determine whether any SFINAE errors have been trapped.
7259 bool hasErrorOccurred() const {
7260 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7264 /// \brief RAII class used to indicate that we are performing provisional
7265 /// semantic analysis to determine the validity of a construct, so
7266 /// typo-correction and diagnostics in the immediate context (not within
7267 /// implicitly-instantiated templates) should be suppressed.
7268 class TentativeAnalysisScope {
7270 // FIXME: Using a SFINAETrap for this is a hack.
7272 bool PrevDisableTypoCorrection;
7274 explicit TentativeAnalysisScope(Sema &SemaRef)
7275 : SemaRef(SemaRef), Trap(SemaRef, true),
7276 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7277 SemaRef.DisableTypoCorrection = true;
7279 ~TentativeAnalysisScope() {
7280 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7284 /// \brief The current instantiation scope used to store local
7286 LocalInstantiationScope *CurrentInstantiationScope;
7288 /// \brief Tracks whether we are in a context where typo correction is
7290 bool DisableTypoCorrection;
7292 /// \brief The number of typos corrected by CorrectTypo.
7293 unsigned TyposCorrected;
7295 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7296 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7298 /// \brief A cache containing identifiers for which typo correction failed and
7299 /// their locations, so that repeated attempts to correct an identifier in a
7300 /// given location are ignored if typo correction already failed for it.
7301 IdentifierSourceLocations TypoCorrectionFailures;
7303 /// \brief Worker object for performing CFG-based warnings.
7304 sema::AnalysisBasedWarnings AnalysisWarnings;
7305 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7307 /// \brief An entity for which implicit template instantiation is required.
7309 /// The source location associated with the declaration is the first place in
7310 /// the source code where the declaration was "used". It is not necessarily
7311 /// the point of instantiation (which will be either before or after the
7312 /// namespace-scope declaration that triggered this implicit instantiation),
7313 /// However, it is the location that diagnostics should generally refer to,
7314 /// because users will need to know what code triggered the instantiation.
7315 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7317 /// \brief The queue of implicit template instantiations that are required
7318 /// but have not yet been performed.
7319 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7321 class SavePendingInstantiationsAndVTableUsesRAII {
7323 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7324 : S(S), Enabled(Enabled) {
7325 if (!Enabled) return;
7327 SavedPendingInstantiations.swap(S.PendingInstantiations);
7328 SavedVTableUses.swap(S.VTableUses);
7331 ~SavePendingInstantiationsAndVTableUsesRAII() {
7332 if (!Enabled) return;
7334 // Restore the set of pending vtables.
7335 assert(S.VTableUses.empty() &&
7336 "VTableUses should be empty before it is discarded.");
7337 S.VTableUses.swap(SavedVTableUses);
7339 // Restore the set of pending implicit instantiations.
7340 assert(S.PendingInstantiations.empty() &&
7341 "PendingInstantiations should be empty before it is discarded.");
7342 S.PendingInstantiations.swap(SavedPendingInstantiations);
7347 SmallVector<VTableUse, 16> SavedVTableUses;
7348 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7352 /// \brief The queue of implicit template instantiations that are required
7353 /// and must be performed within the current local scope.
7355 /// This queue is only used for member functions of local classes in
7356 /// templates, which must be instantiated in the same scope as their
7357 /// enclosing function, so that they can reference function-local
7358 /// types, static variables, enumerators, etc.
7359 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7361 class SavePendingLocalImplicitInstantiationsRAII {
7363 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7364 SavedPendingLocalImplicitInstantiations.swap(
7365 S.PendingLocalImplicitInstantiations);
7368 ~SavePendingLocalImplicitInstantiationsRAII() {
7369 assert(S.PendingLocalImplicitInstantiations.empty() &&
7370 "there shouldn't be any pending local implicit instantiations");
7371 SavedPendingLocalImplicitInstantiations.swap(
7372 S.PendingLocalImplicitInstantiations);
7377 std::deque<PendingImplicitInstantiation>
7378 SavedPendingLocalImplicitInstantiations;
7381 /// A helper class for building up ExtParameterInfos.
7382 class ExtParameterInfoBuilder {
7383 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7384 bool HasInteresting = false;
7387 /// Set the ExtParameterInfo for the parameter at the given index,
7389 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7390 assert(Infos.size() <= index);
7391 Infos.resize(index);
7392 Infos.push_back(info);
7394 if (!HasInteresting)
7395 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7398 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7399 /// ExtParameterInfo array we've built up.
7400 const FunctionProtoType::ExtParameterInfo *
7401 getPointerOrNull(unsigned numParams) {
7402 if (!HasInteresting) return nullptr;
7403 Infos.resize(numParams);
7404 return Infos.data();
7408 void PerformPendingInstantiations(bool LocalOnly = false);
7410 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7411 const MultiLevelTemplateArgumentList &TemplateArgs,
7412 SourceLocation Loc, DeclarationName Entity,
7413 bool AllowDeducedTST = false);
7415 QualType SubstType(QualType T,
7416 const MultiLevelTemplateArgumentList &TemplateArgs,
7417 SourceLocation Loc, DeclarationName Entity);
7419 TypeSourceInfo *SubstType(TypeLoc TL,
7420 const MultiLevelTemplateArgumentList &TemplateArgs,
7421 SourceLocation Loc, DeclarationName Entity);
7423 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7424 const MultiLevelTemplateArgumentList &TemplateArgs,
7426 DeclarationName Entity,
7427 CXXRecordDecl *ThisContext,
7428 unsigned ThisTypeQuals);
7429 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7430 const MultiLevelTemplateArgumentList &Args);
7431 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7432 const MultiLevelTemplateArgumentList &TemplateArgs,
7433 int indexAdjustment,
7434 Optional<unsigned> NumExpansions,
7435 bool ExpectParameterPack);
7436 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7437 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7438 const MultiLevelTemplateArgumentList &TemplateArgs,
7439 SmallVectorImpl<QualType> &ParamTypes,
7440 SmallVectorImpl<ParmVarDecl *> *OutParams,
7441 ExtParameterInfoBuilder &ParamInfos);
7442 ExprResult SubstExpr(Expr *E,
7443 const MultiLevelTemplateArgumentList &TemplateArgs);
7445 /// \brief Substitute the given template arguments into a list of
7446 /// expressions, expanding pack expansions if required.
7448 /// \param Exprs The list of expressions to substitute into.
7450 /// \param IsCall Whether this is some form of call, in which case
7451 /// default arguments will be dropped.
7453 /// \param TemplateArgs The set of template arguments to substitute.
7455 /// \param Outputs Will receive all of the substituted arguments.
7457 /// \returns true if an error occurred, false otherwise.
7458 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7459 const MultiLevelTemplateArgumentList &TemplateArgs,
7460 SmallVectorImpl<Expr *> &Outputs);
7462 StmtResult SubstStmt(Stmt *S,
7463 const MultiLevelTemplateArgumentList &TemplateArgs);
7465 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7466 const MultiLevelTemplateArgumentList &TemplateArgs);
7468 ExprResult SubstInitializer(Expr *E,
7469 const MultiLevelTemplateArgumentList &TemplateArgs,
7470 bool CXXDirectInit);
7473 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7474 CXXRecordDecl *Pattern,
7475 const MultiLevelTemplateArgumentList &TemplateArgs);
7478 InstantiateClass(SourceLocation PointOfInstantiation,
7479 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7480 const MultiLevelTemplateArgumentList &TemplateArgs,
7481 TemplateSpecializationKind TSK,
7482 bool Complain = true);
7484 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7485 EnumDecl *Instantiation, EnumDecl *Pattern,
7486 const MultiLevelTemplateArgumentList &TemplateArgs,
7487 TemplateSpecializationKind TSK);
7489 bool InstantiateInClassInitializer(
7490 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7491 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7493 struct LateInstantiatedAttribute {
7494 const Attr *TmplAttr;
7495 LocalInstantiationScope *Scope;
7498 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7500 : TmplAttr(A), Scope(S), NewDecl(D)
7503 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7505 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7506 const Decl *Pattern, Decl *Inst,
7507 LateInstantiatedAttrVec *LateAttrs = nullptr,
7508 LocalInstantiationScope *OuterMostScope = nullptr);
7511 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7512 const Decl *Pattern, Decl *Inst,
7513 LateInstantiatedAttrVec *LateAttrs = nullptr,
7514 LocalInstantiationScope *OuterMostScope = nullptr);
7517 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7518 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7519 TemplateSpecializationKind TSK,
7520 bool Complain = true);
7522 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7523 CXXRecordDecl *Instantiation,
7524 const MultiLevelTemplateArgumentList &TemplateArgs,
7525 TemplateSpecializationKind TSK);
7527 void InstantiateClassTemplateSpecializationMembers(
7528 SourceLocation PointOfInstantiation,
7529 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7530 TemplateSpecializationKind TSK);
7532 NestedNameSpecifierLoc
7533 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7534 const MultiLevelTemplateArgumentList &TemplateArgs);
7537 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7538 const MultiLevelTemplateArgumentList &TemplateArgs);
7540 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7542 const MultiLevelTemplateArgumentList &TemplateArgs);
7543 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7544 TemplateArgumentListInfo &Result,
7545 const MultiLevelTemplateArgumentList &TemplateArgs);
7547 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7548 FunctionDecl *Function);
7549 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7550 FunctionDecl *Function,
7551 bool Recursive = false,
7552 bool DefinitionRequired = false,
7553 bool AtEndOfTU = false);
7554 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7555 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7556 const TemplateArgumentList &TemplateArgList,
7557 const TemplateArgumentListInfo &TemplateArgsInfo,
7558 SmallVectorImpl<TemplateArgument> &Converted,
7559 SourceLocation PointOfInstantiation, void *InsertPos,
7560 LateInstantiatedAttrVec *LateAttrs = nullptr,
7561 LocalInstantiationScope *StartingScope = nullptr);
7562 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7563 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7564 const MultiLevelTemplateArgumentList &TemplateArgs);
7566 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7567 const MultiLevelTemplateArgumentList &TemplateArgs,
7568 LateInstantiatedAttrVec *LateAttrs,
7570 LocalInstantiationScope *StartingScope,
7571 bool InstantiatingVarTemplate = false);
7572 void InstantiateVariableInitializer(
7573 VarDecl *Var, VarDecl *OldVar,
7574 const MultiLevelTemplateArgumentList &TemplateArgs);
7575 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7576 VarDecl *Var, bool Recursive = false,
7577 bool DefinitionRequired = false,
7578 bool AtEndOfTU = false);
7579 void InstantiateStaticDataMemberDefinition(
7580 SourceLocation PointOfInstantiation,
7582 bool Recursive = false,
7583 bool DefinitionRequired = false);
7585 void InstantiateMemInitializers(CXXConstructorDecl *New,
7586 const CXXConstructorDecl *Tmpl,
7587 const MultiLevelTemplateArgumentList &TemplateArgs);
7589 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7590 const MultiLevelTemplateArgumentList &TemplateArgs);
7591 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7592 const MultiLevelTemplateArgumentList &TemplateArgs);
7594 // Objective-C declarations.
7595 enum ObjCContainerKind {
7602 OCK_CategoryImplementation
7604 ObjCContainerKind getObjCContainerKind() const;
7606 DeclResult actOnObjCTypeParam(Scope *S,
7607 ObjCTypeParamVariance variance,
7608 SourceLocation varianceLoc,
7610 IdentifierInfo *paramName,
7611 SourceLocation paramLoc,
7612 SourceLocation colonLoc,
7613 ParsedType typeBound);
7615 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7616 ArrayRef<Decl *> typeParams,
7617 SourceLocation rAngleLoc);
7618 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7620 Decl *ActOnStartClassInterface(Scope *S,
7621 SourceLocation AtInterfaceLoc,
7622 IdentifierInfo *ClassName,
7623 SourceLocation ClassLoc,
7624 ObjCTypeParamList *typeParamList,
7625 IdentifierInfo *SuperName,
7626 SourceLocation SuperLoc,
7627 ArrayRef<ParsedType> SuperTypeArgs,
7628 SourceRange SuperTypeArgsRange,
7629 Decl * const *ProtoRefs,
7630 unsigned NumProtoRefs,
7631 const SourceLocation *ProtoLocs,
7632 SourceLocation EndProtoLoc,
7633 AttributeList *AttrList);
7635 void ActOnSuperClassOfClassInterface(Scope *S,
7636 SourceLocation AtInterfaceLoc,
7637 ObjCInterfaceDecl *IDecl,
7638 IdentifierInfo *ClassName,
7639 SourceLocation ClassLoc,
7640 IdentifierInfo *SuperName,
7641 SourceLocation SuperLoc,
7642 ArrayRef<ParsedType> SuperTypeArgs,
7643 SourceRange SuperTypeArgsRange);
7645 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7646 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7647 IdentifierInfo *SuperName,
7648 SourceLocation SuperLoc);
7650 Decl *ActOnCompatibilityAlias(
7651 SourceLocation AtCompatibilityAliasLoc,
7652 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7653 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7655 bool CheckForwardProtocolDeclarationForCircularDependency(
7656 IdentifierInfo *PName,
7657 SourceLocation &PLoc, SourceLocation PrevLoc,
7658 const ObjCList<ObjCProtocolDecl> &PList);
7660 Decl *ActOnStartProtocolInterface(
7661 SourceLocation AtProtoInterfaceLoc,
7662 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7663 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7664 const SourceLocation *ProtoLocs,
7665 SourceLocation EndProtoLoc,
7666 AttributeList *AttrList);
7668 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7669 IdentifierInfo *ClassName,
7670 SourceLocation ClassLoc,
7671 ObjCTypeParamList *typeParamList,
7672 IdentifierInfo *CategoryName,
7673 SourceLocation CategoryLoc,
7674 Decl * const *ProtoRefs,
7675 unsigned NumProtoRefs,
7676 const SourceLocation *ProtoLocs,
7677 SourceLocation EndProtoLoc,
7678 AttributeList *AttrList);
7680 Decl *ActOnStartClassImplementation(
7681 SourceLocation AtClassImplLoc,
7682 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7683 IdentifierInfo *SuperClassname,
7684 SourceLocation SuperClassLoc);
7686 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7687 IdentifierInfo *ClassName,
7688 SourceLocation ClassLoc,
7689 IdentifierInfo *CatName,
7690 SourceLocation CatLoc);
7692 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7693 ArrayRef<Decl *> Decls);
7695 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7696 IdentifierInfo **IdentList,
7697 SourceLocation *IdentLocs,
7698 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7701 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7702 ArrayRef<IdentifierLocPair> IdentList,
7703 AttributeList *attrList);
7705 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7706 ArrayRef<IdentifierLocPair> ProtocolId,
7707 SmallVectorImpl<Decl *> &Protocols);
7709 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7710 SourceLocation ProtocolLoc,
7711 IdentifierInfo *TypeArgId,
7712 SourceLocation TypeArgLoc,
7713 bool SelectProtocolFirst = false);
7715 /// Given a list of identifiers (and their locations), resolve the
7716 /// names to either Objective-C protocol qualifiers or type
7717 /// arguments, as appropriate.
7718 void actOnObjCTypeArgsOrProtocolQualifiers(
7720 ParsedType baseType,
7721 SourceLocation lAngleLoc,
7722 ArrayRef<IdentifierInfo *> identifiers,
7723 ArrayRef<SourceLocation> identifierLocs,
7724 SourceLocation rAngleLoc,
7725 SourceLocation &typeArgsLAngleLoc,
7726 SmallVectorImpl<ParsedType> &typeArgs,
7727 SourceLocation &typeArgsRAngleLoc,
7728 SourceLocation &protocolLAngleLoc,
7729 SmallVectorImpl<Decl *> &protocols,
7730 SourceLocation &protocolRAngleLoc,
7731 bool warnOnIncompleteProtocols);
7733 /// Build a an Objective-C protocol-qualified 'id' type where no
7734 /// base type was specified.
7735 TypeResult actOnObjCProtocolQualifierType(
7736 SourceLocation lAngleLoc,
7737 ArrayRef<Decl *> protocols,
7738 ArrayRef<SourceLocation> protocolLocs,
7739 SourceLocation rAngleLoc);
7741 /// Build a specialized and/or protocol-qualified Objective-C type.
7742 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7745 ParsedType BaseType,
7746 SourceLocation TypeArgsLAngleLoc,
7747 ArrayRef<ParsedType> TypeArgs,
7748 SourceLocation TypeArgsRAngleLoc,
7749 SourceLocation ProtocolLAngleLoc,
7750 ArrayRef<Decl *> Protocols,
7751 ArrayRef<SourceLocation> ProtocolLocs,
7752 SourceLocation ProtocolRAngleLoc);
7754 /// Build an Objective-C type parameter type.
7755 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7756 SourceLocation ProtocolLAngleLoc,
7757 ArrayRef<ObjCProtocolDecl *> Protocols,
7758 ArrayRef<SourceLocation> ProtocolLocs,
7759 SourceLocation ProtocolRAngleLoc,
7760 bool FailOnError = false);
7762 /// Build an Objective-C object pointer type.
7763 QualType BuildObjCObjectType(QualType BaseType,
7765 SourceLocation TypeArgsLAngleLoc,
7766 ArrayRef<TypeSourceInfo *> TypeArgs,
7767 SourceLocation TypeArgsRAngleLoc,
7768 SourceLocation ProtocolLAngleLoc,
7769 ArrayRef<ObjCProtocolDecl *> Protocols,
7770 ArrayRef<SourceLocation> ProtocolLocs,
7771 SourceLocation ProtocolRAngleLoc,
7772 bool FailOnError = false);
7774 /// Check the application of the Objective-C '__kindof' qualifier to
7776 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7778 /// Ensure attributes are consistent with type.
7779 /// \param [in, out] Attributes The attributes to check; they will
7780 /// be modified to be consistent with \p PropertyTy.
7781 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7783 unsigned &Attributes,
7784 bool propertyInPrimaryClass);
7786 /// Process the specified property declaration and create decls for the
7787 /// setters and getters as needed.
7788 /// \param property The property declaration being processed
7789 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7792 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7793 ObjCPropertyDecl *SuperProperty,
7794 const IdentifierInfo *Name,
7795 bool OverridingProtocolProperty);
7797 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7798 ObjCInterfaceDecl *ID);
7800 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7801 ArrayRef<Decl *> allMethods = None,
7802 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7804 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7805 SourceLocation LParenLoc,
7806 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7807 Selector GetterSel, Selector SetterSel,
7808 tok::ObjCKeywordKind MethodImplKind,
7809 DeclContext *lexicalDC = nullptr);
7811 Decl *ActOnPropertyImplDecl(Scope *S,
7812 SourceLocation AtLoc,
7813 SourceLocation PropertyLoc,
7815 IdentifierInfo *PropertyId,
7816 IdentifierInfo *PropertyIvar,
7817 SourceLocation PropertyIvarLoc,
7818 ObjCPropertyQueryKind QueryKind);
7820 enum ObjCSpecialMethodKind {
7826 OSMK_NonRetainingInit
7829 struct ObjCArgInfo {
7830 IdentifierInfo *Name;
7831 SourceLocation NameLoc;
7832 // The Type is null if no type was specified, and the DeclSpec is invalid
7835 ObjCDeclSpec DeclSpec;
7837 /// ArgAttrs - Attribute list for this argument.
7838 AttributeList *ArgAttrs;
7841 Decl *ActOnMethodDeclaration(
7843 SourceLocation BeginLoc, // location of the + or -.
7844 SourceLocation EndLoc, // location of the ; or {.
7845 tok::TokenKind MethodType,
7846 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7847 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7848 // optional arguments. The number of types/arguments is obtained
7849 // from the Sel.getNumArgs().
7850 ObjCArgInfo *ArgInfo,
7851 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7852 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7853 bool isVariadic, bool MethodDefinition);
7855 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7856 const ObjCObjectPointerType *OPT,
7858 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7861 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7862 bool inferObjCARCLifetime(ValueDecl *decl);
7865 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7867 SourceLocation OpLoc,
7868 DeclarationName MemberName,
7869 SourceLocation MemberLoc,
7870 SourceLocation SuperLoc, QualType SuperType,
7874 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7875 IdentifierInfo &propertyName,
7876 SourceLocation receiverNameLoc,
7877 SourceLocation propertyNameLoc);
7879 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7881 /// \brief Describes the kind of message expression indicated by a message
7882 /// send that starts with an identifier.
7883 enum ObjCMessageKind {
7884 /// \brief The message is sent to 'super'.
7886 /// \brief The message is an instance message.
7887 ObjCInstanceMessage,
7888 /// \brief The message is a class message, and the identifier is a type
7893 ObjCMessageKind getObjCMessageKind(Scope *S,
7894 IdentifierInfo *Name,
7895 SourceLocation NameLoc,
7897 bool HasTrailingDot,
7898 ParsedType &ReceiverType);
7900 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7902 SourceLocation LBracLoc,
7903 ArrayRef<SourceLocation> SelectorLocs,
7904 SourceLocation RBracLoc,
7907 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7908 QualType ReceiverType,
7909 SourceLocation SuperLoc,
7911 ObjCMethodDecl *Method,
7912 SourceLocation LBracLoc,
7913 ArrayRef<SourceLocation> SelectorLocs,
7914 SourceLocation RBracLoc,
7916 bool isImplicit = false);
7918 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7919 bool isSuperReceiver,
7922 ObjCMethodDecl *Method,
7925 ExprResult ActOnClassMessage(Scope *S,
7926 ParsedType Receiver,
7928 SourceLocation LBracLoc,
7929 ArrayRef<SourceLocation> SelectorLocs,
7930 SourceLocation RBracLoc,
7933 ExprResult BuildInstanceMessage(Expr *Receiver,
7934 QualType ReceiverType,
7935 SourceLocation SuperLoc,
7937 ObjCMethodDecl *Method,
7938 SourceLocation LBracLoc,
7939 ArrayRef<SourceLocation> SelectorLocs,
7940 SourceLocation RBracLoc,
7942 bool isImplicit = false);
7944 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7945 QualType ReceiverType,
7948 ObjCMethodDecl *Method,
7951 ExprResult ActOnInstanceMessage(Scope *S,
7954 SourceLocation LBracLoc,
7955 ArrayRef<SourceLocation> SelectorLocs,
7956 SourceLocation RBracLoc,
7959 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7960 ObjCBridgeCastKind Kind,
7961 SourceLocation BridgeKeywordLoc,
7962 TypeSourceInfo *TSInfo,
7965 ExprResult ActOnObjCBridgedCast(Scope *S,
7966 SourceLocation LParenLoc,
7967 ObjCBridgeCastKind Kind,
7968 SourceLocation BridgeKeywordLoc,
7970 SourceLocation RParenLoc,
7973 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7975 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7977 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7980 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7981 QualType DestType, QualType SrcType,
7982 ObjCInterfaceDecl *&RelatedClass,
7983 ObjCMethodDecl *&ClassMethod,
7984 ObjCMethodDecl *&InstanceMethod,
7985 TypedefNameDecl *&TDNDecl,
7986 bool CfToNs, bool Diagnose = true);
7988 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7989 QualType DestType, QualType SrcType,
7990 Expr *&SrcExpr, bool Diagnose = true);
7992 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7993 bool Diagnose = true);
7995 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7997 /// \brief Check whether the given new method is a valid override of the
7998 /// given overridden method, and set any properties that should be inherited.
7999 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8000 const ObjCMethodDecl *Overridden);
8002 /// \brief Describes the compatibility of a result type with its method.
8003 enum ResultTypeCompatibilityKind {
8009 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8010 ObjCInterfaceDecl *CurrentClass,
8011 ResultTypeCompatibilityKind RTC);
8013 enum PragmaOptionsAlignKind {
8014 POAK_Native, // #pragma options align=native
8015 POAK_Natural, // #pragma options align=natural
8016 POAK_Packed, // #pragma options align=packed
8017 POAK_Power, // #pragma options align=power
8018 POAK_Mac68k, // #pragma options align=mac68k
8019 POAK_Reset // #pragma options align=reset
8022 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8023 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8024 SourceLocation PragmaLoc);
8026 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8027 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8028 StringRef SlotLabel, Expr *Alignment);
8030 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8031 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8033 /// ActOnPragmaMSComment - Called on well formed
8034 /// \#pragma comment(kind, "arg").
8035 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8038 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8039 /// pointers_to_members(representation method[, general purpose
8040 /// representation]).
8041 void ActOnPragmaMSPointersToMembers(
8042 LangOptions::PragmaMSPointersToMembersKind Kind,
8043 SourceLocation PragmaLoc);
8045 /// \brief Called on well formed \#pragma vtordisp().
8046 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8047 SourceLocation PragmaLoc,
8048 MSVtorDispAttr::Mode Value);
8050 enum PragmaSectionKind {
8057 bool UnifySection(StringRef SectionName,
8059 DeclaratorDecl *TheDecl);
8060 bool UnifySection(StringRef SectionName,
8062 SourceLocation PragmaSectionLocation);
8064 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8065 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8066 PragmaMsStackAction Action,
8067 llvm::StringRef StackSlotLabel,
8068 StringLiteral *SegmentName,
8069 llvm::StringRef PragmaName);
8071 /// \brief Called on well formed \#pragma section().
8072 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8073 int SectionFlags, StringLiteral *SegmentName);
8075 /// \brief Called on well-formed \#pragma init_seg().
8076 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8077 StringLiteral *SegmentName);
8079 /// \brief Called on #pragma clang __debug dump II
8080 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8082 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8083 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8086 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8087 void ActOnPragmaUnused(const Token &Identifier,
8089 SourceLocation PragmaLoc);
8091 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8092 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8093 SourceLocation PragmaLoc);
8095 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8096 SourceLocation Loc);
8097 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8099 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8100 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8101 SourceLocation PragmaLoc,
8102 SourceLocation WeakNameLoc);
8104 /// ActOnPragmaRedefineExtname - Called on well formed
8105 /// \#pragma redefine_extname oldname newname.
8106 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8107 IdentifierInfo* AliasName,
8108 SourceLocation PragmaLoc,
8109 SourceLocation WeakNameLoc,
8110 SourceLocation AliasNameLoc);
8112 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8113 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8114 IdentifierInfo* AliasName,
8115 SourceLocation PragmaLoc,
8116 SourceLocation WeakNameLoc,
8117 SourceLocation AliasNameLoc);
8119 /// ActOnPragmaFPContract - Called on well formed
8120 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8121 /// \#pragma clang fp contract
8122 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8124 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8125 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8126 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8128 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8129 void AddMsStructLayoutForRecord(RecordDecl *RD);
8131 /// FreePackedContext - Deallocate and null out PackContext.
8132 void FreePackedContext();
8134 /// PushNamespaceVisibilityAttr - Note that we've entered a
8135 /// namespace with a visibility attribute.
8136 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8137 SourceLocation Loc);
8139 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8140 /// add an appropriate visibility attribute.
8141 void AddPushedVisibilityAttribute(Decl *RD);
8143 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8144 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8145 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8147 /// FreeVisContext - Deallocate and null out VisContext.
8148 void FreeVisContext();
8150 /// AddCFAuditedAttribute - Check whether we're currently within
8151 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8152 /// the appropriate attribute.
8153 void AddCFAuditedAttribute(Decl *D);
8155 /// \brief Called on well formed \#pragma clang optimize.
8156 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8158 /// \brief Get the location for the currently active "\#pragma clang optimize
8159 /// off". If this location is invalid, then the state of the pragma is "on".
8160 SourceLocation getOptimizeOffPragmaLocation() const {
8161 return OptimizeOffPragmaLocation;
8164 /// \brief Only called on function definitions; if there is a pragma in scope
8165 /// with the effect of a range-based optnone, consider marking the function
8166 /// with attribute optnone.
8167 void AddRangeBasedOptnone(FunctionDecl *FD);
8169 /// \brief Adds the 'optnone' attribute to the function declaration if there
8170 /// are no conflicts; Loc represents the location causing the 'optnone'
8171 /// attribute to be added (usually because of a pragma).
8172 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8174 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8175 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8176 unsigned SpellingListIndex, bool IsPackExpansion);
8177 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8178 unsigned SpellingListIndex, bool IsPackExpansion);
8180 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8182 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8183 unsigned SpellingListIndex);
8185 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8187 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8188 unsigned SpellingListIndex);
8190 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8192 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8193 unsigned SpellingListIndex);
8195 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8197 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8198 Expr *MinBlocks, unsigned SpellingListIndex);
8200 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8201 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8202 unsigned SpellingListIndex, bool InInstantiation = false);
8204 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8205 ParameterABI ABI, unsigned SpellingListIndex);
8207 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8208 unsigned SpellingListIndex, bool isNSConsumed,
8209 bool isTemplateInstantiation);
8211 //===--------------------------------------------------------------------===//
8212 // C++ Coroutines TS
8214 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8215 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8216 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8218 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8219 bool IsImplicit = false);
8220 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8221 UnresolvedLookupExpr* Lookup);
8222 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8223 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8224 bool IsImplicit = false);
8225 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8226 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8227 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8229 //===--------------------------------------------------------------------===//
8230 // OpenCL extensions.
8233 std::string CurrOpenCLExtension;
8234 /// Extensions required by an OpenCL type.
8235 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8236 /// Extensions required by an OpenCL declaration.
8237 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8239 llvm::StringRef getCurrentOpenCLExtension() const {
8240 return CurrOpenCLExtension;
8242 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8243 CurrOpenCLExtension = Ext;
8246 /// \brief Set OpenCL extensions for a type which can only be used when these
8247 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8248 /// \param Exts A space separated list of OpenCL extensions.
8249 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8251 /// \brief Set OpenCL extensions for a declaration which can only be
8252 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8254 /// \param Exts A space separated list of OpenCL extensions.
8255 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8257 /// \brief Set current OpenCL extensions for a type which can only be used
8258 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8259 /// empty, do nothing.
8260 void setCurrentOpenCLExtensionForType(QualType T);
8262 /// \brief Set current OpenCL extensions for a declaration which
8263 /// can only be used when these OpenCL extensions are enabled. If current
8264 /// OpenCL extension is empty, do nothing.
8265 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8267 bool isOpenCLDisabledDecl(Decl *FD);
8269 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8270 /// is disabled due to required OpenCL extensions being disabled. If so,
8271 /// emit diagnostics.
8272 /// \return true if type is disabled.
8273 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8275 /// \brief Check if declaration \p D used by expression \p E
8276 /// is disabled due to required OpenCL extensions being disabled. If so,
8277 /// emit diagnostics.
8278 /// \return true if type is disabled.
8279 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8281 //===--------------------------------------------------------------------===//
8282 // OpenMP directives and clauses.
8285 void *VarDataSharingAttributesStack;
8286 /// Set to true inside '#pragma omp declare target' region.
8287 bool IsInOpenMPDeclareTargetContext = false;
8288 /// \brief Initialization of data-sharing attributes stack.
8289 void InitDataSharingAttributesStack();
8290 void DestroyDataSharingAttributesStack();
8292 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8293 bool StrictlyPositive = true);
8294 /// Returns OpenMP nesting level for current directive.
8295 unsigned getOpenMPNestingLevel() const;
8297 /// Checks if a type or a declaration is disabled due to the owning extension
8298 /// being disabled, and emits diagnostic messages if it is disabled.
8299 /// \param D type or declaration to be checked.
8300 /// \param DiagLoc source location for the diagnostic message.
8301 /// \param DiagInfo information to be emitted for the diagnostic message.
8302 /// \param SrcRange source range of the declaration.
8303 /// \param Map maps type or declaration to the extensions.
8304 /// \param Selector selects diagnostic message: 0 for type and 1 for
8306 /// \return true if the type or declaration is disabled.
8307 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8308 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8309 MapT &Map, unsigned Selector = 0,
8310 SourceRange SrcRange = SourceRange());
8313 /// \brief Return true if the provided declaration \a VD should be captured by
8315 /// \param Level Relative level of nested OpenMP construct for that the check
8317 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8319 /// \brief Check if the specified variable is used in one of the private
8320 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8322 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8323 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8324 ExprObjectKind OK, SourceLocation Loc);
8326 /// \brief Check if the specified variable is used in 'private' clause.
8327 /// \param Level Relative level of nested OpenMP construct for that the check
8329 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8331 /// \brief Check if the specified variable is captured by 'target' directive.
8332 /// \param Level Relative level of nested OpenMP construct for that the check
8334 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8336 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8338 /// \brief Called on start of new data sharing attribute block.
8339 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8340 const DeclarationNameInfo &DirName, Scope *CurScope,
8341 SourceLocation Loc);
8342 /// \brief Start analysis of clauses.
8343 void StartOpenMPClause(OpenMPClauseKind K);
8344 /// \brief End analysis of clauses.
8345 void EndOpenMPClause();
8346 /// \brief Called on end of data sharing attribute block.
8347 void EndOpenMPDSABlock(Stmt *CurDirective);
8349 /// \brief Check if the current region is an OpenMP loop region and if it is,
8350 /// mark loop control variable, used in \p Init for loop initialization, as
8351 /// private by default.
8352 /// \param Init First part of the for loop.
8353 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8355 // OpenMP directives and clauses.
8356 /// \brief Called on correct id-expression from the '#pragma omp
8358 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8359 CXXScopeSpec &ScopeSpec,
8360 const DeclarationNameInfo &Id);
8361 /// \brief Called on well-formed '#pragma omp threadprivate'.
8362 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8364 ArrayRef<Expr *> VarList);
8365 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8366 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8368 ArrayRef<Expr *> VarList);
8369 /// \brief Check if the specified type is allowed to be used in 'omp declare
8370 /// reduction' construct.
8371 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8372 TypeResult ParsedType);
8373 /// \brief Called on start of '#pragma omp declare reduction'.
8374 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8375 Scope *S, DeclContext *DC, DeclarationName Name,
8376 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8377 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8378 /// \brief Initialize declare reduction construct initializer.
8379 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8380 /// \brief Finish current declare reduction construct initializer.
8381 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8382 /// \brief Initialize declare reduction construct initializer.
8383 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8384 /// \brief Finish current declare reduction construct initializer.
8385 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8386 /// \brief Called at the end of '#pragma omp declare reduction'.
8387 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8388 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8390 /// Called on the start of target region i.e. '#pragma omp declare target'.
8391 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8392 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8393 void ActOnFinishOpenMPDeclareTargetDirective();
8394 /// Called on correct id-expression from the '#pragma omp declare target'.
8395 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8396 const DeclarationNameInfo &Id,
8397 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8398 NamedDeclSetType &SameDirectiveDecls);
8399 /// Check declaration inside target region.
8400 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8401 /// Return true inside OpenMP target region.
8402 bool isInOpenMPDeclareTargetContext() const {
8403 return IsInOpenMPDeclareTargetContext;
8406 /// Return the number of captured regions created for an OpenMP directive.
8407 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8409 /// \brief Initialization of captured region for OpenMP region.
8410 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8411 /// \brief End of OpenMP region.
8413 /// \param S Statement associated with the current OpenMP region.
8414 /// \param Clauses List of clauses for the current OpenMP region.
8416 /// \returns Statement for finished OpenMP region.
8417 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8418 StmtResult ActOnOpenMPExecutableDirective(
8419 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8420 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8421 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8422 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8423 /// of the associated statement.
8424 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8426 SourceLocation StartLoc,
8427 SourceLocation EndLoc);
8428 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8429 /// of the associated statement.
8430 StmtResult ActOnOpenMPSimdDirective(
8431 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8432 SourceLocation EndLoc,
8433 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8434 /// \brief Called on well-formed '\#pragma omp for' after parsing
8435 /// of the associated statement.
8436 StmtResult ActOnOpenMPForDirective(
8437 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8438 SourceLocation EndLoc,
8439 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8440 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8441 /// of the associated statement.
8442 StmtResult ActOnOpenMPForSimdDirective(
8443 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8444 SourceLocation EndLoc,
8445 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8446 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8447 /// of the associated statement.
8448 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8449 Stmt *AStmt, SourceLocation StartLoc,
8450 SourceLocation EndLoc);
8451 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8452 /// associated statement.
8453 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8454 SourceLocation EndLoc);
8455 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8456 /// associated statement.
8457 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8458 Stmt *AStmt, SourceLocation StartLoc,
8459 SourceLocation EndLoc);
8460 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8461 /// associated statement.
8462 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8463 SourceLocation EndLoc);
8464 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8465 /// associated statement.
8466 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8467 ArrayRef<OMPClause *> Clauses,
8468 Stmt *AStmt, SourceLocation StartLoc,
8469 SourceLocation EndLoc);
8470 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8471 /// of the associated statement.
8472 StmtResult ActOnOpenMPParallelForDirective(
8473 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8474 SourceLocation EndLoc,
8475 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8476 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8477 /// parsing of the associated statement.
8478 StmtResult ActOnOpenMPParallelForSimdDirective(
8479 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8480 SourceLocation EndLoc,
8481 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8482 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8483 /// parsing of the associated statement.
8484 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8486 SourceLocation StartLoc,
8487 SourceLocation EndLoc);
8488 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8489 /// associated statement.
8490 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8491 Stmt *AStmt, SourceLocation StartLoc,
8492 SourceLocation EndLoc);
8493 /// \brief Called on well-formed '\#pragma omp taskyield'.
8494 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8495 SourceLocation EndLoc);
8496 /// \brief Called on well-formed '\#pragma omp barrier'.
8497 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8498 SourceLocation EndLoc);
8499 /// \brief Called on well-formed '\#pragma omp taskwait'.
8500 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8501 SourceLocation EndLoc);
8502 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8503 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8504 SourceLocation EndLoc);
8505 /// \brief Called on well-formed '\#pragma omp flush'.
8506 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8507 SourceLocation StartLoc,
8508 SourceLocation EndLoc);
8509 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8510 /// associated statement.
8511 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8512 Stmt *AStmt, SourceLocation StartLoc,
8513 SourceLocation EndLoc);
8514 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8515 /// associated statement.
8516 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8517 Stmt *AStmt, SourceLocation StartLoc,
8518 SourceLocation EndLoc);
8519 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8520 /// associated statement.
8521 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8522 Stmt *AStmt, SourceLocation StartLoc,
8523 SourceLocation EndLoc);
8524 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8525 /// the associated statement.
8526 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8527 Stmt *AStmt, SourceLocation StartLoc,
8528 SourceLocation EndLoc);
8529 /// \brief Called on well-formed '\#pragma omp target enter data' after
8530 /// parsing of the associated statement.
8531 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8532 SourceLocation StartLoc,
8533 SourceLocation EndLoc);
8534 /// \brief Called on well-formed '\#pragma omp target exit data' after
8535 /// parsing of the associated statement.
8536 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8537 SourceLocation StartLoc,
8538 SourceLocation EndLoc);
8539 /// \brief Called on well-formed '\#pragma omp target parallel' after
8540 /// parsing of the associated statement.
8541 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8543 SourceLocation StartLoc,
8544 SourceLocation EndLoc);
8545 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8546 /// parsing of the associated statement.
8547 StmtResult ActOnOpenMPTargetParallelForDirective(
8548 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8549 SourceLocation EndLoc,
8550 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8551 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8552 /// associated statement.
8553 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8554 Stmt *AStmt, SourceLocation StartLoc,
8555 SourceLocation EndLoc);
8556 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8558 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8559 SourceLocation EndLoc,
8560 OpenMPDirectiveKind CancelRegion);
8561 /// \brief Called on well-formed '\#pragma omp cancel'.
8562 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8563 SourceLocation StartLoc,
8564 SourceLocation EndLoc,
8565 OpenMPDirectiveKind CancelRegion);
8566 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8567 /// associated statement.
8568 StmtResult ActOnOpenMPTaskLoopDirective(
8569 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8570 SourceLocation EndLoc,
8571 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8572 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8573 /// the associated statement.
8574 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8575 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8576 SourceLocation EndLoc,
8577 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8578 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8579 /// of the associated statement.
8580 StmtResult ActOnOpenMPDistributeDirective(
8581 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8582 SourceLocation EndLoc,
8583 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8584 /// \brief Called on well-formed '\#pragma omp target update'.
8585 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8586 SourceLocation StartLoc,
8587 SourceLocation EndLoc);
8588 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8589 /// parsing of the associated statement.
8590 StmtResult ActOnOpenMPDistributeParallelForDirective(
8591 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8592 SourceLocation EndLoc,
8593 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8594 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8595 /// after parsing of the associated statement.
8596 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8597 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8598 SourceLocation EndLoc,
8599 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8600 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8601 /// parsing of the associated statement.
8602 StmtResult ActOnOpenMPDistributeSimdDirective(
8603 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8604 SourceLocation EndLoc,
8605 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8606 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8607 /// parsing of the associated statement.
8608 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8609 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8610 SourceLocation EndLoc,
8611 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8612 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8613 /// the associated statement.
8614 StmtResult ActOnOpenMPTargetSimdDirective(
8615 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8616 SourceLocation EndLoc,
8617 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8618 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8619 /// the associated statement.
8620 StmtResult ActOnOpenMPTeamsDistributeDirective(
8621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8622 SourceLocation EndLoc,
8623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8624 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8625 /// of the associated statement.
8626 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8627 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8628 SourceLocation EndLoc,
8629 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8630 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8631 /// after parsing of the associated statement.
8632 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8633 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8634 SourceLocation EndLoc,
8635 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8636 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8637 /// after parsing of the associated statement.
8638 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8640 SourceLocation EndLoc,
8641 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8642 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8643 /// associated statement.
8644 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8646 SourceLocation StartLoc,
8647 SourceLocation EndLoc);
8648 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8649 /// of the associated statement.
8650 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8651 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8652 SourceLocation EndLoc,
8653 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8654 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8655 /// after parsing of the associated statement.
8656 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8657 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8658 SourceLocation EndLoc,
8659 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8660 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8661 /// simd' after parsing of the associated statement.
8662 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8663 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8664 SourceLocation EndLoc,
8665 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8666 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8667 /// parsing of the associated statement.
8668 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8669 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8670 SourceLocation EndLoc,
8671 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8673 /// Checks correctness of linear modifiers.
8674 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8675 SourceLocation LinLoc);
8676 /// Checks that the specified declaration matches requirements for the linear
8678 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8679 OpenMPLinearClauseKind LinKind, QualType Type);
8681 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8682 /// the associated method/function.
8683 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8684 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8685 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8686 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8687 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8689 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8691 SourceLocation StartLoc,
8692 SourceLocation LParenLoc,
8693 SourceLocation EndLoc);
8694 /// \brief Called on well-formed 'if' clause.
8695 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8696 Expr *Condition, SourceLocation StartLoc,
8697 SourceLocation LParenLoc,
8698 SourceLocation NameModifierLoc,
8699 SourceLocation ColonLoc,
8700 SourceLocation EndLoc);
8701 /// \brief Called on well-formed 'final' clause.
8702 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8703 SourceLocation LParenLoc,
8704 SourceLocation EndLoc);
8705 /// \brief Called on well-formed 'num_threads' clause.
8706 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8707 SourceLocation StartLoc,
8708 SourceLocation LParenLoc,
8709 SourceLocation EndLoc);
8710 /// \brief Called on well-formed 'safelen' clause.
8711 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8712 SourceLocation StartLoc,
8713 SourceLocation LParenLoc,
8714 SourceLocation EndLoc);
8715 /// \brief Called on well-formed 'simdlen' clause.
8716 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8717 SourceLocation LParenLoc,
8718 SourceLocation EndLoc);
8719 /// \brief Called on well-formed 'collapse' clause.
8720 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8721 SourceLocation StartLoc,
8722 SourceLocation LParenLoc,
8723 SourceLocation EndLoc);
8724 /// \brief Called on well-formed 'ordered' clause.
8726 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8727 SourceLocation LParenLoc = SourceLocation(),
8728 Expr *NumForLoops = nullptr);
8729 /// \brief Called on well-formed 'grainsize' clause.
8730 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8731 SourceLocation LParenLoc,
8732 SourceLocation EndLoc);
8733 /// \brief Called on well-formed 'num_tasks' clause.
8734 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8735 SourceLocation LParenLoc,
8736 SourceLocation EndLoc);
8737 /// \brief Called on well-formed 'hint' clause.
8738 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8739 SourceLocation LParenLoc,
8740 SourceLocation EndLoc);
8742 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8744 SourceLocation ArgumentLoc,
8745 SourceLocation StartLoc,
8746 SourceLocation LParenLoc,
8747 SourceLocation EndLoc);
8748 /// \brief Called on well-formed 'default' clause.
8749 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8750 SourceLocation KindLoc,
8751 SourceLocation StartLoc,
8752 SourceLocation LParenLoc,
8753 SourceLocation EndLoc);
8754 /// \brief Called on well-formed 'proc_bind' clause.
8755 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8756 SourceLocation KindLoc,
8757 SourceLocation StartLoc,
8758 SourceLocation LParenLoc,
8759 SourceLocation EndLoc);
8761 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8762 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8763 SourceLocation StartLoc, SourceLocation LParenLoc,
8764 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8765 SourceLocation EndLoc);
8766 /// \brief Called on well-formed 'schedule' clause.
8767 OMPClause *ActOnOpenMPScheduleClause(
8768 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8769 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8770 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8771 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8773 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8774 SourceLocation EndLoc);
8775 /// \brief Called on well-formed 'nowait' clause.
8776 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8777 SourceLocation EndLoc);
8778 /// \brief Called on well-formed 'untied' clause.
8779 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8780 SourceLocation EndLoc);
8781 /// \brief Called on well-formed 'mergeable' clause.
8782 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8783 SourceLocation EndLoc);
8784 /// \brief Called on well-formed 'read' clause.
8785 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8786 SourceLocation EndLoc);
8787 /// \brief Called on well-formed 'write' clause.
8788 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8789 SourceLocation EndLoc);
8790 /// \brief Called on well-formed 'update' clause.
8791 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8792 SourceLocation EndLoc);
8793 /// \brief Called on well-formed 'capture' clause.
8794 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8795 SourceLocation EndLoc);
8796 /// \brief Called on well-formed 'seq_cst' clause.
8797 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8798 SourceLocation EndLoc);
8799 /// \brief Called on well-formed 'threads' clause.
8800 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8801 SourceLocation EndLoc);
8802 /// \brief Called on well-formed 'simd' clause.
8803 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8804 SourceLocation EndLoc);
8805 /// \brief Called on well-formed 'nogroup' clause.
8806 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8807 SourceLocation EndLoc);
8809 OMPClause *ActOnOpenMPVarListClause(
8810 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8811 SourceLocation StartLoc, SourceLocation LParenLoc,
8812 SourceLocation ColonLoc, SourceLocation EndLoc,
8813 CXXScopeSpec &ReductionIdScopeSpec,
8814 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8815 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8816 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8817 SourceLocation DepLinMapLoc);
8818 /// \brief Called on well-formed 'private' clause.
8819 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8820 SourceLocation StartLoc,
8821 SourceLocation LParenLoc,
8822 SourceLocation EndLoc);
8823 /// \brief Called on well-formed 'firstprivate' clause.
8824 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8825 SourceLocation StartLoc,
8826 SourceLocation LParenLoc,
8827 SourceLocation EndLoc);
8828 /// \brief Called on well-formed 'lastprivate' clause.
8829 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8830 SourceLocation StartLoc,
8831 SourceLocation LParenLoc,
8832 SourceLocation EndLoc);
8833 /// \brief Called on well-formed 'shared' clause.
8834 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8835 SourceLocation StartLoc,
8836 SourceLocation LParenLoc,
8837 SourceLocation EndLoc);
8838 /// \brief Called on well-formed 'reduction' clause.
8839 OMPClause *ActOnOpenMPReductionClause(
8840 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8841 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8842 CXXScopeSpec &ReductionIdScopeSpec,
8843 const DeclarationNameInfo &ReductionId,
8844 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8845 /// \brief Called on well-formed 'linear' clause.
8847 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8848 SourceLocation StartLoc, SourceLocation LParenLoc,
8849 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8850 SourceLocation ColonLoc, SourceLocation EndLoc);
8851 /// \brief Called on well-formed 'aligned' clause.
8852 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8854 SourceLocation StartLoc,
8855 SourceLocation LParenLoc,
8856 SourceLocation ColonLoc,
8857 SourceLocation EndLoc);
8858 /// \brief Called on well-formed 'copyin' clause.
8859 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8860 SourceLocation StartLoc,
8861 SourceLocation LParenLoc,
8862 SourceLocation EndLoc);
8863 /// \brief Called on well-formed 'copyprivate' clause.
8864 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8865 SourceLocation StartLoc,
8866 SourceLocation LParenLoc,
8867 SourceLocation EndLoc);
8868 /// \brief Called on well-formed 'flush' pseudo clause.
8869 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8870 SourceLocation StartLoc,
8871 SourceLocation LParenLoc,
8872 SourceLocation EndLoc);
8873 /// \brief Called on well-formed 'depend' clause.
8875 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8876 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8877 SourceLocation StartLoc, SourceLocation LParenLoc,
8878 SourceLocation EndLoc);
8879 /// \brief Called on well-formed 'device' clause.
8880 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8881 SourceLocation LParenLoc,
8882 SourceLocation EndLoc);
8883 /// \brief Called on well-formed 'map' clause.
8885 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8886 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8887 SourceLocation MapLoc, SourceLocation ColonLoc,
8888 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8889 SourceLocation LParenLoc, SourceLocation EndLoc);
8890 /// \brief Called on well-formed 'num_teams' clause.
8891 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8892 SourceLocation LParenLoc,
8893 SourceLocation EndLoc);
8894 /// \brief Called on well-formed 'thread_limit' clause.
8895 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8896 SourceLocation StartLoc,
8897 SourceLocation LParenLoc,
8898 SourceLocation EndLoc);
8899 /// \brief Called on well-formed 'priority' clause.
8900 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8901 SourceLocation LParenLoc,
8902 SourceLocation EndLoc);
8903 /// \brief Called on well-formed 'dist_schedule' clause.
8904 OMPClause *ActOnOpenMPDistScheduleClause(
8905 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8906 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8907 SourceLocation CommaLoc, SourceLocation EndLoc);
8908 /// \brief Called on well-formed 'defaultmap' clause.
8909 OMPClause *ActOnOpenMPDefaultmapClause(
8910 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8911 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8912 SourceLocation KindLoc, SourceLocation EndLoc);
8913 /// \brief Called on well-formed 'to' clause.
8914 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8915 SourceLocation StartLoc,
8916 SourceLocation LParenLoc,
8917 SourceLocation EndLoc);
8918 /// \brief Called on well-formed 'from' clause.
8919 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8920 SourceLocation StartLoc,
8921 SourceLocation LParenLoc,
8922 SourceLocation EndLoc);
8923 /// Called on well-formed 'use_device_ptr' clause.
8924 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8925 SourceLocation StartLoc,
8926 SourceLocation LParenLoc,
8927 SourceLocation EndLoc);
8928 /// Called on well-formed 'is_device_ptr' clause.
8929 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8930 SourceLocation StartLoc,
8931 SourceLocation LParenLoc,
8932 SourceLocation EndLoc);
8934 /// \brief The kind of conversion being performed.
8935 enum CheckedConversionKind {
8936 /// \brief An implicit conversion.
8937 CCK_ImplicitConversion,
8938 /// \brief A C-style cast.
8940 /// \brief A functional-style cast.
8942 /// \brief A cast other than a C-style cast.
8946 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8947 /// cast. If there is already an implicit cast, merge into the existing one.
8948 /// If isLvalue, the result of the cast is an lvalue.
8949 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8950 ExprValueKind VK = VK_RValue,
8951 const CXXCastPath *BasePath = nullptr,
8952 CheckedConversionKind CCK
8953 = CCK_ImplicitConversion);
8955 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8956 /// to the conversion from scalar type ScalarTy to the Boolean type.
8957 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8959 /// IgnoredValueConversions - Given that an expression's result is
8960 /// syntactically ignored, perform any conversions that are
8962 ExprResult IgnoredValueConversions(Expr *E);
8964 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8965 // functions and arrays to their respective pointers (C99 6.3.2.1).
8966 ExprResult UsualUnaryConversions(Expr *E);
8968 /// CallExprUnaryConversions - a special case of an unary conversion
8969 /// performed on a function designator of a call expression.
8970 ExprResult CallExprUnaryConversions(Expr *E);
8972 // DefaultFunctionArrayConversion - converts functions and arrays
8973 // to their respective pointers (C99 6.3.2.1).
8974 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8976 // DefaultFunctionArrayLvalueConversion - converts functions and
8977 // arrays to their respective pointers and performs the
8978 // lvalue-to-rvalue conversion.
8979 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8980 bool Diagnose = true);
8982 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8983 // the operand. This is DefaultFunctionArrayLvalueConversion,
8984 // except that it assumes the operand isn't of function or array
8986 ExprResult DefaultLvalueConversion(Expr *E);
8988 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8989 // do not have a prototype. Integer promotions are performed on each
8990 // argument, and arguments that have type float are promoted to double.
8991 ExprResult DefaultArgumentPromotion(Expr *E);
8993 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
8994 /// it as an xvalue. In C++98, the result will still be a prvalue, because
8995 /// we don't have xvalues there.
8996 ExprResult TemporaryMaterializationConversion(Expr *E);
8998 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8999 enum VariadicCallType {
9003 VariadicConstructor,
9004 VariadicDoesNotApply
9007 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9008 const FunctionProtoType *Proto,
9011 // Used for determining in which context a type is allowed to be passed to a
9021 // Determines which VarArgKind fits an expression.
9022 VarArgKind isValidVarArgType(const QualType &Ty);
9024 /// Check to see if the given expression is a valid argument to a variadic
9025 /// function, issuing a diagnostic if not.
9026 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9028 /// Check to see if a given expression could have '.c_str()' called on it.
9029 bool hasCStrMethod(const Expr *E);
9031 /// GatherArgumentsForCall - Collector argument expressions for various
9032 /// form of call prototypes.
9033 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9034 const FunctionProtoType *Proto,
9035 unsigned FirstParam, ArrayRef<Expr *> Args,
9036 SmallVectorImpl<Expr *> &AllArgs,
9037 VariadicCallType CallType = VariadicDoesNotApply,
9038 bool AllowExplicit = false,
9039 bool IsListInitialization = false);
9041 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9042 // will create a runtime trap if the resulting type is not a POD type.
9043 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9044 FunctionDecl *FDecl);
9046 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9047 // operands and then handles various conversions that are common to binary
9048 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9049 // routine returns the first non-arithmetic type found. The client is
9050 // responsible for emitting appropriate error diagnostics.
9051 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9052 bool IsCompAssign = false);
9054 /// AssignConvertType - All of the 'assignment' semantic checks return this
9055 /// enum to indicate whether the assignment was allowed. These checks are
9056 /// done for simple assignments, as well as initialization, return from
9057 /// function, argument passing, etc. The query is phrased in terms of a
9058 /// source and destination type.
9059 enum AssignConvertType {
9060 /// Compatible - the types are compatible according to the standard.
9063 /// PointerToInt - The assignment converts a pointer to an int, which we
9064 /// accept as an extension.
9067 /// IntToPointer - The assignment converts an int to a pointer, which we
9068 /// accept as an extension.
9071 /// FunctionVoidPointer - The assignment is between a function pointer and
9072 /// void*, which the standard doesn't allow, but we accept as an extension.
9073 FunctionVoidPointer,
9075 /// IncompatiblePointer - The assignment is between two pointers types that
9076 /// are not compatible, but we accept them as an extension.
9077 IncompatiblePointer,
9079 /// IncompatiblePointerSign - The assignment is between two pointers types
9080 /// which point to integers which have a different sign, but are otherwise
9081 /// identical. This is a subset of the above, but broken out because it's by
9082 /// far the most common case of incompatible pointers.
9083 IncompatiblePointerSign,
9085 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9086 /// c/v/r qualifiers, which we accept as an extension.
9087 CompatiblePointerDiscardsQualifiers,
9089 /// IncompatiblePointerDiscardsQualifiers - The assignment
9090 /// discards qualifiers that we don't permit to be discarded,
9091 /// like address spaces.
9092 IncompatiblePointerDiscardsQualifiers,
9094 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9095 /// nested pointer types, and the qualifiers other than the first two
9096 /// levels differ e.g. char ** -> const char **, but we accept them as an
9098 IncompatibleNestedPointerQualifiers,
9100 /// IncompatibleVectors - The assignment is between two vector types that
9101 /// have the same size, which we accept as an extension.
9102 IncompatibleVectors,
9104 /// IntToBlockPointer - The assignment converts an int to a block
9105 /// pointer. We disallow this.
9108 /// IncompatibleBlockPointer - The assignment is between two block
9109 /// pointers types that are not compatible.
9110 IncompatibleBlockPointer,
9112 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9113 /// id type and something else (that is incompatible with it). For example,
9114 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9115 IncompatibleObjCQualifiedId,
9117 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9118 /// object with __weak qualifier.
9119 IncompatibleObjCWeakRef,
9121 /// Incompatible - We reject this conversion outright, it is invalid to
9122 /// represent it in the AST.
9126 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9127 /// assignment conversion type specified by ConvTy. This returns true if the
9128 /// conversion was invalid or false if the conversion was accepted.
9129 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9131 QualType DstType, QualType SrcType,
9132 Expr *SrcExpr, AssignmentAction Action,
9133 bool *Complained = nullptr);
9135 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9136 /// enum. If AllowMask is true, then we also allow the complement of a valid
9137 /// value, to be used as a mask.
9138 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9139 bool AllowMask) const;
9141 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9142 /// integer not in the range of enum values.
9143 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9146 /// CheckAssignmentConstraints - Perform type checking for assignment,
9147 /// argument passing, variable initialization, and function return values.
9149 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9153 /// Check assignment constraints and optionally prepare for a conversion of
9154 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9156 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9159 bool ConvertRHS = true);
9161 /// Check assignment constraints for an assignment of RHS to LHSType.
9163 /// \param LHSType The destination type for the assignment.
9164 /// \param RHS The source expression for the assignment.
9165 /// \param Diagnose If \c true, diagnostics may be produced when checking
9166 /// for assignability. If a diagnostic is produced, \p RHS will be
9167 /// set to ExprError(). Note that this function may still return
9168 /// without producing a diagnostic, even for an invalid assignment.
9169 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9170 /// in an audited Core Foundation API and does not need to be checked
9171 /// for ARC retain issues.
9172 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9173 /// conversions necessary to perform the assignment. If \c false,
9174 /// \p Diagnose must also be \c false.
9175 AssignConvertType CheckSingleAssignmentConstraints(
9176 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9177 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9179 // \brief If the lhs type is a transparent union, check whether we
9180 // can initialize the transparent union with the given expression.
9181 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9184 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9186 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9188 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9189 AssignmentAction Action,
9190 bool AllowExplicit = false);
9191 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9192 AssignmentAction Action,
9194 ImplicitConversionSequence& ICS);
9195 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9196 const ImplicitConversionSequence& ICS,
9197 AssignmentAction Action,
9198 CheckedConversionKind CCK
9199 = CCK_ImplicitConversion);
9200 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9201 const StandardConversionSequence& SCS,
9202 AssignmentAction Action,
9203 CheckedConversionKind CCK);
9205 /// the following "Check" methods will return a valid/converted QualType
9206 /// or a null QualType (indicating an error diagnostic was issued).
9208 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9209 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9211 QualType CheckPointerToMemberOperands( // C++ 5.5
9212 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9213 SourceLocation OpLoc, bool isIndirect);
9214 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9215 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9217 QualType CheckRemainderOperands( // C99 6.5.5
9218 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9219 bool IsCompAssign = false);
9220 QualType CheckAdditionOperands( // C99 6.5.6
9221 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9222 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9223 QualType CheckSubtractionOperands( // C99 6.5.6
9224 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9225 QualType* CompLHSTy = nullptr);
9226 QualType CheckShiftOperands( // C99 6.5.7
9227 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9228 BinaryOperatorKind Opc, bool IsCompAssign = false);
9229 QualType CheckCompareOperands( // C99 6.5.8/9
9230 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9231 BinaryOperatorKind Opc, bool isRelational);
9232 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9233 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9234 BinaryOperatorKind Opc);
9235 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9236 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9237 BinaryOperatorKind Opc);
9238 // CheckAssignmentOperands is used for both simple and compound assignment.
9239 // For simple assignment, pass both expressions and a null converted type.
9240 // For compound assignment, pass both expressions and the converted type.
9241 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9242 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9244 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9245 UnaryOperatorKind Opcode, Expr *Op);
9246 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9247 BinaryOperatorKind Opcode,
9248 Expr *LHS, Expr *RHS);
9249 ExprResult checkPseudoObjectRValue(Expr *E);
9250 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9252 QualType CheckConditionalOperands( // C99 6.5.15
9253 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9254 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9255 QualType CXXCheckConditionalOperands( // C++ 5.16
9256 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9257 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9258 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9259 bool ConvertArgs = true);
9260 QualType FindCompositePointerType(SourceLocation Loc,
9261 ExprResult &E1, ExprResult &E2,
9262 bool ConvertArgs = true) {
9263 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9264 QualType Composite =
9265 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9271 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9272 SourceLocation QuestionLoc);
9274 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9275 SourceLocation QuestionLoc);
9277 void DiagnoseAlwaysNonNullPointer(Expr *E,
9278 Expr::NullPointerConstantKind NullType,
9279 bool IsEqual, SourceRange Range);
9281 /// type checking for vector binary operators.
9282 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9283 SourceLocation Loc, bool IsCompAssign,
9284 bool AllowBothBool, bool AllowBoolConversion);
9285 QualType GetSignedVectorType(QualType V);
9286 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9287 SourceLocation Loc, bool isRelational);
9288 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9289 SourceLocation Loc);
9291 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9292 bool isLaxVectorConversion(QualType srcType, QualType destType);
9294 /// type checking declaration initializers (C99 6.7.8)
9295 bool CheckForConstantInitializer(Expr *e, QualType t);
9297 // type checking C++ declaration initializers (C++ [dcl.init]).
9299 /// ReferenceCompareResult - Expresses the result of comparing two
9300 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9301 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9302 enum ReferenceCompareResult {
9303 /// Ref_Incompatible - The two types are incompatible, so direct
9304 /// reference binding is not possible.
9305 Ref_Incompatible = 0,
9306 /// Ref_Related - The two types are reference-related, which means
9307 /// that their unqualified forms (T1 and T2) are either the same
9308 /// or T1 is a base class of T2.
9310 /// Ref_Compatible - The two types are reference-compatible.
9314 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9315 QualType T1, QualType T2,
9316 bool &DerivedToBase,
9317 bool &ObjCConversion,
9318 bool &ObjCLifetimeConversion);
9320 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9321 Expr *CastExpr, CastKind &CastKind,
9322 ExprValueKind &VK, CXXCastPath &Path);
9324 /// \brief Force an expression with unknown-type to an expression of the
9326 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9328 /// \brief Type-check an expression that's being passed to an
9329 /// __unknown_anytype parameter.
9330 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9331 Expr *result, QualType ¶mType);
9333 // CheckVectorCast - check type constraints for vectors.
9334 // Since vectors are an extension, there are no C standard reference for this.
9335 // We allow casting between vectors and integer datatypes of the same size.
9336 // returns true if the cast is invalid
9337 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9340 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9341 /// implicit casts if necessary.
9342 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9344 // CheckExtVectorCast - check type constraints for extended vectors.
9345 // Since vectors are an extension, there are no C standard reference for this.
9346 // We allow casting between vectors and integer datatypes of the same size,
9347 // or vectors and the element type of that vector.
9348 // returns the cast expr
9349 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9352 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9353 SourceLocation LParenLoc,
9355 SourceLocation RParenLoc);
9357 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9359 /// \brief Checks for invalid conversions and casts between
9360 /// retainable pointers and other pointer kinds for ARC and Weak.
9361 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9362 QualType castType, Expr *&op,
9363 CheckedConversionKind CCK,
9364 bool Diagnose = true,
9365 bool DiagnoseCFAudited = false,
9366 BinaryOperatorKind Opc = BO_PtrMemD
9369 Expr *stripARCUnbridgedCast(Expr *e);
9370 void diagnoseARCUnbridgedCast(Expr *e);
9372 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9375 /// checkRetainCycles - Check whether an Objective-C message send
9376 /// might create an obvious retain cycle.
9377 void checkRetainCycles(ObjCMessageExpr *msg);
9378 void checkRetainCycles(Expr *receiver, Expr *argument);
9379 void checkRetainCycles(VarDecl *Var, Expr *Init);
9381 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9382 /// to weak/__unsafe_unretained type.
9383 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9385 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9386 /// to weak/__unsafe_unretained expression.
9387 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9389 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9390 /// \param Method - May be null.
9391 /// \param [out] ReturnType - The return type of the send.
9392 /// \return true iff there were any incompatible types.
9393 bool CheckMessageArgumentTypes(QualType ReceiverType,
9394 MultiExprArg Args, Selector Sel,
9395 ArrayRef<SourceLocation> SelectorLocs,
9396 ObjCMethodDecl *Method, bool isClassMessage,
9397 bool isSuperMessage,
9398 SourceLocation lbrac, SourceLocation rbrac,
9399 SourceRange RecRange,
9400 QualType &ReturnType, ExprValueKind &VK);
9402 /// \brief Determine the result of a message send expression based on
9403 /// the type of the receiver, the method expected to receive the message,
9404 /// and the form of the message send.
9405 QualType getMessageSendResultType(QualType ReceiverType,
9406 ObjCMethodDecl *Method,
9407 bool isClassMessage, bool isSuperMessage);
9409 /// \brief If the given expression involves a message send to a method
9410 /// with a related result type, emit a note describing what happened.
9411 void EmitRelatedResultTypeNote(const Expr *E);
9413 /// \brief Given that we had incompatible pointer types in a return
9414 /// statement, check whether we're in a method with a related result
9415 /// type, and if so, emit a note describing what happened.
9416 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9418 class ConditionResult {
9420 FullExprArg Condition;
9426 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9428 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9429 HasKnownValue(IsConstexpr && Condition.get() &&
9430 !Condition.get()->isValueDependent()),
9431 KnownValue(HasKnownValue &&
9432 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9433 explicit ConditionResult(bool Invalid)
9434 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9435 HasKnownValue(false), KnownValue(false) {}
9438 ConditionResult() : ConditionResult(false) {}
9439 bool isInvalid() const { return Invalid; }
9440 std::pair<VarDecl *, Expr *> get() const {
9441 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9444 llvm::Optional<bool> getKnownValue() const {
9450 static ConditionResult ConditionError() { return ConditionResult(true); }
9452 enum class ConditionKind {
9453 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9454 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9455 Switch ///< An integral condition for a 'switch' statement.
9458 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9459 Expr *SubExpr, ConditionKind CK);
9461 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9462 SourceLocation StmtLoc,
9465 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9467 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9468 SourceLocation StmtLoc,
9470 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9472 /// CheckBooleanCondition - Diagnose problems involving the use of
9473 /// the given expression as a boolean condition (e.g. in an if
9474 /// statement). Also performs the standard function and array
9475 /// decays, possibly changing the input variable.
9477 /// \param Loc - A location associated with the condition, e.g. the
9479 /// \return true iff there were any errors
9480 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9481 bool IsConstexpr = false);
9483 /// DiagnoseAssignmentAsCondition - Given that an expression is
9484 /// being used as a boolean condition, warn if it's an assignment.
9485 void DiagnoseAssignmentAsCondition(Expr *E);
9487 /// \brief Redundant parentheses over an equality comparison can indicate
9488 /// that the user intended an assignment used as condition.
9489 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9491 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9492 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9494 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9495 /// the specified width and sign. If an overflow occurs, detect it and emit
9496 /// the specified diagnostic.
9497 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9498 unsigned NewWidth, bool NewSign,
9499 SourceLocation Loc, unsigned DiagID);
9501 /// Checks that the Objective-C declaration is declared in the global scope.
9502 /// Emits an error and marks the declaration as invalid if it's not declared
9503 /// in the global scope.
9504 bool CheckObjCDeclScope(Decl *D);
9506 /// \brief Abstract base class used for diagnosing integer constant
9507 /// expression violations.
9508 class VerifyICEDiagnoser {
9512 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9514 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9515 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9516 virtual ~VerifyICEDiagnoser() { }
9519 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9520 /// and reports the appropriate diagnostics. Returns false on success.
9521 /// Can optionally return the value of the expression.
9522 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9523 VerifyICEDiagnoser &Diagnoser,
9524 bool AllowFold = true);
9525 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9527 bool AllowFold = true);
9528 ExprResult VerifyIntegerConstantExpression(Expr *E,
9529 llvm::APSInt *Result = nullptr);
9531 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9532 /// the correct width, and that the field type is valid.
9533 /// Returns false on success.
9534 /// Can optionally return whether the bit-field is of width 0
9535 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9536 QualType FieldTy, bool IsMsStruct,
9537 Expr *BitWidth, bool *ZeroWidth = nullptr);
9540 unsigned ForceCUDAHostDeviceDepth = 0;
9543 /// Increments our count of the number of times we've seen a pragma forcing
9544 /// functions to be __host__ __device__. So long as this count is greater
9545 /// than zero, all functions encountered will be __host__ __device__.
9546 void PushForceCUDAHostDevice();
9548 /// Decrements our count of the number of times we've seen a pragma forcing
9549 /// functions to be __host__ __device__. Returns false if the count is 0
9550 /// before incrementing, so you can emit an error.
9551 bool PopForceCUDAHostDevice();
9553 /// Diagnostics that are emitted only if we discover that the given function
9554 /// must be codegen'ed. Because handling these correctly adds overhead to
9555 /// compilation, this is currently only enabled for CUDA compilations.
9556 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9557 std::vector<PartialDiagnosticAt>>
9560 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9561 /// key in a hashtable, both the FD and location are hashed.
9562 struct FunctionDeclAndLoc {
9563 CanonicalDeclPtr<FunctionDecl> FD;
9567 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9568 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9569 /// same deferred diag twice.
9570 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9572 /// An inverse call graph, mapping known-emitted functions to one of their
9573 /// known-emitted callers (plus the location of the call).
9575 /// Functions that we can tell a priori must be emitted aren't added to this
9577 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9578 /* Caller = */ FunctionDeclAndLoc>
9579 CUDAKnownEmittedFns;
9581 /// A partial call graph maintained during CUDA compilation to support
9582 /// deferred diagnostics.
9584 /// Functions are only added here if, at the time they're considered, they are
9585 /// not known-emitted. As soon as we discover that a function is
9586 /// known-emitted, we remove it and everything it transitively calls from this
9587 /// set and add those functions to CUDAKnownEmittedFns.
9588 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9589 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9593 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9595 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9596 /// which are not allowed to appear inside __device__ functions and are
9597 /// allowed to appear in __host__ __device__ functions only if the host+device
9598 /// function is never codegen'ed.
9600 /// To handle this, we use the notion of "deferred diagnostics", where we
9601 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9603 /// This class lets you emit either a regular diagnostic, a deferred
9604 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9605 /// its constructor, thus simplifying the process of creating these "maybe
9606 /// deferred" diagnostics.
9607 class CUDADiagBuilder {
9610 /// Emit no diagnostics.
9612 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9614 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9615 /// emit a call stack showing how this function can be reached by an a
9616 /// priori known-emitted function.
9617 K_ImmediateWithCallStack,
9618 /// Create a deferred diagnostic, which is emitted only if the function
9619 /// it's attached to is codegen'ed. Also emit a call stack as with
9620 /// K_ImmediateWithCallStack.
9624 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9625 FunctionDecl *Fn, Sema &S);
9628 /// Convertible to bool: True if we immediately emitted an error, false if
9629 /// we didn't emit an error or we created a deferred error.
9633 /// if (CUDADiagBuilder(...) << foo << bar)
9634 /// return ExprError();
9636 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9637 /// want to use these instead of creating a CUDADiagBuilder yourself.
9638 operator bool() const { return ImmediateDiag.hasValue(); }
9640 template <typename T>
9641 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9643 if (Diag.ImmediateDiag.hasValue())
9644 *Diag.ImmediateDiag << Value;
9645 else if (Diag.PartialDiag.hasValue())
9646 *Diag.PartialDiag << Value;
9657 // Invariant: At most one of these Optionals has a value.
9658 // FIXME: Switch these to a Variant once that exists.
9659 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9660 llvm::Optional<PartialDiagnostic> PartialDiag;
9663 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9664 /// is "used as device code".
9666 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9667 /// - If CurContext is a __device__ or __global__ function, emits the
9668 /// diagnostics immediately.
9669 /// - If CurContext is a __host__ __device__ function and we are compiling for
9670 /// the device, creates a diagnostic which is emitted if and when we realize
9671 /// that the function will be codegen'ed.
9675 /// // Variable-length arrays are not allowed in CUDA device code.
9676 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9677 /// return ExprError();
9678 /// // Otherwise, continue parsing as normal.
9679 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9681 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9682 /// is "used as host code".
9684 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9685 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9687 enum CUDAFunctionTarget {
9695 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9698 /// Use this rather than examining the function's attributes yourself -- you
9699 /// will get it wrong. Returns CFT_Host if D is null.
9700 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9701 bool IgnoreImplicitHDAttr = false);
9702 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9704 /// Gets the CUDA target for the current context.
9705 CUDAFunctionTarget CurrentCUDATarget() {
9706 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9709 // CUDA function call preference. Must be ordered numerically from
9711 enum CUDAFunctionPreference {
9712 CFP_Never, // Invalid caller/callee combination.
9713 CFP_WrongSide, // Calls from host-device to host or device
9714 // function that do not match current compilation
9716 CFP_HostDevice, // Any calls to host/device functions.
9717 CFP_SameSide, // Calls from host-device to host or device
9718 // function matching current compilation mode.
9719 CFP_Native, // host-to-host or device-to-device calls.
9722 /// Identifies relative preference of a given Caller/Callee
9723 /// combination, based on their host/device attributes.
9724 /// \param Caller function which needs address of \p Callee.
9725 /// nullptr in case of global context.
9726 /// \param Callee target function
9728 /// \returns preference value for particular Caller/Callee combination.
9729 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9730 const FunctionDecl *Callee);
9732 /// Determines whether Caller may invoke Callee, based on their CUDA
9733 /// host/device attributes. Returns false if the call is not allowed.
9735 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9736 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9737 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9738 const FunctionDecl *Callee) {
9739 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9742 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9743 /// depending on FD and the current compilation settings.
9744 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9745 const LookupResult &Previous);
9748 /// Check whether we're allowed to call Callee from the current context.
9750 /// - If the call is never allowed in a semantically-correct program
9751 /// (CFP_Never), emits an error and returns false.
9753 /// - If the call is allowed in semantically-correct programs, but only if
9754 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9755 /// be emitted if and when the caller is codegen'ed, and returns true.
9757 /// Will only create deferred diagnostics for a given SourceLocation once,
9758 /// so you can safely call this multiple times without generating duplicate
9759 /// deferred errors.
9761 /// - Otherwise, returns true without emitting any diagnostics.
9762 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9764 /// Set __device__ or __host__ __device__ attributes on the given lambda
9765 /// operator() method.
9767 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9768 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9769 /// functions become __host__ __device__ themselves.
9770 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9772 /// Finds a function in \p Matches with highest calling priority
9773 /// from \p Caller context and erases all functions with lower
9774 /// calling priority.
9775 void EraseUnwantedCUDAMatches(
9776 const FunctionDecl *Caller,
9777 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9779 /// Given a implicit special member, infer its CUDA target from the
9780 /// calls it needs to make to underlying base/field special members.
9781 /// \param ClassDecl the class for which the member is being created.
9782 /// \param CSM the kind of special member.
9783 /// \param MemberDecl the special member itself.
9784 /// \param ConstRHS true if this is a copy operation with a const object on
9786 /// \param Diagnose true if this call should emit diagnostics.
9787 /// \return true if there was an error inferring.
9788 /// The result of this call is implicit CUDA target attribute(s) attached to
9789 /// the member declaration.
9790 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9791 CXXSpecialMember CSM,
9792 CXXMethodDecl *MemberDecl,
9796 /// \return true if \p CD can be considered empty according to CUDA
9797 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9798 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9799 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9801 /// Check whether NewFD is a valid overload for CUDA. Emits
9802 /// diagnostics and invalidates NewFD if not.
9803 void checkCUDATargetOverload(FunctionDecl *NewFD,
9804 const LookupResult &Previous);
9805 /// Copies target attributes from the template TD to the function FD.
9806 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9808 /// \name Code completion
9810 /// \brief Describes the context in which code completion occurs.
9811 enum ParserCompletionContext {
9812 /// \brief Code completion occurs at top-level or namespace context.
9814 /// \brief Code completion occurs within a class, struct, or union.
9816 /// \brief Code completion occurs within an Objective-C interface, protocol,
9819 /// \brief Code completion occurs within an Objective-C implementation or
9820 /// category implementation
9821 PCC_ObjCImplementation,
9822 /// \brief Code completion occurs within the list of instance variables
9823 /// in an Objective-C interface, protocol, category, or implementation.
9824 PCC_ObjCInstanceVariableList,
9825 /// \brief Code completion occurs following one or more template
9828 /// \brief Code completion occurs following one or more template
9829 /// headers within a class.
9831 /// \brief Code completion occurs within an expression.
9833 /// \brief Code completion occurs within a statement, which may
9834 /// also be an expression or a declaration.
9836 /// \brief Code completion occurs at the beginning of the
9837 /// initialization statement (or expression) in a for loop.
9839 /// \brief Code completion occurs within the condition of an if,
9840 /// while, switch, or for statement.
9842 /// \brief Code completion occurs within the body of a function on a
9843 /// recovery path, where we do not have a specific handle on our position
9845 PCC_RecoveryInFunction,
9846 /// \brief Code completion occurs where only a type is permitted.
9848 /// \brief Code completion occurs in a parenthesized expression, which
9849 /// might also be a type cast.
9850 PCC_ParenthesizedExpression,
9851 /// \brief Code completion occurs within a sequence of declaration
9852 /// specifiers within a function, method, or block.
9853 PCC_LocalDeclarationSpecifiers
9856 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9857 void CodeCompleteOrdinaryName(Scope *S,
9858 ParserCompletionContext CompletionContext);
9859 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9860 bool AllowNonIdentifiers,
9861 bool AllowNestedNameSpecifiers);
9863 struct CodeCompleteExpressionData;
9864 void CodeCompleteExpression(Scope *S,
9865 const CodeCompleteExpressionData &Data);
9866 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9867 SourceLocation OpLoc, bool IsArrow,
9868 bool IsBaseExprStatement);
9869 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9870 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9871 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9872 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9873 const VirtSpecifiers *VS = nullptr);
9874 void CodeCompleteBracketDeclarator(Scope *S);
9875 void CodeCompleteCase(Scope *S);
9876 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9877 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9878 ArrayRef<Expr *> Args);
9879 void CodeCompleteInitializer(Scope *S, Decl *D);
9880 void CodeCompleteReturn(Scope *S);
9881 void CodeCompleteAfterIf(Scope *S);
9882 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9884 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9885 bool EnteringContext);
9886 void CodeCompleteUsing(Scope *S);
9887 void CodeCompleteUsingDirective(Scope *S);
9888 void CodeCompleteNamespaceDecl(Scope *S);
9889 void CodeCompleteNamespaceAliasDecl(Scope *S);
9890 void CodeCompleteOperatorName(Scope *S);
9891 void CodeCompleteConstructorInitializer(
9893 ArrayRef<CXXCtorInitializer *> Initializers);
9895 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9896 bool AfterAmpersand);
9898 void CodeCompleteObjCAtDirective(Scope *S);
9899 void CodeCompleteObjCAtVisibility(Scope *S);
9900 void CodeCompleteObjCAtStatement(Scope *S);
9901 void CodeCompleteObjCAtExpression(Scope *S);
9902 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9903 void CodeCompleteObjCPropertyGetter(Scope *S);
9904 void CodeCompleteObjCPropertySetter(Scope *S);
9905 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9907 void CodeCompleteObjCMessageReceiver(Scope *S);
9908 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9909 ArrayRef<IdentifierInfo *> SelIdents,
9910 bool AtArgumentExpression);
9911 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9912 ArrayRef<IdentifierInfo *> SelIdents,
9913 bool AtArgumentExpression,
9914 bool IsSuper = false);
9915 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9916 ArrayRef<IdentifierInfo *> SelIdents,
9917 bool AtArgumentExpression,
9918 ObjCInterfaceDecl *Super = nullptr);
9919 void CodeCompleteObjCForCollection(Scope *S,
9920 DeclGroupPtrTy IterationVar);
9921 void CodeCompleteObjCSelector(Scope *S,
9922 ArrayRef<IdentifierInfo *> SelIdents);
9923 void CodeCompleteObjCProtocolReferences(
9924 ArrayRef<IdentifierLocPair> Protocols);
9925 void CodeCompleteObjCProtocolDecl(Scope *S);
9926 void CodeCompleteObjCInterfaceDecl(Scope *S);
9927 void CodeCompleteObjCSuperclass(Scope *S,
9928 IdentifierInfo *ClassName,
9929 SourceLocation ClassNameLoc);
9930 void CodeCompleteObjCImplementationDecl(Scope *S);
9931 void CodeCompleteObjCInterfaceCategory(Scope *S,
9932 IdentifierInfo *ClassName,
9933 SourceLocation ClassNameLoc);
9934 void CodeCompleteObjCImplementationCategory(Scope *S,
9935 IdentifierInfo *ClassName,
9936 SourceLocation ClassNameLoc);
9937 void CodeCompleteObjCPropertyDefinition(Scope *S);
9938 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9939 IdentifierInfo *PropertyName);
9940 void CodeCompleteObjCMethodDecl(Scope *S,
9941 bool IsInstanceMethod,
9942 ParsedType ReturnType);
9943 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9944 bool IsInstanceMethod,
9945 bool AtParameterName,
9946 ParsedType ReturnType,
9947 ArrayRef<IdentifierInfo *> SelIdents);
9948 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
9949 SourceLocation ClassNameLoc,
9950 bool IsBaseExprStatement);
9951 void CodeCompletePreprocessorDirective(bool InConditional);
9952 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9953 void CodeCompletePreprocessorMacroName(bool IsDefinition);
9954 void CodeCompletePreprocessorExpression();
9955 void CodeCompletePreprocessorMacroArgument(Scope *S,
9956 IdentifierInfo *Macro,
9957 MacroInfo *MacroInfo,
9959 void CodeCompleteNaturalLanguage();
9960 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9961 CodeCompletionTUInfo &CCTUInfo,
9962 SmallVectorImpl<CodeCompletionResult> &Results);
9965 //===--------------------------------------------------------------------===//
9966 // Extra semantic analysis beyond the C type system
9969 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9970 unsigned ByteNo) const;
9973 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9974 const ArraySubscriptExpr *ASE=nullptr,
9975 bool AllowOnePastEnd=true, bool IndexNegated=false);
9976 void CheckArrayAccess(const Expr *E);
9977 // Used to grab the relevant information from a FormatAttr and a
9978 // FunctionDeclaration.
9979 struct FormatStringInfo {
9981 unsigned FirstDataArg;
9985 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9986 FormatStringInfo *FSI);
9987 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9988 const FunctionProtoType *Proto);
9989 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9990 ArrayRef<const Expr *> Args);
9991 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9992 const FunctionProtoType *Proto);
9993 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9994 void CheckConstructorCall(FunctionDecl *FDecl,
9995 ArrayRef<const Expr *> Args,
9996 const FunctionProtoType *Proto,
9997 SourceLocation Loc);
9999 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10000 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10001 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10002 VariadicCallType CallType);
10004 bool CheckObjCString(Expr *Arg);
10005 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10007 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10008 unsigned BuiltinID, CallExpr *TheCall);
10010 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10011 unsigned MaxWidth);
10012 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10013 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10015 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10016 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10017 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10018 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10019 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10020 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10021 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10023 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
10024 bool SemaBuiltinVAStart(CallExpr *TheCall);
10025 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
10026 bool SemaBuiltinVAStartARM(CallExpr *Call);
10027 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10028 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10029 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10032 // Used by C++ template instantiation.
10033 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10034 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10035 SourceLocation BuiltinLoc,
10036 SourceLocation RParenLoc);
10039 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10040 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10041 bool SemaBuiltinAssume(CallExpr *TheCall);
10042 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10043 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10044 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10045 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10046 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10047 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10048 AtomicExpr::AtomicOp Op);
10049 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10050 llvm::APSInt &Result);
10051 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10052 int Low, int High);
10053 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10054 unsigned Multiple);
10055 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10056 int ArgNum, unsigned ExpectedFieldNum,
10059 enum FormatStringType {
10066 FST_FreeBSDKPrintf,
10071 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10073 bool FormatStringHasSArg(const StringLiteral *FExpr);
10075 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10078 bool CheckFormatArguments(const FormatAttr *Format,
10079 ArrayRef<const Expr *> Args,
10081 VariadicCallType CallType,
10082 SourceLocation Loc, SourceRange Range,
10083 llvm::SmallBitVector &CheckedVarArgs);
10084 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10085 bool HasVAListArg, unsigned format_idx,
10086 unsigned firstDataArg, FormatStringType Type,
10087 VariadicCallType CallType,
10088 SourceLocation Loc, SourceRange range,
10089 llvm::SmallBitVector &CheckedVarArgs);
10091 void CheckAbsoluteValueFunction(const CallExpr *Call,
10092 const FunctionDecl *FDecl);
10094 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10096 void CheckMemaccessArguments(const CallExpr *Call,
10098 IdentifierInfo *FnName);
10100 void CheckStrlcpycatArguments(const CallExpr *Call,
10101 IdentifierInfo *FnName);
10103 void CheckStrncatArguments(const CallExpr *Call,
10104 IdentifierInfo *FnName);
10106 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10107 SourceLocation ReturnLoc,
10108 bool isObjCMethod = false,
10109 const AttrVec *Attrs = nullptr,
10110 const FunctionDecl *FD = nullptr);
10112 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10113 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10114 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10115 void CheckForIntOverflow(Expr *E);
10116 void CheckUnsequencedOperations(Expr *E);
10118 /// \brief Perform semantic checks on a completed expression. This will either
10119 /// be a full-expression or a default argument expression.
10120 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10121 bool IsConstexpr = false);
10123 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10126 /// Check if there is a field shadowing.
10127 void CheckShadowInheritedFields(const SourceLocation &Loc,
10128 DeclarationName FieldName,
10129 const CXXRecordDecl *RD);
10131 /// \brief Check if the given expression contains 'break' or 'continue'
10132 /// statement that produces control flow different from GCC.
10133 void CheckBreakContinueBinding(Expr *E);
10135 /// \brief Check whether receiver is mutable ObjC container which
10136 /// attempts to add itself into the container
10137 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10139 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10140 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10141 bool DeleteWasArrayForm);
10143 /// \brief Register a magic integral constant to be used as a type tag.
10144 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10145 uint64_t MagicValue, QualType Type,
10146 bool LayoutCompatible, bool MustBeNull);
10148 struct TypeTagData {
10151 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10152 Type(Type), LayoutCompatible(LayoutCompatible),
10153 MustBeNull(MustBeNull)
10158 /// If true, \c Type should be compared with other expression's types for
10159 /// layout-compatibility.
10160 unsigned LayoutCompatible : 1;
10161 unsigned MustBeNull : 1;
10164 /// A pair of ArgumentKind identifier and magic value. This uniquely
10165 /// identifies the magic value.
10166 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10169 /// \brief A map from magic value to type information.
10170 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10171 TypeTagForDatatypeMagicValues;
10173 /// \brief Peform checks on a call of a function with argument_with_type_tag
10174 /// or pointer_with_type_tag attributes.
10175 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10176 const Expr * const *ExprArgs);
10178 /// \brief Check if we are taking the address of a packed field
10179 /// as this may be a problem if the pointer value is dereferenced.
10180 void CheckAddressOfPackedMember(Expr *rhs);
10182 /// \brief The parser's current scope.
10184 /// The parser maintains this state here.
10187 mutable IdentifierInfo *Ident_super;
10188 mutable IdentifierInfo *Ident___float128;
10190 /// Nullability type specifiers.
10191 IdentifierInfo *Ident__Nonnull = nullptr;
10192 IdentifierInfo *Ident__Nullable = nullptr;
10193 IdentifierInfo *Ident__Null_unspecified = nullptr;
10195 IdentifierInfo *Ident_NSError = nullptr;
10198 friend class Parser;
10199 friend class InitializationSequence;
10200 friend class ASTReader;
10201 friend class ASTDeclReader;
10202 friend class ASTWriter;
10205 /// Retrieve the keyword associated
10206 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10208 /// The struct behind the CFErrorRef pointer.
10209 RecordDecl *CFError = nullptr;
10211 /// Retrieve the identifier "NSError".
10212 IdentifierInfo *getNSErrorIdent();
10214 /// \brief Retrieve the parser's current scope.
10216 /// This routine must only be used when it is certain that semantic analysis
10217 /// and the parser are in precisely the same context, which is not the case
10218 /// when, e.g., we are performing any kind of template instantiation.
10219 /// Therefore, the only safe places to use this scope are in the parser
10220 /// itself and in routines directly invoked from the parser and *never* from
10221 /// template substitution or instantiation.
10222 Scope *getCurScope() const { return CurScope; }
10224 void incrementMSManglingNumber() const {
10225 return CurScope->incrementMSManglingNumber();
10228 IdentifierInfo *getSuperIdentifier() const;
10229 IdentifierInfo *getFloat128Identifier() const;
10231 Decl *getObjCDeclContext() const;
10233 DeclContext *getCurLexicalContext() const {
10234 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10237 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10239 /// \param D The declaration to check. Note that this may be altered to point
10240 /// to another declaration that \c D gets it's availability from. i.e., we
10241 /// walk the list of typedefs to find an availability attribute.
10243 /// \param Message If non-null, this will be populated with the message from
10244 /// the availability attribute that is selected.
10245 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10246 std::string *Message);
10248 const DeclContext *getCurObjCLexicalContext() const {
10249 const DeclContext *DC = getCurLexicalContext();
10250 // A category implicitly has the attribute of the interface.
10251 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10252 DC = CatD->getClassInterface();
10256 /// \brief To be used for checking whether the arguments being passed to
10257 /// function exceeds the number of parameters expected for it.
10258 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10259 bool PartialOverloading = false) {
10260 // We check whether we're just after a comma in code-completion.
10261 if (NumArgs > 0 && PartialOverloading)
10262 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10263 return NumArgs > NumParams;
10266 // Emitting members of dllexported classes is delayed until the class
10267 // (including field initializers) is fully parsed.
10268 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10271 /// \brief Helper class that collects misaligned member designations and
10272 /// their location info for delayed diagnostics.
10273 struct MisalignedMember {
10277 CharUnits Alignment;
10279 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10280 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10281 CharUnits Alignment)
10282 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10283 explicit MisalignedMember(Expr *E)
10284 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10286 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10288 /// \brief Small set of gathered accesses to potentially misaligned members
10289 /// due to the packed attribute.
10290 SmallVector<MisalignedMember, 4> MisalignedMembers;
10292 /// \brief Adds an expression to the set of gathered misaligned members.
10293 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10294 CharUnits Alignment);
10297 /// \brief Diagnoses the current set of gathered accesses. This typically
10298 /// happens at full expression level. The set is cleared after emitting the
10300 void DiagnoseMisalignedMembers();
10302 /// \brief This function checks if the expression is in the sef of potentially
10303 /// misaligned members and it is converted to some pointer type T with lower
10304 /// or equal alignment requirements. If so it removes it. This is used when
10305 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10307 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10309 /// \brief This function calls Action when it determines that E designates a
10310 /// misaligned member due to the packed attribute. This is used to emit
10311 /// local diagnostics like in reference binding.
10312 void RefersToMemberWithReducedAlignment(
10314 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10318 /// \brief RAII object that enters a new expression evaluation context.
10319 class EnterExpressionEvaluationContext {
10321 bool Entered = true;
10325 EnterExpressionEvaluationContext(Sema &Actions,
10326 Sema::ExpressionEvaluationContext NewContext,
10327 Decl *LambdaContextDecl = nullptr,
10328 bool IsDecltype = false,
10329 bool ShouldEnter = true)
10330 : Actions(Actions), Entered(ShouldEnter) {
10332 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10335 EnterExpressionEvaluationContext(Sema &Actions,
10336 Sema::ExpressionEvaluationContext NewContext,
10337 Sema::ReuseLambdaContextDecl_t,
10338 bool IsDecltype = false)
10339 : Actions(Actions) {
10340 Actions.PushExpressionEvaluationContext(NewContext,
10341 Sema::ReuseLambdaContextDecl,
10345 enum InitListTag { InitList };
10346 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10347 bool ShouldEnter = true)
10348 : Actions(Actions), Entered(false) {
10349 // In C++11 onwards, narrowing checks are performed on the contents of
10350 // braced-init-lists, even when they occur within unevaluated operands.
10351 // Therefore we still need to instantiate constexpr functions used in such
10353 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10354 Actions.getLangOpts().CPlusPlus11) {
10355 Actions.PushExpressionEvaluationContext(
10356 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10361 ~EnterExpressionEvaluationContext() {
10363 Actions.PopExpressionEvaluationContext();
10367 DeductionFailureInfo
10368 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10369 sema::TemplateDeductionInfo &Info);
10371 /// \brief Contains a late templated function.
10372 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10373 struct LateParsedTemplate {
10375 /// \brief The template function declaration to be late parsed.
10379 } // end namespace clang
10382 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10384 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10385 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10386 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10388 static FunctionDeclAndLoc getEmptyKey() {
10389 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10392 static FunctionDeclAndLoc getTombstoneKey() {
10393 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10396 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10397 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10398 FDL.Loc.getRawEncoding());
10401 static bool isEqual(const FunctionDeclAndLoc &LHS,
10402 const FunctionDeclAndLoc &RHS) {
10403 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10406 } // namespace llvm