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 /// \brief pragma clang section kind
340 enum PragmaClangSectionKind {
348 enum PragmaClangSectionAction {
353 struct PragmaClangSection {
354 std::string SectionName;
356 SourceLocation PragmaLocation;
358 void Act(SourceLocation PragmaLocation,
359 PragmaClangSectionAction Action,
360 StringLiteral* Name);
363 PragmaClangSection PragmaClangBSSSection;
364 PragmaClangSection PragmaClangDataSection;
365 PragmaClangSection PragmaClangRodataSection;
366 PragmaClangSection PragmaClangTextSection;
368 enum PragmaMsStackAction {
369 PSK_Reset = 0x0, // #pragma ()
370 PSK_Set = 0x1, // #pragma (value)
371 PSK_Push = 0x2, // #pragma (push[, id])
372 PSK_Pop = 0x4, // #pragma (pop[, id])
373 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
374 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
375 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
378 template<typename ValueType>
381 llvm::StringRef StackSlotLabel;
383 SourceLocation PragmaLocation;
384 Slot(llvm::StringRef StackSlotLabel,
386 SourceLocation PragmaLocation)
387 : StackSlotLabel(StackSlotLabel), Value(Value),
388 PragmaLocation(PragmaLocation) {}
390 void Act(SourceLocation PragmaLocation,
391 PragmaMsStackAction Action,
392 llvm::StringRef StackSlotLabel,
395 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
396 // method body to restore the stacks on exit, so it works like this:
399 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
401 // #pragma <name>(pop, InternalPragmaSlot)
404 // It works even with #pragma vtordisp, although MSVC doesn't support
405 // #pragma vtordisp(push [, id], n)
408 // Push / pop a named sentinel slot.
409 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
410 assert((Action == PSK_Push || Action == PSK_Pop) &&
411 "Can only push / pop #pragma stack sentinels!");
412 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
416 explicit PragmaStack(const ValueType &Default)
417 : DefaultValue(Default), CurrentValue(Default) {}
419 SmallVector<Slot, 2> Stack;
420 ValueType DefaultValue; // Value used for PSK_Reset action.
421 ValueType CurrentValue;
422 SourceLocation CurrentPragmaLocation;
424 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
425 // we shouldn't do so if they're in a module).
427 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
428 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
430 /// 0: Suppress all vtordisps
431 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
433 /// 2: Always insert vtordisps to support RTTI on partially constructed
435 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
437 // Sentinel to represent when the stack is set to mac68k alignment.
438 static const unsigned kMac68kAlignmentSentinel = ~0U;
439 PragmaStack<unsigned> PackStack;
441 PragmaStack<StringLiteral *> DataSegStack;
442 PragmaStack<StringLiteral *> BSSSegStack;
443 PragmaStack<StringLiteral *> ConstSegStack;
444 PragmaStack<StringLiteral *> CodeSegStack;
446 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
447 // Actions should be performed only if we enter / exit a C++ method body.
448 class PragmaStackSentinelRAII {
450 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
451 ~PragmaStackSentinelRAII();
459 /// A mapping that describes the nullability we've seen in each header file.
460 FileNullabilityMap NullabilityMap;
462 /// Last section used with #pragma init_seg.
463 StringLiteral *CurInitSeg;
464 SourceLocation CurInitSegLoc;
466 /// VisContext - Manages the stack for \#pragma GCC visibility.
467 void *VisContext; // Really a "PragmaVisStack*"
469 /// \brief This represents the stack of attributes that were pushed by
470 /// \#pragma clang attribute.
471 struct PragmaAttributeEntry {
473 AttributeList *Attribute;
474 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
477 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
479 /// \brief The declaration that is currently receiving an attribute from the
480 /// #pragma attribute stack.
481 const Decl *PragmaAttributeCurrentTargetDecl;
483 /// \brief This represents the last location of a "#pragma clang optimize off"
484 /// directive if such a directive has not been closed by an "on" yet. If
485 /// optimizations are currently "on", this is set to an invalid location.
486 SourceLocation OptimizeOffPragmaLocation;
488 /// \brief Flag indicating if Sema is building a recovery call expression.
490 /// This flag is used to avoid building recovery call expressions
491 /// if Sema is already doing so, which would cause infinite recursions.
492 bool IsBuildingRecoveryCallExpr;
494 /// Used to control the generation of ExprWithCleanups.
497 /// ExprCleanupObjects - This is the stack of objects requiring
498 /// cleanup that are created by the current full expression. The
499 /// element type here is ExprWithCleanups::Object.
500 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
502 /// \brief Store a list of either DeclRefExprs or MemberExprs
503 /// that contain a reference to a variable (constant) that may or may not
504 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
505 /// and discarded value conversions have been applied to all subexpressions
506 /// of the enclosing full expression. This is cleared at the end of each
508 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
510 /// \brief Stack containing information about each of the nested
511 /// function, block, and method scopes that are currently active.
513 /// This array is never empty. Clients should ignore the first
514 /// element, which is used to cache a single FunctionScopeInfo
515 /// that's used to parse every top-level function.
516 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
518 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
519 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
522 /// ExtVectorDecls - This is a list all the extended vector types. This allows
523 /// us to associate a raw vector type with one of the ext_vector type names.
524 /// This is only necessary for issuing pretty diagnostics.
525 ExtVectorDeclsType ExtVectorDecls;
527 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
528 std::unique_ptr<CXXFieldCollector> FieldCollector;
530 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
532 /// \brief Set containing all declared private fields that are not used.
533 NamedDeclSetType UnusedPrivateFields;
535 /// \brief Set containing all typedefs that are likely unused.
536 llvm::SmallSetVector<const TypedefNameDecl *, 4>
537 UnusedLocalTypedefNameCandidates;
539 /// \brief Delete-expressions to be analyzed at the end of translation unit
541 /// This list contains class members, and locations of delete-expressions
542 /// that could not be proven as to whether they mismatch with new-expression
543 /// used in initializer of the field.
544 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
545 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
546 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
548 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
550 /// PureVirtualClassDiagSet - a set of class declarations which we have
551 /// emitted a list of pure virtual functions. Used to prevent emitting the
552 /// same list more than once.
553 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
555 /// ParsingInitForAutoVars - a set of declarations with auto types for which
556 /// we are currently parsing the initializer.
557 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
559 /// \brief Look for a locally scoped extern "C" declaration by the given name.
560 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
562 typedef LazyVector<VarDecl *, ExternalSemaSource,
563 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
564 TentativeDefinitionsType;
566 /// \brief All the tentative definitions encountered in the TU.
567 TentativeDefinitionsType TentativeDefinitions;
569 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
570 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
571 UnusedFileScopedDeclsType;
573 /// \brief The set of file scoped decls seen so far that have not been used
574 /// and must warn if not used. Only contains the first declaration.
575 UnusedFileScopedDeclsType UnusedFileScopedDecls;
577 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
578 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
579 DelegatingCtorDeclsType;
581 /// \brief All the delegating constructors seen so far in the file, used for
582 /// cycle detection at the end of the TU.
583 DelegatingCtorDeclsType DelegatingCtorDecls;
585 /// \brief All the overriding functions seen during a class definition
586 /// that had their exception spec checks delayed, plus the overridden
588 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
589 DelayedExceptionSpecChecks;
591 /// \brief All the members seen during a class definition which were both
592 /// explicitly defaulted and had explicitly-specified exception
593 /// specifications, along with the function type containing their
594 /// user-specified exception specification. Those exception specifications
595 /// were overridden with the default specifications, but we still need to
596 /// check whether they are compatible with the default specification, and
597 /// we can't do that until the nesting set of class definitions is complete.
598 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
599 DelayedDefaultedMemberExceptionSpecs;
601 typedef llvm::MapVector<const FunctionDecl *,
602 std::unique_ptr<LateParsedTemplate>>
603 LateParsedTemplateMapT;
604 LateParsedTemplateMapT LateParsedTemplateMap;
606 /// \brief Callback to the parser to parse templated functions when needed.
607 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
608 typedef void LateTemplateParserCleanupCB(void *P);
609 LateTemplateParserCB *LateTemplateParser;
610 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
613 void SetLateTemplateParser(LateTemplateParserCB *LTP,
614 LateTemplateParserCleanupCB *LTPCleanup,
616 LateTemplateParser = LTP;
617 LateTemplateParserCleanup = LTPCleanup;
621 class DelayedDiagnostics;
623 class DelayedDiagnosticsState {
624 sema::DelayedDiagnosticPool *SavedPool;
625 friend class Sema::DelayedDiagnostics;
627 typedef DelayedDiagnosticsState ParsingDeclState;
628 typedef DelayedDiagnosticsState ProcessingContextState;
630 /// A class which encapsulates the logic for delaying diagnostics
631 /// during parsing and other processing.
632 class DelayedDiagnostics {
633 /// \brief The current pool of diagnostics into which delayed
634 /// diagnostics should go.
635 sema::DelayedDiagnosticPool *CurPool;
638 DelayedDiagnostics() : CurPool(nullptr) {}
640 /// Adds a delayed diagnostic.
641 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
643 /// Determines whether diagnostics should be delayed.
644 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
646 /// Returns the current delayed-diagnostics pool.
647 sema::DelayedDiagnosticPool *getCurrentPool() const {
651 /// Enter a new scope. Access and deprecation diagnostics will be
652 /// collected in this pool.
653 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
654 DelayedDiagnosticsState state;
655 state.SavedPool = CurPool;
660 /// Leave a delayed-diagnostic state that was previously pushed.
661 /// Do not emit any of the diagnostics. This is performed as part
662 /// of the bookkeeping of popping a pool "properly".
663 void popWithoutEmitting(DelayedDiagnosticsState state) {
664 CurPool = state.SavedPool;
667 /// Enter a new scope where access and deprecation diagnostics are
669 DelayedDiagnosticsState pushUndelayed() {
670 DelayedDiagnosticsState state;
671 state.SavedPool = CurPool;
676 /// Undo a previous pushUndelayed().
677 void popUndelayed(DelayedDiagnosticsState state) {
678 assert(CurPool == nullptr);
679 CurPool = state.SavedPool;
681 } DelayedDiagnostics;
683 /// A RAII object to temporarily push a declaration context.
687 DeclContext *SavedContext;
688 ProcessingContextState SavedContextState;
689 QualType SavedCXXThisTypeOverride;
692 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
693 : S(S), SavedContext(S.CurContext),
694 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
695 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
697 assert(ContextToPush && "pushing null context");
698 S.CurContext = ContextToPush;
700 S.CXXThisTypeOverride = QualType();
704 if (!SavedContext) return;
705 S.CurContext = SavedContext;
706 S.DelayedDiagnostics.popUndelayed(SavedContextState);
707 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
708 SavedContext = nullptr;
716 /// \brief RAII object to handle the state changes required to synthesize
718 class SynthesizedFunctionScope {
720 Sema::ContextRAII SavedContext;
721 bool PushedCodeSynthesisContext = false;
724 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
725 : S(S), SavedContext(S, DC) {
726 S.PushFunctionScope();
727 S.PushExpressionEvaluationContext(
728 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
729 if (auto *FD = dyn_cast<FunctionDecl>(DC))
730 FD->setWillHaveBody(true);
732 assert(isa<ObjCMethodDecl>(DC));
735 void addContextNote(SourceLocation UseLoc) {
736 assert(!PushedCodeSynthesisContext);
738 Sema::CodeSynthesisContext Ctx;
739 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
740 Ctx.PointOfInstantiation = UseLoc;
741 Ctx.Entity = cast<Decl>(S.CurContext);
742 S.pushCodeSynthesisContext(Ctx);
744 PushedCodeSynthesisContext = true;
747 ~SynthesizedFunctionScope() {
748 if (PushedCodeSynthesisContext)
749 S.popCodeSynthesisContext();
750 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
751 FD->setWillHaveBody(false);
752 S.PopExpressionEvaluationContext();
753 S.PopFunctionScopeInfo();
757 /// WeakUndeclaredIdentifiers - Identifiers contained in
758 /// \#pragma weak before declared. rare. may alias another
759 /// identifier, declared or undeclared
760 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
762 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
763 /// \#pragma redefine_extname before declared. Used in Solaris system headers
764 /// to define functions that occur in multiple standards to call the version
765 /// in the currently selected standard.
766 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
769 /// \brief Load weak undeclared identifiers from the external source.
770 void LoadExternalWeakUndeclaredIdentifiers();
772 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
773 /// \#pragma weak during processing of other Decls.
774 /// I couldn't figure out a clean way to generate these in-line, so
775 /// we store them here and handle separately -- which is a hack.
776 /// It would be best to refactor this.
777 SmallVector<Decl*,2> WeakTopLevelDecl;
779 IdentifierResolver IdResolver;
781 /// Translation Unit Scope - useful to Objective-C actions that need
782 /// to lookup file scope declarations in the "ordinary" C decl namespace.
783 /// For example, user-defined classes, built-in "id" type, etc.
786 /// \brief The C++ "std" namespace, where the standard library resides.
787 LazyDeclPtr StdNamespace;
789 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
790 /// standard library.
791 LazyDeclPtr StdBadAlloc;
793 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
794 /// standard library.
795 LazyDeclPtr StdAlignValT;
797 /// \brief The C++ "std::experimental" namespace, where the experimental parts
798 /// of the standard library resides.
799 NamespaceDecl *StdExperimentalNamespaceCache;
801 /// \brief The C++ "std::initializer_list" template, which is defined in
802 /// \<initializer_list>.
803 ClassTemplateDecl *StdInitializerList;
805 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
806 RecordDecl *CXXTypeInfoDecl;
808 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
809 RecordDecl *MSVCGuidDecl;
811 /// \brief Caches identifiers/selectors for NSFoundation APIs.
812 std::unique_ptr<NSAPI> NSAPIObj;
814 /// \brief The declaration of the Objective-C NSNumber class.
815 ObjCInterfaceDecl *NSNumberDecl;
817 /// \brief The declaration of the Objective-C NSValue class.
818 ObjCInterfaceDecl *NSValueDecl;
820 /// \brief Pointer to NSNumber type (NSNumber *).
821 QualType NSNumberPointer;
823 /// \brief Pointer to NSValue type (NSValue *).
824 QualType NSValuePointer;
826 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
827 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
829 /// \brief The declaration of the Objective-C NSString class.
830 ObjCInterfaceDecl *NSStringDecl;
832 /// \brief Pointer to NSString type (NSString *).
833 QualType NSStringPointer;
835 /// \brief The declaration of the stringWithUTF8String: method.
836 ObjCMethodDecl *StringWithUTF8StringMethod;
838 /// \brief The declaration of the valueWithBytes:objCType: method.
839 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
841 /// \brief The declaration of the Objective-C NSArray class.
842 ObjCInterfaceDecl *NSArrayDecl;
844 /// \brief The declaration of the arrayWithObjects:count: method.
845 ObjCMethodDecl *ArrayWithObjectsMethod;
847 /// \brief The declaration of the Objective-C NSDictionary class.
848 ObjCInterfaceDecl *NSDictionaryDecl;
850 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
851 ObjCMethodDecl *DictionaryWithObjectsMethod;
853 /// \brief id<NSCopying> type.
854 QualType QIDNSCopying;
856 /// \brief will hold 'respondsToSelector:'
857 Selector RespondsToSelectorSel;
859 /// A flag to remember whether the implicit forms of operator new and delete
860 /// have been declared.
861 bool GlobalNewDeleteDeclared;
863 /// A flag to indicate that we're in a context that permits abstract
864 /// references to fields. This is really a
865 bool AllowAbstractFieldReference;
867 /// \brief Describes how the expressions currently being parsed are
868 /// evaluated at run-time, if at all.
869 enum class ExpressionEvaluationContext {
870 /// \brief The current expression and its subexpressions occur within an
871 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
872 /// \c sizeof, where the type of the expression may be significant but
873 /// no code will be generated to evaluate the value of the expression at
877 /// \brief The current expression occurs within a braced-init-list within
878 /// an unevaluated operand. This is mostly like a regular unevaluated
879 /// context, except that we still instantiate constexpr functions that are
880 /// referenced here so that we can perform narrowing checks correctly.
883 /// \brief The current expression occurs within a discarded statement.
884 /// This behaves largely similarly to an unevaluated operand in preventing
885 /// definitions from being required, but not in other ways.
888 /// \brief The current expression occurs within an unevaluated
889 /// operand that unconditionally permits abstract references to
890 /// fields, such as a SIZE operator in MS-style inline assembly.
893 /// \brief The current context is "potentially evaluated" in C++11 terms,
894 /// but the expression is evaluated at compile-time (like the values of
895 /// cases in a switch statement).
898 /// \brief The current expression is potentially evaluated at run time,
899 /// which means that code may be generated to evaluate the value of the
900 /// expression at run time.
901 PotentiallyEvaluated,
903 /// \brief The current expression is potentially evaluated, but any
904 /// declarations referenced inside that expression are only used if
905 /// in fact the current expression is used.
907 /// This value is used when parsing default function arguments, for which
908 /// we would like to provide diagnostics (e.g., passing non-POD arguments
909 /// through varargs) but do not want to mark declarations as "referenced"
910 /// until the default argument is used.
911 PotentiallyEvaluatedIfUsed
914 /// \brief Data structure used to record current or nested
915 /// expression evaluation contexts.
916 struct ExpressionEvaluationContextRecord {
917 /// \brief The expression evaluation context.
918 ExpressionEvaluationContext Context;
920 /// \brief Whether the enclosing context needed a cleanup.
921 CleanupInfo ParentCleanup;
923 /// \brief Whether we are in a decltype expression.
926 /// \brief The number of active cleanup objects when we entered
927 /// this expression evaluation context.
928 unsigned NumCleanupObjects;
930 /// \brief The number of typos encountered during this expression evaluation
931 /// context (i.e. the number of TypoExprs created).
934 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
936 /// \brief The lambdas that are present within this context, if it
937 /// is indeed an unevaluated context.
938 SmallVector<LambdaExpr *, 2> Lambdas;
940 /// \brief The declaration that provides context for lambda expressions
941 /// and block literals if the normal declaration context does not
942 /// suffice, e.g., in a default function argument.
943 Decl *ManglingContextDecl;
945 /// \brief The context information used to mangle lambda expressions
946 /// and block literals within this context.
948 /// This mangling information is allocated lazily, since most contexts
949 /// do not have lambda expressions or block literals.
950 std::unique_ptr<MangleNumberingContext> MangleNumbering;
952 /// \brief If we are processing a decltype type, a set of call expressions
953 /// for which we have deferred checking the completeness of the return type.
954 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
956 /// \brief If we are processing a decltype type, a set of temporary binding
957 /// expressions for which we have deferred checking the destructor.
958 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
960 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
961 unsigned NumCleanupObjects,
962 CleanupInfo ParentCleanup,
963 Decl *ManglingContextDecl,
965 : Context(Context), ParentCleanup(ParentCleanup),
966 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
968 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
970 /// \brief Retrieve the mangling numbering context, used to consistently
971 /// number constructs like lambdas for mangling.
972 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
974 bool isUnevaluated() const {
975 return Context == ExpressionEvaluationContext::Unevaluated ||
976 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
977 Context == ExpressionEvaluationContext::UnevaluatedList;
979 bool isConstantEvaluated() const {
980 return Context == ExpressionEvaluationContext::ConstantEvaluated;
984 /// A stack of expression evaluation contexts.
985 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
987 /// \brief Compute the mangling number context for a lambda expression or
990 /// \param DC - The DeclContext containing the lambda expression or
992 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
993 /// associated with the context, if relevant.
994 MangleNumberingContext *getCurrentMangleNumberContext(
995 const DeclContext *DC,
996 Decl *&ManglingContextDecl);
999 /// SpecialMemberOverloadResult - The overloading result for a special member
1002 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1003 /// integer are used to determine whether overload resolution succeeded.
1004 class SpecialMemberOverloadResult {
1013 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1016 SpecialMemberOverloadResult() : Pair() {}
1017 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1018 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1020 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1021 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1023 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1024 void setKind(Kind K) { Pair.setInt(K); }
1027 class SpecialMemberOverloadResultEntry
1028 : public llvm::FastFoldingSetNode,
1029 public SpecialMemberOverloadResult {
1031 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1032 : FastFoldingSetNode(ID)
1036 /// \brief A cache of special member function overload resolution results
1037 /// for C++ records.
1038 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1040 /// \brief A cache of the flags available in enumerations with the flag_bits
1042 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1044 /// \brief The kind of translation unit we are processing.
1046 /// When we're processing a complete translation unit, Sema will perform
1047 /// end-of-translation-unit semantic tasks (such as creating
1048 /// initializers for tentative definitions in C) once parsing has
1049 /// completed. Modules and precompiled headers perform different kinds of
1051 TranslationUnitKind TUKind;
1053 llvm::BumpPtrAllocator BumpAlloc;
1055 /// \brief The number of SFINAE diagnostics that have been trapped.
1056 unsigned NumSFINAEErrors;
1058 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1059 UnparsedDefaultArgInstantiationsMap;
1061 /// \brief A mapping from parameters with unparsed default arguments to the
1062 /// set of instantiations of each parameter.
1064 /// This mapping is a temporary data structure used when parsing
1065 /// nested class templates or nested classes of class templates,
1066 /// where we might end up instantiating an inner class before the
1067 /// default arguments of its methods have been parsed.
1068 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1070 // Contains the locations of the beginning of unparsed default
1071 // argument locations.
1072 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1074 /// UndefinedInternals - all the used, undefined objects which require a
1075 /// definition in this translation unit.
1076 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1078 /// Obtain a sorted list of functions that are undefined but ODR-used.
1079 void getUndefinedButUsed(
1080 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1082 /// Retrieves list of suspicious delete-expressions that will be checked at
1083 /// the end of translation unit.
1084 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1085 getMismatchingDeleteExpressions() const;
1087 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1088 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1090 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1091 /// We need to maintain a list, since selectors can have differing signatures
1092 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1093 /// of selectors are "overloaded").
1094 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1095 /// methods inside categories with a particular selector.
1096 GlobalMethodPool MethodPool;
1098 /// Method selectors used in a \@selector expression. Used for implementation
1100 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1102 /// Kinds of C++ special members.
1103 enum CXXSpecialMember {
1104 CXXDefaultConstructor,
1113 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1115 /// The C++ special members which we are currently in the process of
1116 /// declaring. If this process recursively triggers the declaration of the
1117 /// same special member, we should act as if it is not yet declared.
1118 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1120 /// The function definitions which were renamed as part of typo-correction
1121 /// to match their respective declarations. We want to keep track of them
1122 /// to ensure that we don't emit a "redefinition" error if we encounter a
1123 /// correctly named definition after the renamed definition.
1124 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1126 /// Stack of types that correspond to the parameter entities that are
1127 /// currently being copy-initialized. Can be empty.
1128 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1130 void ReadMethodPool(Selector Sel);
1131 void updateOutOfDateSelector(Selector Sel);
1133 /// Private Helper predicate to check for 'self'.
1134 bool isSelfExpr(Expr *RExpr);
1135 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1137 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1138 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1139 /// should not be used elsewhere.
1140 void EmitCurrentDiagnostic(unsigned DiagID);
1142 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1144 class FPContractStateRAII {
1146 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1147 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1151 FPOptions OldFPFeaturesState;
1154 void addImplicitTypedef(StringRef Name, QualType T);
1157 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1158 TranslationUnitKind TUKind = TU_Complete,
1159 CodeCompleteConsumer *CompletionConsumer = nullptr);
1162 /// \brief Perform initialization that occurs after the parser has been
1163 /// initialized but before it parses anything.
1166 const LangOptions &getLangOpts() const { return LangOpts; }
1167 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1168 FPOptions &getFPOptions() { return FPFeatures; }
1170 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1171 SourceManager &getSourceManager() const { return SourceMgr; }
1172 Preprocessor &getPreprocessor() const { return PP; }
1173 ASTContext &getASTContext() const { return Context; }
1174 ASTConsumer &getASTConsumer() const { return Consumer; }
1175 ASTMutationListener *getASTMutationListener() const;
1176 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1178 ///\brief Registers an external source. If an external source already exists,
1179 /// creates a multiplex external source and appends to it.
1181 ///\param[in] E - A non-null external sema source.
1183 void addExternalSource(ExternalSemaSource *E);
1185 void PrintStats() const;
1187 /// \brief Helper class that creates diagnostics with optional
1188 /// template instantiation stacks.
1190 /// This class provides a wrapper around the basic DiagnosticBuilder
1191 /// class that emits diagnostics. SemaDiagnosticBuilder is
1192 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1193 /// does) and, if the diagnostic comes from inside a template
1194 /// instantiation, printing the template instantiation stack as
1196 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1201 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1202 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1204 // This is a cunning lie. DiagnosticBuilder actually performs move
1205 // construction in its copy constructor (but due to varied uses, it's not
1206 // possible to conveniently express this as actual move construction). So
1207 // the default copy ctor here is fine, because the base class disables the
1208 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1209 // in that case anwyay.
1210 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1212 ~SemaDiagnosticBuilder() {
1213 // If we aren't active, there is nothing to do.
1214 if (!isActive()) return;
1216 // Otherwise, we need to emit the diagnostic. First flush the underlying
1217 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1218 // won't emit the diagnostic in its own destructor.
1220 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1221 // do its own needless checks to see if the diagnostic needs to be
1222 // emitted. However, because we take care to ensure that the builder
1223 // objects never escape, a sufficiently smart compiler will be able to
1224 // eliminate that code.
1228 // Dispatch to Sema to emit the diagnostic.
1229 SemaRef.EmitCurrentDiagnostic(DiagID);
1232 /// Teach operator<< to produce an object of the correct type.
1233 template<typename T>
1234 friend const SemaDiagnosticBuilder &operator<<(
1235 const SemaDiagnosticBuilder &Diag, const T &Value) {
1236 const DiagnosticBuilder &BaseDiag = Diag;
1242 /// \brief Emit a diagnostic.
1243 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1244 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1245 return SemaDiagnosticBuilder(DB, *this, DiagID);
1248 /// \brief Emit a partial diagnostic.
1249 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1251 /// \brief Build a partial diagnostic.
1252 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1254 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1256 /// \brief Get a string to suggest for zero-initialization of a type.
1258 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1259 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1261 /// \brief Calls \c Lexer::getLocForEndOfToken()
1262 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1264 /// \brief Retrieve the module loader associated with the preprocessor.
1265 ModuleLoader &getModuleLoader() const;
1267 void emitAndClearUnusedLocalTypedefWarnings();
1269 void ActOnEndOfTranslationUnit();
1271 void CheckDelegatingCtorCycles();
1273 Scope *getScopeForContext(DeclContext *Ctx);
1275 void PushFunctionScope();
1276 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1277 sema::LambdaScopeInfo *PushLambdaScope();
1279 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1280 /// is during Parsing. Currently it is used to pass on the depth
1281 /// when parsing generic lambda 'auto' parameters.
1282 void RecordParsingTemplateParameterDepth(unsigned Depth);
1284 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1286 CapturedRegionKind K);
1288 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1289 const Decl *D = nullptr,
1290 const BlockExpr *blkExpr = nullptr);
1292 sema::FunctionScopeInfo *getCurFunction() const {
1293 return FunctionScopes.back();
1296 sema::FunctionScopeInfo *getEnclosingFunction() const {
1297 if (FunctionScopes.empty())
1300 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1301 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1303 return FunctionScopes[e];
1308 template <typename ExprT>
1309 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1310 if (!isUnevaluatedContext())
1311 getCurFunction()->recordUseOfWeak(E, IsRead);
1314 void PushCompoundScope();
1315 void PopCompoundScope();
1317 sema::CompoundScopeInfo &getCurCompoundScope() const;
1319 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1321 /// \brief Retrieve the current block, if any.
1322 sema::BlockScopeInfo *getCurBlock();
1324 /// Retrieve the current lambda scope info, if any.
1325 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1326 /// lambda scope info ignoring all inner capturing scopes that are not
1328 sema::LambdaScopeInfo *
1329 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1331 /// \brief Retrieve the current generic lambda info, if any.
1332 sema::LambdaScopeInfo *getCurGenericLambda();
1334 /// \brief Retrieve the current captured region, if any.
1335 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1337 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1338 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1340 void ActOnComment(SourceRange Comment);
1342 //===--------------------------------------------------------------------===//
1343 // Type Analysis / Processing: SemaType.cpp.
1346 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1347 const DeclSpec *DS = nullptr);
1348 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1349 const DeclSpec *DS = nullptr);
1350 QualType BuildPointerType(QualType T,
1351 SourceLocation Loc, DeclarationName Entity);
1352 QualType BuildReferenceType(QualType T, bool LValueRef,
1353 SourceLocation Loc, DeclarationName Entity);
1354 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1355 Expr *ArraySize, unsigned Quals,
1356 SourceRange Brackets, DeclarationName Entity);
1357 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1358 SourceLocation AttrLoc);
1360 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1362 /// \brief Build a function type.
1364 /// This routine checks the function type according to C++ rules and
1365 /// under the assumption that the result type and parameter types have
1366 /// just been instantiated from a template. It therefore duplicates
1367 /// some of the behavior of GetTypeForDeclarator, but in a much
1368 /// simpler form that is only suitable for this narrow use case.
1370 /// \param T The return type of the function.
1372 /// \param ParamTypes The parameter types of the function. This array
1373 /// will be modified to account for adjustments to the types of the
1374 /// function parameters.
1376 /// \param Loc The location of the entity whose type involves this
1377 /// function type or, if there is no such entity, the location of the
1378 /// type that will have function type.
1380 /// \param Entity The name of the entity that involves the function
1383 /// \param EPI Extra information about the function type. Usually this will
1384 /// be taken from an existing function with the same prototype.
1386 /// \returns A suitable function type, if there are no errors. The
1387 /// unqualified type will always be a FunctionProtoType.
1388 /// Otherwise, returns a NULL type.
1389 QualType BuildFunctionType(QualType T,
1390 MutableArrayRef<QualType> ParamTypes,
1391 SourceLocation Loc, DeclarationName Entity,
1392 const FunctionProtoType::ExtProtoInfo &EPI);
1394 QualType BuildMemberPointerType(QualType T, QualType Class,
1396 DeclarationName Entity);
1397 QualType BuildBlockPointerType(QualType T,
1398 SourceLocation Loc, DeclarationName Entity);
1399 QualType BuildParenType(QualType T);
1400 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1401 QualType BuildReadPipeType(QualType T,
1402 SourceLocation Loc);
1403 QualType BuildWritePipeType(QualType T,
1404 SourceLocation Loc);
1406 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1407 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1408 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1409 TypeSourceInfo *ReturnTypeInfo);
1411 /// \brief Package the given type and TSI into a ParsedType.
1412 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1413 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1414 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1415 static QualType GetTypeFromParser(ParsedType Ty,
1416 TypeSourceInfo **TInfo = nullptr);
1417 CanThrowResult canThrow(const Expr *E);
1418 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1419 const FunctionProtoType *FPT);
1420 void UpdateExceptionSpec(FunctionDecl *FD,
1421 const FunctionProtoType::ExceptionSpecInfo &ESI);
1422 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1423 bool CheckDistantExceptionSpec(QualType T);
1424 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1425 bool CheckEquivalentExceptionSpec(
1426 const FunctionProtoType *Old, SourceLocation OldLoc,
1427 const FunctionProtoType *New, SourceLocation NewLoc);
1428 bool CheckEquivalentExceptionSpec(
1429 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1430 const FunctionProtoType *Old, SourceLocation OldLoc,
1431 const FunctionProtoType *New, SourceLocation NewLoc);
1432 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1433 const PartialDiagnostic &NestedDiagID,
1434 const PartialDiagnostic &NoteID,
1435 const FunctionProtoType *Superset,
1436 SourceLocation SuperLoc,
1437 const FunctionProtoType *Subset,
1438 SourceLocation SubLoc);
1439 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1440 const PartialDiagnostic &NoteID,
1441 const FunctionProtoType *Target,
1442 SourceLocation TargetLoc,
1443 const FunctionProtoType *Source,
1444 SourceLocation SourceLoc);
1446 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1448 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1449 /// in an Objective-C message declaration. Return the appropriate type.
1450 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1452 /// \brief Abstract class used to diagnose incomplete types.
1453 struct TypeDiagnoser {
1456 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1457 virtual ~TypeDiagnoser() {}
1460 static int getPrintable(int I) { return I; }
1461 static unsigned getPrintable(unsigned I) { return I; }
1462 static bool getPrintable(bool B) { return B; }
1463 static const char * getPrintable(const char *S) { return S; }
1464 static StringRef getPrintable(StringRef S) { return S; }
1465 static const std::string &getPrintable(const std::string &S) { return S; }
1466 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1469 static DeclarationName getPrintable(DeclarationName N) { return N; }
1470 static QualType getPrintable(QualType T) { return T; }
1471 static SourceRange getPrintable(SourceRange R) { return R; }
1472 static SourceRange getPrintable(SourceLocation L) { return L; }
1473 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1474 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1476 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1478 std::tuple<const Ts &...> Args;
1480 template <std::size_t... Is>
1481 void emit(const SemaDiagnosticBuilder &DB,
1482 llvm::index_sequence<Is...>) const {
1483 // Apply all tuple elements to the builder in order.
1484 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1489 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1490 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1491 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1494 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1495 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1496 emit(DB, llvm::index_sequence_for<Ts...>());
1502 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1503 TypeDiagnoser *Diagnoser);
1505 struct ModuleScope {
1506 clang::Module *Module;
1507 VisibleModuleSet OuterVisibleModules;
1509 /// The modules we're currently parsing.
1510 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1512 /// Get the module whose scope we are currently within.
1513 Module *getCurrentModule() const {
1514 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1517 VisibleModuleSet VisibleModules;
1520 /// \brief Get the module owning an entity.
1521 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1523 /// \brief Make a merged definition of an existing hidden definition \p ND
1524 /// visible at the specified location.
1525 void makeMergedDefinitionVisible(NamedDecl *ND);
1527 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1529 /// Determine whether a declaration is visible to name lookup.
1530 bool isVisible(const NamedDecl *D) {
1531 return !D->isHidden() || isVisibleSlow(D);
1534 /// Determine whether any declaration of an entity is visible.
1536 hasVisibleDeclaration(const NamedDecl *D,
1537 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1538 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1540 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1541 llvm::SmallVectorImpl<Module *> *Modules);
1543 bool hasVisibleMergedDefinition(NamedDecl *Def);
1545 /// Determine if \p D has a visible definition. If not, suggest a declaration
1546 /// that should be made visible to expose the definition.
1547 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1548 bool OnlyNeedComplete = false);
1549 bool hasVisibleDefinition(const NamedDecl *D) {
1551 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1554 /// Determine if the template parameter \p D has a visible default argument.
1556 hasVisibleDefaultArgument(const NamedDecl *D,
1557 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1559 /// Determine if there is a visible declaration of \p D that is an explicit
1560 /// specialization declaration for a specialization of a template. (For a
1561 /// member specialization, use hasVisibleMemberSpecialization.)
1562 bool hasVisibleExplicitSpecialization(
1563 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1565 /// Determine if there is a visible declaration of \p D that is a member
1566 /// specialization declaration (as opposed to an instantiated declaration).
1567 bool hasVisibleMemberSpecialization(
1568 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1570 /// Determine if \p A and \p B are equivalent internal linkage declarations
1571 /// from different modules, and thus an ambiguity error can be downgraded to
1572 /// an extension warning.
1573 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1574 const NamedDecl *B);
1575 void diagnoseEquivalentInternalLinkageDeclarations(
1576 SourceLocation Loc, const NamedDecl *D,
1577 ArrayRef<const NamedDecl *> Equiv);
1579 bool isCompleteType(SourceLocation Loc, QualType T) {
1580 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1582 bool RequireCompleteType(SourceLocation Loc, QualType T,
1583 TypeDiagnoser &Diagnoser);
1584 bool RequireCompleteType(SourceLocation Loc, QualType T,
1587 template <typename... Ts>
1588 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1589 const Ts &...Args) {
1590 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1591 return RequireCompleteType(Loc, T, Diagnoser);
1594 void completeExprArrayBound(Expr *E);
1595 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1596 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1598 template <typename... Ts>
1599 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1600 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1601 return RequireCompleteExprType(E, Diagnoser);
1604 bool RequireLiteralType(SourceLocation Loc, QualType T,
1605 TypeDiagnoser &Diagnoser);
1606 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1608 template <typename... Ts>
1609 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1610 const Ts &...Args) {
1611 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1612 return RequireLiteralType(Loc, T, Diagnoser);
1615 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1616 const CXXScopeSpec &SS, QualType T);
1618 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1619 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1620 /// context, such as when building a type for decltype(auto).
1621 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1622 bool AsUnevaluated = true);
1623 QualType BuildUnaryTransformType(QualType BaseType,
1624 UnaryTransformType::UTTKind UKind,
1625 SourceLocation Loc);
1627 //===--------------------------------------------------------------------===//
1628 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1631 struct SkipBodyInfo {
1632 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1634 NamedDecl *Previous;
1637 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1639 void DiagnoseUseOfUnimplementedSelectors();
1641 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1643 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1644 Scope *S, CXXScopeSpec *SS = nullptr,
1645 bool isClassName = false, bool HasTrailingDot = false,
1646 ParsedType ObjectType = nullptr,
1647 bool IsCtorOrDtorName = false,
1648 bool WantNontrivialTypeSourceInfo = false,
1649 bool IsClassTemplateDeductionContext = true,
1650 IdentifierInfo **CorrectedII = nullptr);
1651 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1652 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1653 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1654 SourceLocation IILoc,
1657 ParsedType &SuggestedType,
1658 bool IsTemplateName = false);
1660 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1661 /// type name has failed in a dependent context. In these situations, we
1662 /// automatically form a DependentTypeName that will retry lookup in a related
1663 /// scope during instantiation.
1664 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1665 SourceLocation NameLoc,
1666 bool IsTemplateTypeArg);
1668 /// \brief Describes the result of the name lookup and resolution performed
1669 /// by \c ClassifyName().
1670 enum NameClassificationKind {
1676 NC_NestedNameSpecifier,
1682 class NameClassification {
1683 NameClassificationKind Kind;
1685 TemplateName Template;
1687 const IdentifierInfo *Keyword;
1689 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1692 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1694 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1696 NameClassification(const IdentifierInfo *Keyword)
1697 : Kind(NC_Keyword), Keyword(Keyword) { }
1699 static NameClassification Error() {
1700 return NameClassification(NC_Error);
1703 static NameClassification Unknown() {
1704 return NameClassification(NC_Unknown);
1707 static NameClassification NestedNameSpecifier() {
1708 return NameClassification(NC_NestedNameSpecifier);
1711 static NameClassification TypeTemplate(TemplateName Name) {
1712 NameClassification Result(NC_TypeTemplate);
1713 Result.Template = Name;
1717 static NameClassification VarTemplate(TemplateName Name) {
1718 NameClassification Result(NC_VarTemplate);
1719 Result.Template = Name;
1723 static NameClassification FunctionTemplate(TemplateName Name) {
1724 NameClassification Result(NC_FunctionTemplate);
1725 Result.Template = Name;
1729 NameClassificationKind getKind() const { return Kind; }
1731 ParsedType getType() const {
1732 assert(Kind == NC_Type);
1736 ExprResult getExpression() const {
1737 assert(Kind == NC_Expression);
1741 TemplateName getTemplateName() const {
1742 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1743 Kind == NC_VarTemplate);
1747 TemplateNameKind getTemplateNameKind() const {
1749 case NC_TypeTemplate:
1750 return TNK_Type_template;
1751 case NC_FunctionTemplate:
1752 return TNK_Function_template;
1753 case NC_VarTemplate:
1754 return TNK_Var_template;
1756 llvm_unreachable("unsupported name classification.");
1761 /// \brief Perform name lookup on the given name, classifying it based on
1762 /// the results of name lookup and the following token.
1764 /// This routine is used by the parser to resolve identifiers and help direct
1765 /// parsing. When the identifier cannot be found, this routine will attempt
1766 /// to correct the typo and classify based on the resulting name.
1768 /// \param S The scope in which we're performing name lookup.
1770 /// \param SS The nested-name-specifier that precedes the name.
1772 /// \param Name The identifier. If typo correction finds an alternative name,
1773 /// this pointer parameter will be updated accordingly.
1775 /// \param NameLoc The location of the identifier.
1777 /// \param NextToken The token following the identifier. Used to help
1778 /// disambiguate the name.
1780 /// \param IsAddressOfOperand True if this name is the operand of a unary
1781 /// address of ('&') expression, assuming it is classified as an
1784 /// \param CCC The correction callback, if typo correction is desired.
1786 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1787 SourceLocation NameLoc, const Token &NextToken,
1788 bool IsAddressOfOperand,
1789 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1791 /// Describes the detailed kind of a template name. Used in diagnostics.
1792 enum class TemplateNameKindForDiagnostics {
1797 TemplateTemplateParam,
1800 TemplateNameKindForDiagnostics
1801 getTemplateNameKindForDiagnostics(TemplateName Name);
1803 /// Determine whether it's plausible that E was intended to be a
1805 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1806 if (!getLangOpts().CPlusPlus || E.isInvalid())
1808 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1809 return !DRE->hasExplicitTemplateArgs();
1810 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1811 return !ME->hasExplicitTemplateArgs();
1812 // Any additional cases recognized here should also be handled by
1813 // diagnoseExprIntendedAsTemplateName.
1816 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1817 SourceLocation Less,
1818 SourceLocation Greater);
1820 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1822 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1823 MultiTemplateParamsArg TemplateParameterLists);
1824 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1825 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1826 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1827 DeclarationName Name,
1828 SourceLocation Loc);
1830 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1831 SourceLocation FallbackLoc,
1832 SourceLocation ConstQualLoc = SourceLocation(),
1833 SourceLocation VolatileQualLoc = SourceLocation(),
1834 SourceLocation RestrictQualLoc = SourceLocation(),
1835 SourceLocation AtomicQualLoc = SourceLocation(),
1836 SourceLocation UnalignedQualLoc = SourceLocation());
1838 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1839 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1840 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1841 const LookupResult &R);
1842 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1843 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1844 const LookupResult &R);
1845 void CheckShadow(Scope *S, VarDecl *D);
1847 /// Warn if 'E', which is an expression that is about to be modified, refers
1848 /// to a shadowing declaration.
1849 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1851 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1854 /// Map of current shadowing declarations to shadowed declarations. Warn if
1855 /// it looks like the user is trying to modify the shadowing declaration.
1856 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1859 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1860 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1861 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1862 TypedefNameDecl *NewTD);
1863 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1864 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1865 TypeSourceInfo *TInfo,
1866 LookupResult &Previous);
1867 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1868 LookupResult &Previous, bool &Redeclaration);
1869 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1870 TypeSourceInfo *TInfo,
1871 LookupResult &Previous,
1872 MultiTemplateParamsArg TemplateParamLists,
1874 ArrayRef<BindingDecl *> Bindings = None);
1876 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1877 MultiTemplateParamsArg TemplateParamLists);
1878 // Returns true if the variable declaration is a redeclaration
1879 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1880 void CheckVariableDeclarationType(VarDecl *NewVD);
1881 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1883 void CheckCompleteVariableDeclaration(VarDecl *VD);
1884 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1885 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1887 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1888 TypeSourceInfo *TInfo,
1889 LookupResult &Previous,
1890 MultiTemplateParamsArg TemplateParamLists,
1892 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1894 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1895 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1897 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1898 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1899 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1900 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1901 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1902 // Returns true if the function declaration is a redeclaration
1903 bool CheckFunctionDeclaration(Scope *S,
1904 FunctionDecl *NewFD, LookupResult &Previous,
1905 bool IsMemberSpecialization);
1906 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1907 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1908 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1909 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1910 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1913 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1914 SourceLocation NameLoc, IdentifierInfo *Name,
1915 QualType T, TypeSourceInfo *TSInfo,
1917 void ActOnParamDefaultArgument(Decl *param,
1918 SourceLocation EqualLoc,
1920 void ActOnParamUnparsedDefaultArgument(Decl *param,
1921 SourceLocation EqualLoc,
1922 SourceLocation ArgLoc);
1923 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1924 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1925 SourceLocation EqualLoc);
1927 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1928 void ActOnUninitializedDecl(Decl *dcl);
1929 void ActOnInitializerError(Decl *Dcl);
1931 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1932 void ActOnCXXForRangeDecl(Decl *D);
1933 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1934 IdentifierInfo *Ident,
1935 ParsedAttributes &Attrs,
1936 SourceLocation AttrEnd);
1937 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1938 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1939 void FinalizeDeclaration(Decl *D);
1940 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1941 ArrayRef<Decl *> Group);
1942 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1944 /// Should be called on all declarations that might have attached
1945 /// documentation comments.
1946 void ActOnDocumentableDecl(Decl *D);
1947 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1949 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1950 SourceLocation LocAfterDecls);
1951 void CheckForFunctionRedefinition(
1952 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1953 SkipBodyInfo *SkipBody = nullptr);
1954 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1955 MultiTemplateParamsArg TemplateParamLists,
1956 SkipBodyInfo *SkipBody = nullptr);
1957 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1958 SkipBodyInfo *SkipBody = nullptr);
1959 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1960 bool isObjCMethodDecl(Decl *D) {
1961 return D && isa<ObjCMethodDecl>(D);
1964 /// \brief Determine whether we can delay parsing the body of a function or
1965 /// function template until it is used, assuming we don't care about emitting
1966 /// code for that function.
1968 /// This will be \c false if we may need the body of the function in the
1969 /// middle of parsing an expression (where it's impractical to switch to
1970 /// parsing a different function), for instance, if it's constexpr in C++11
1971 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1972 bool canDelayFunctionBody(const Declarator &D);
1974 /// \brief Determine whether we can skip parsing the body of a function
1975 /// definition, assuming we don't care about analyzing its body or emitting
1976 /// code for that function.
1978 /// This will be \c false only if we may need the body of the function in
1979 /// order to parse the rest of the program (for instance, if it is
1980 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1981 bool canSkipFunctionBody(Decl *D);
1983 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1984 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1985 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1986 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1987 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1989 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1990 /// attribute for which parsing is delayed.
1991 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1993 /// \brief Diagnose any unused parameters in the given sequence of
1994 /// ParmVarDecl pointers.
1995 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1997 /// \brief Diagnose whether the size of parameters or return value of a
1998 /// function or obj-c method definition is pass-by-value and larger than a
1999 /// specified threshold.
2001 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2002 QualType ReturnTy, NamedDecl *D);
2004 void DiagnoseInvalidJumps(Stmt *Body);
2005 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2006 SourceLocation AsmLoc,
2007 SourceLocation RParenLoc);
2009 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2010 Decl *ActOnEmptyDeclaration(Scope *S,
2011 AttributeList *AttrList,
2012 SourceLocation SemiLoc);
2014 enum class ModuleDeclKind {
2015 Module, ///< 'module X;'
2016 Partition, ///< 'module partition X;'
2017 Implementation, ///< 'module implementation X;'
2020 /// The parser has processed a module-declaration that begins the definition
2021 /// of a module interface or implementation.
2022 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2023 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2026 /// \brief The parser has processed a module import declaration.
2028 /// \param AtLoc The location of the '@' symbol, if any.
2030 /// \param ImportLoc The location of the 'import' keyword.
2032 /// \param Path The module access path.
2033 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2036 /// \brief The parser has processed a module import translated from a
2037 /// #include or similar preprocessing directive.
2038 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2039 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2041 /// \brief The parsed has entered a submodule.
2042 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2043 /// \brief The parser has left a submodule.
2044 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2046 /// \brief Create an implicit import of the given module at the given
2047 /// source location, for error recovery, if possible.
2049 /// This routine is typically used when an entity found by name lookup
2050 /// is actually hidden within a module that we know about but the user
2051 /// has forgotten to import.
2052 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2055 /// Kinds of missing import. Note, the values of these enumerators correspond
2056 /// to %select values in diagnostics.
2057 enum class MissingImportKind {
2061 ExplicitSpecialization,
2062 PartialSpecialization
2065 /// \brief Diagnose that the specified declaration needs to be visible but
2066 /// isn't, and suggest a module import that would resolve the problem.
2067 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2068 MissingImportKind MIK, bool Recover = true);
2069 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2070 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2071 MissingImportKind MIK, bool Recover);
2073 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2074 SourceLocation LBraceLoc);
2075 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2076 SourceLocation RBraceLoc);
2078 /// \brief We've found a use of a templated declaration that would trigger an
2079 /// implicit instantiation. Check that any relevant explicit specializations
2080 /// and partial specializations are visible, and diagnose if not.
2081 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2083 /// \brief We've found a use of a template specialization that would select a
2084 /// partial specialization. Check that the partial specialization is visible,
2085 /// and diagnose if not.
2086 void checkPartialSpecializationVisibility(SourceLocation Loc,
2089 /// \brief Retrieve a suitable printing policy.
2090 PrintingPolicy getPrintingPolicy() const {
2091 return getPrintingPolicy(Context, PP);
2094 /// \brief Retrieve a suitable printing policy.
2095 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2096 const Preprocessor &PP);
2099 void ActOnPopScope(SourceLocation Loc, Scope *S);
2100 void ActOnTranslationUnitScope(Scope *S);
2102 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2103 RecordDecl *&AnonRecord);
2104 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2105 MultiTemplateParamsArg TemplateParams,
2106 bool IsExplicitInstantiation,
2107 RecordDecl *&AnonRecord);
2109 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2112 const PrintingPolicy &Policy);
2114 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2115 RecordDecl *Record);
2117 /// Common ways to introduce type names without a tag for use in diagnostics.
2118 /// Keep in sync with err_tag_reference_non_tag.
2127 NTK_TypeAliasTemplate,
2128 NTK_TemplateTemplateArgument,
2131 /// Given a non-tag type declaration, returns an enum useful for indicating
2132 /// what kind of non-tag type this is.
2133 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2135 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2136 TagTypeKind NewTag, bool isDefinition,
2137 SourceLocation NewTagLoc,
2138 const IdentifierInfo *Name);
2141 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2142 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2143 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2144 TUK_Friend // Friend declaration: 'friend struct foo;'
2147 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2148 SourceLocation KWLoc, CXXScopeSpec &SS,
2149 IdentifierInfo *Name, SourceLocation NameLoc,
2150 AttributeList *Attr, AccessSpecifier AS,
2151 SourceLocation ModulePrivateLoc,
2152 MultiTemplateParamsArg TemplateParameterLists,
2153 bool &OwnedDecl, bool &IsDependent,
2154 SourceLocation ScopedEnumKWLoc,
2155 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2156 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2157 SkipBodyInfo *SkipBody = nullptr);
2159 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2160 unsigned TagSpec, SourceLocation TagLoc,
2162 IdentifierInfo *Name, SourceLocation NameLoc,
2163 AttributeList *Attr,
2164 MultiTemplateParamsArg TempParamLists);
2166 TypeResult ActOnDependentTag(Scope *S,
2169 const CXXScopeSpec &SS,
2170 IdentifierInfo *Name,
2171 SourceLocation TagLoc,
2172 SourceLocation NameLoc);
2174 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2175 IdentifierInfo *ClassName,
2176 SmallVectorImpl<Decl *> &Decls);
2177 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2178 Declarator &D, Expr *BitfieldWidth);
2180 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2181 Declarator &D, Expr *BitfieldWidth,
2182 InClassInitStyle InitStyle,
2183 AccessSpecifier AS);
2184 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2185 SourceLocation DeclStart,
2186 Declarator &D, Expr *BitfieldWidth,
2187 InClassInitStyle InitStyle,
2189 AttributeList *MSPropertyAttr);
2191 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2192 TypeSourceInfo *TInfo,
2193 RecordDecl *Record, SourceLocation Loc,
2194 bool Mutable, Expr *BitfieldWidth,
2195 InClassInitStyle InitStyle,
2196 SourceLocation TSSL,
2197 AccessSpecifier AS, NamedDecl *PrevDecl,
2198 Declarator *D = nullptr);
2200 bool CheckNontrivialField(FieldDecl *FD);
2201 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2202 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2203 bool Diagnose = false);
2204 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2205 void ActOnLastBitfield(SourceLocation DeclStart,
2206 SmallVectorImpl<Decl *> &AllIvarDecls);
2207 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2208 Declarator &D, Expr *BitfieldWidth,
2209 tok::ObjCKeywordKind visibility);
2211 // This is used for both record definitions and ObjC interface declarations.
2212 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2213 ArrayRef<Decl *> Fields,
2214 SourceLocation LBrac, SourceLocation RBrac,
2215 AttributeList *AttrList);
2217 /// ActOnTagStartDefinition - Invoked when we have entered the
2218 /// scope of a tag's definition (e.g., for an enumeration, class,
2219 /// struct, or union).
2220 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2222 typedef void *SkippedDefinitionContext;
2224 /// \brief Invoked when we enter a tag definition that we're skipping.
2225 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2227 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2229 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2230 /// C++ record definition's base-specifiers clause and are starting its
2231 /// member declarations.
2232 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2233 SourceLocation FinalLoc,
2234 bool IsFinalSpelledSealed,
2235 SourceLocation LBraceLoc);
2237 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2238 /// the definition of a tag (enumeration, class, struct, or union).
2239 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2240 SourceRange BraceRange);
2242 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2244 void ActOnObjCContainerFinishDefinition();
2246 /// \brief Invoked when we must temporarily exit the objective-c container
2247 /// scope for parsing/looking-up C constructs.
2249 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2250 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2251 void ActOnObjCReenterContainerContext(DeclContext *DC);
2253 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2254 /// error parsing the definition of a tag.
2255 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2257 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2258 EnumConstantDecl *LastEnumConst,
2259 SourceLocation IdLoc,
2262 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2263 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2264 QualType EnumUnderlyingTy,
2265 bool EnumUnderlyingIsImplicit,
2266 const EnumDecl *Prev);
2268 /// Determine whether the body of an anonymous enumeration should be skipped.
2269 /// \param II The name of the first enumerator.
2270 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2271 SourceLocation IILoc);
2273 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2274 SourceLocation IdLoc, IdentifierInfo *Id,
2275 AttributeList *Attrs,
2276 SourceLocation EqualLoc, Expr *Val);
2277 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2279 ArrayRef<Decl *> Elements,
2280 Scope *S, AttributeList *Attr);
2282 DeclContext *getContainingDC(DeclContext *DC);
2284 /// Set the current declaration context until it gets popped.
2285 void PushDeclContext(Scope *S, DeclContext *DC);
2286 void PopDeclContext();
2288 /// EnterDeclaratorContext - Used when we must lookup names in the context
2289 /// of a declarator's nested name specifier.
2290 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2291 void ExitDeclaratorContext(Scope *S);
2293 /// Push the parameters of D, which must be a function, into scope.
2294 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2295 void ActOnExitFunctionContext();
2297 DeclContext *getFunctionLevelDeclContext();
2299 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2300 /// to the function decl for the function being parsed. If we're currently
2301 /// in a 'block', this returns the containing context.
2302 FunctionDecl *getCurFunctionDecl();
2304 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2305 /// the method decl for the method being parsed. If we're currently
2306 /// in a 'block', this returns the containing context.
2307 ObjCMethodDecl *getCurMethodDecl();
2309 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2310 /// or C function we're in, otherwise return null. If we're currently
2311 /// in a 'block', this returns the containing context.
2312 NamedDecl *getCurFunctionOrMethodDecl();
2314 /// Add this decl to the scope shadowed decl chains.
2315 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2317 /// \brief Make the given externally-produced declaration visible at the
2318 /// top level scope.
2320 /// \param D The externally-produced declaration to push.
2322 /// \param Name The name of the externally-produced declaration.
2323 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2325 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2326 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2327 /// true if 'D' belongs to the given declaration context.
2329 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2330 /// enclosing namespace set of the context, rather than contained
2331 /// directly within it.
2332 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2333 bool AllowInlineNamespace = false);
2335 /// Finds the scope corresponding to the given decl context, if it
2336 /// happens to be an enclosing scope. Otherwise return NULL.
2337 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2339 /// Subroutines of ActOnDeclarator().
2340 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2341 TypeSourceInfo *TInfo);
2342 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2344 /// \brief Describes the kind of merge to perform for availability
2345 /// attributes (including "deprecated", "unavailable", and "availability").
2346 enum AvailabilityMergeKind {
2347 /// \brief Don't merge availability attributes at all.
2349 /// \brief Merge availability attributes for a redeclaration, which requires
2352 /// \brief Merge availability attributes for an override, which requires
2353 /// an exact match or a weakening of constraints.
2355 /// \brief Merge availability attributes for an implementation of
2356 /// a protocol requirement.
2357 AMK_ProtocolImplementation,
2360 /// Attribute merging methods. Return true if a new attribute was added.
2361 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2362 IdentifierInfo *Platform,
2364 VersionTuple Introduced,
2365 VersionTuple Deprecated,
2366 VersionTuple Obsoleted,
2369 bool IsStrict, StringRef Replacement,
2370 AvailabilityMergeKind AMK,
2371 unsigned AttrSpellingListIndex);
2372 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2373 TypeVisibilityAttr::VisibilityType Vis,
2374 unsigned AttrSpellingListIndex);
2375 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2376 VisibilityAttr::VisibilityType Vis,
2377 unsigned AttrSpellingListIndex);
2378 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2379 unsigned AttrSpellingListIndex, StringRef Uuid);
2380 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2381 unsigned AttrSpellingListIndex);
2382 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2383 unsigned AttrSpellingListIndex);
2385 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2386 unsigned AttrSpellingListIndex,
2387 MSInheritanceAttr::Spelling SemanticSpelling);
2388 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2389 IdentifierInfo *Format, int FormatIdx,
2390 int FirstArg, unsigned AttrSpellingListIndex);
2391 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2392 unsigned AttrSpellingListIndex);
2393 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2394 IdentifierInfo *Ident,
2395 unsigned AttrSpellingListIndex);
2396 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2397 unsigned AttrSpellingListIndex);
2398 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2399 unsigned AttrSpellingListIndex);
2400 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2401 IdentifierInfo *Ident,
2402 unsigned AttrSpellingListIndex);
2403 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2404 unsigned AttrSpellingListIndex);
2406 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2407 AvailabilityMergeKind AMK = AMK_Redeclaration);
2408 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2409 LookupResult &OldDecls);
2410 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2411 bool MergeTypeWithOld);
2412 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2413 Scope *S, bool MergeTypeWithOld);
2414 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2415 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2416 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2417 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2418 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2419 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2420 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2422 // AssignmentAction - This is used by all the assignment diagnostic functions
2423 // to represent what is actually causing the operation
2424 enum AssignmentAction {
2432 AA_Passing_CFAudited
2435 /// C++ Overloading.
2437 /// This is a legitimate overload: the existing declarations are
2438 /// functions or function templates with different signatures.
2441 /// This is not an overload because the signature exactly matches
2442 /// an existing declaration.
2445 /// This is not an overload because the lookup results contain a
2449 OverloadKind CheckOverload(Scope *S,
2451 const LookupResult &OldDecls,
2452 NamedDecl *&OldDecl,
2453 bool IsForUsingDecl);
2454 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2455 bool ConsiderCudaAttrs = true);
2457 /// \brief Checks availability of the function depending on the current
2458 /// function context.Inside an unavailable function,unavailability is ignored.
2460 /// \returns true if \p FD is unavailable and current context is inside
2461 /// an available function, false otherwise.
2462 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2464 ImplicitConversionSequence
2465 TryImplicitConversion(Expr *From, QualType ToType,
2466 bool SuppressUserConversions,
2468 bool InOverloadResolution,
2470 bool AllowObjCWritebackConversion);
2472 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2473 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2474 bool IsComplexPromotion(QualType FromType, QualType ToType);
2475 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2476 bool InOverloadResolution,
2477 QualType& ConvertedType, bool &IncompatibleObjC);
2478 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2479 QualType& ConvertedType, bool &IncompatibleObjC);
2480 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2481 QualType &ConvertedType);
2482 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2483 QualType& ConvertedType);
2484 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2485 const FunctionProtoType *NewType,
2486 unsigned *ArgPos = nullptr);
2487 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2488 QualType FromType, QualType ToType);
2490 void maybeExtendBlockObject(ExprResult &E);
2491 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2492 bool CheckPointerConversion(Expr *From, QualType ToType,
2494 CXXCastPath& BasePath,
2495 bool IgnoreBaseAccess,
2496 bool Diagnose = true);
2497 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2498 bool InOverloadResolution,
2499 QualType &ConvertedType);
2500 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2502 CXXCastPath &BasePath,
2503 bool IgnoreBaseAccess);
2504 bool IsQualificationConversion(QualType FromType, QualType ToType,
2505 bool CStyle, bool &ObjCLifetimeConversion);
2506 bool IsFunctionConversion(QualType FromType, QualType ToType,
2507 QualType &ResultTy);
2508 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2509 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2511 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2512 const VarDecl *NRVOCandidate,
2513 QualType ResultType,
2515 bool AllowNRVO = true);
2517 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2519 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2520 SourceLocation EqualLoc,
2522 bool TopLevelOfInitList = false,
2523 bool AllowExplicit = false);
2524 ExprResult PerformObjectArgumentInitialization(Expr *From,
2525 NestedNameSpecifier *Qualifier,
2526 NamedDecl *FoundDecl,
2527 CXXMethodDecl *Method);
2529 ExprResult PerformContextuallyConvertToBool(Expr *From);
2530 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2532 /// Contexts in which a converted constant expression is required.
2534 CCEK_CaseValue, ///< Expression in a case label.
2535 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2536 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2537 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2538 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2540 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2541 llvm::APSInt &Value, CCEKind CCE);
2542 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2543 APValue &Value, CCEKind CCE);
2545 /// \brief Abstract base class used to perform a contextual implicit
2546 /// conversion from an expression to any type passing a filter.
2547 class ContextualImplicitConverter {
2550 bool SuppressConversion;
2552 ContextualImplicitConverter(bool Suppress = false,
2553 bool SuppressConversion = false)
2554 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2556 /// \brief Determine whether the specified type is a valid destination type
2557 /// for this conversion.
2558 virtual bool match(QualType T) = 0;
2560 /// \brief Emits a diagnostic complaining that the expression does not have
2561 /// integral or enumeration type.
2562 virtual SemaDiagnosticBuilder
2563 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2565 /// \brief Emits a diagnostic when the expression has incomplete class type.
2566 virtual SemaDiagnosticBuilder
2567 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2569 /// \brief Emits a diagnostic when the only matching conversion function
2571 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2572 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2574 /// \brief Emits a note for the explicit conversion function.
2575 virtual SemaDiagnosticBuilder
2576 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2578 /// \brief Emits a diagnostic when there are multiple possible conversion
2580 virtual SemaDiagnosticBuilder
2581 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2583 /// \brief Emits a note for one of the candidate conversions.
2584 virtual SemaDiagnosticBuilder
2585 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2587 /// \brief Emits a diagnostic when we picked a conversion function
2588 /// (for cases when we are not allowed to pick a conversion function).
2589 virtual SemaDiagnosticBuilder diagnoseConversion(
2590 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2592 virtual ~ContextualImplicitConverter() {}
2595 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2596 bool AllowScopedEnumerations;
2599 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2600 bool Suppress, bool SuppressConversion)
2601 : ContextualImplicitConverter(Suppress, SuppressConversion),
2602 AllowScopedEnumerations(AllowScopedEnumerations) {}
2604 /// Match an integral or (possibly scoped) enumeration type.
2605 bool match(QualType T) override;
2607 SemaDiagnosticBuilder
2608 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2609 return diagnoseNotInt(S, Loc, T);
2612 /// \brief Emits a diagnostic complaining that the expression does not have
2613 /// integral or enumeration type.
2614 virtual SemaDiagnosticBuilder
2615 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2618 /// Perform a contextual implicit conversion.
2619 ExprResult PerformContextualImplicitConversion(
2620 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2623 enum ObjCSubscriptKind {
2628 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2630 // Note that LK_String is intentionally after the other literals, as
2631 // this is used for diagnostics logic.
2632 enum ObjCLiteralKind {
2641 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2643 ExprResult PerformObjectMemberConversion(Expr *From,
2644 NestedNameSpecifier *Qualifier,
2645 NamedDecl *FoundDecl,
2648 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2649 // TODO: make this is a typesafe union.
2650 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2651 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2653 void AddOverloadCandidate(FunctionDecl *Function,
2654 DeclAccessPair FoundDecl,
2655 ArrayRef<Expr *> Args,
2656 OverloadCandidateSet &CandidateSet,
2657 bool SuppressUserConversions = false,
2658 bool PartialOverloading = false,
2659 bool AllowExplicit = false,
2660 ConversionSequenceList EarlyConversions = None);
2661 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2662 ArrayRef<Expr *> Args,
2663 OverloadCandidateSet &CandidateSet,
2664 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2665 bool SuppressUserConversions = false,
2666 bool PartialOverloading = false);
2667 void AddMethodCandidate(DeclAccessPair FoundDecl,
2668 QualType ObjectType,
2669 Expr::Classification ObjectClassification,
2670 ArrayRef<Expr *> Args,
2671 OverloadCandidateSet& CandidateSet,
2672 bool SuppressUserConversion = false);
2673 void AddMethodCandidate(CXXMethodDecl *Method,
2674 DeclAccessPair FoundDecl,
2675 CXXRecordDecl *ActingContext, QualType ObjectType,
2676 Expr::Classification ObjectClassification,
2677 ArrayRef<Expr *> Args,
2678 OverloadCandidateSet& CandidateSet,
2679 bool SuppressUserConversions = false,
2680 bool PartialOverloading = false,
2681 ConversionSequenceList EarlyConversions = None);
2682 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2683 DeclAccessPair FoundDecl,
2684 CXXRecordDecl *ActingContext,
2685 TemplateArgumentListInfo *ExplicitTemplateArgs,
2686 QualType ObjectType,
2687 Expr::Classification ObjectClassification,
2688 ArrayRef<Expr *> Args,
2689 OverloadCandidateSet& CandidateSet,
2690 bool SuppressUserConversions = false,
2691 bool PartialOverloading = false);
2692 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2693 DeclAccessPair FoundDecl,
2694 TemplateArgumentListInfo *ExplicitTemplateArgs,
2695 ArrayRef<Expr *> Args,
2696 OverloadCandidateSet& CandidateSet,
2697 bool SuppressUserConversions = false,
2698 bool PartialOverloading = false);
2699 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2700 ArrayRef<QualType> ParamTypes,
2701 ArrayRef<Expr *> Args,
2702 OverloadCandidateSet &CandidateSet,
2703 ConversionSequenceList &Conversions,
2704 bool SuppressUserConversions,
2705 CXXRecordDecl *ActingContext = nullptr,
2706 QualType ObjectType = QualType(),
2707 Expr::Classification
2708 ObjectClassification = {});
2709 void AddConversionCandidate(CXXConversionDecl *Conversion,
2710 DeclAccessPair FoundDecl,
2711 CXXRecordDecl *ActingContext,
2712 Expr *From, QualType ToType,
2713 OverloadCandidateSet& CandidateSet,
2714 bool AllowObjCConversionOnExplicit);
2715 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2716 DeclAccessPair FoundDecl,
2717 CXXRecordDecl *ActingContext,
2718 Expr *From, QualType ToType,
2719 OverloadCandidateSet &CandidateSet,
2720 bool AllowObjCConversionOnExplicit);
2721 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2722 DeclAccessPair FoundDecl,
2723 CXXRecordDecl *ActingContext,
2724 const FunctionProtoType *Proto,
2725 Expr *Object, ArrayRef<Expr *> Args,
2726 OverloadCandidateSet& CandidateSet);
2727 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2728 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2729 OverloadCandidateSet& CandidateSet,
2730 SourceRange OpRange = SourceRange());
2731 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2732 OverloadCandidateSet& CandidateSet,
2733 bool IsAssignmentOperator = false,
2734 unsigned NumContextualBoolArguments = 0);
2735 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2736 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2737 OverloadCandidateSet& CandidateSet);
2738 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2740 ArrayRef<Expr *> Args,
2741 TemplateArgumentListInfo *ExplicitTemplateArgs,
2742 OverloadCandidateSet& CandidateSet,
2743 bool PartialOverloading = false);
2745 // Emit as a 'note' the specific overload candidate
2746 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2747 QualType DestType = QualType(),
2748 bool TakingAddress = false);
2750 // Emit as a series of 'note's all template and non-templates identified by
2751 // the expression Expr
2752 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2753 bool TakingAddress = false);
2755 /// Check the enable_if expressions on the given function. Returns the first
2756 /// failing attribute, or NULL if they were all successful.
2757 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2758 bool MissingImplicitThis = false);
2760 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2761 /// non-ArgDependent DiagnoseIfAttrs.
2763 /// Argument-dependent diagnose_if attributes should be checked each time a
2764 /// function is used as a direct callee of a function call.
2766 /// Returns true if any errors were emitted.
2767 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2768 const Expr *ThisArg,
2769 ArrayRef<const Expr *> Args,
2770 SourceLocation Loc);
2772 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2773 /// ArgDependent DiagnoseIfAttrs.
2775 /// Argument-independent diagnose_if attributes should be checked on every use
2778 /// Returns true if any errors were emitted.
2779 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2780 SourceLocation Loc);
2782 /// Returns whether the given function's address can be taken or not,
2783 /// optionally emitting a diagnostic if the address can't be taken.
2785 /// Returns false if taking the address of the function is illegal.
2786 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2787 bool Complain = false,
2788 SourceLocation Loc = SourceLocation());
2790 // [PossiblyAFunctionType] --> [Return]
2791 // NonFunctionType --> NonFunctionType
2793 // R (*)(A) --> R (A)
2794 // R (&)(A) --> R (A)
2795 // R (S::*)(A) --> R (A)
2796 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2799 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2800 QualType TargetType,
2802 DeclAccessPair &Found,
2803 bool *pHadMultipleCandidates = nullptr);
2806 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2807 DeclAccessPair &FoundResult);
2809 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2810 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2813 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2814 bool Complain = false,
2815 DeclAccessPair *Found = nullptr);
2817 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2818 ExprResult &SrcExpr,
2819 bool DoFunctionPointerConverion = false,
2820 bool Complain = false,
2821 SourceRange OpRangeForComplaining = SourceRange(),
2822 QualType DestTypeForComplaining = QualType(),
2823 unsigned DiagIDForComplaining = 0);
2826 Expr *FixOverloadedFunctionReference(Expr *E,
2827 DeclAccessPair FoundDecl,
2829 ExprResult FixOverloadedFunctionReference(ExprResult,
2830 DeclAccessPair FoundDecl,
2833 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2834 ArrayRef<Expr *> Args,
2835 OverloadCandidateSet &CandidateSet,
2836 bool PartialOverloading = false);
2838 // An enum used to represent the different possible results of building a
2839 // range-based for loop.
2840 enum ForRangeStatus {
2842 FRS_NoViableFunction,
2843 FRS_DiagnosticIssued
2846 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2847 SourceLocation RangeLoc,
2848 const DeclarationNameInfo &NameInfo,
2849 LookupResult &MemberLookup,
2850 OverloadCandidateSet *CandidateSet,
2851 Expr *Range, ExprResult *CallExpr);
2853 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2854 UnresolvedLookupExpr *ULE,
2855 SourceLocation LParenLoc,
2857 SourceLocation RParenLoc,
2859 bool AllowTypoCorrection=true,
2860 bool CalleesAddressIsTaken=false);
2862 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2863 MultiExprArg Args, SourceLocation RParenLoc,
2864 OverloadCandidateSet *CandidateSet,
2865 ExprResult *Result);
2867 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2868 UnaryOperatorKind Opc,
2869 const UnresolvedSetImpl &Fns,
2872 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2873 BinaryOperatorKind Opc,
2874 const UnresolvedSetImpl &Fns,
2875 Expr *LHS, Expr *RHS);
2877 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2878 SourceLocation RLoc,
2879 Expr *Base,Expr *Idx);
2882 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2883 SourceLocation LParenLoc,
2885 SourceLocation RParenLoc);
2887 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2889 SourceLocation RParenLoc);
2891 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2892 SourceLocation OpLoc,
2893 bool *NoArrowOperatorFound = nullptr);
2895 /// CheckCallReturnType - Checks that a call expression's return type is
2896 /// complete. Returns true on failure. The location passed in is the location
2897 /// that best represents the call.
2898 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2899 CallExpr *CE, FunctionDecl *FD);
2901 /// Helpers for dealing with blocks and functions.
2902 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2903 bool CheckParameterNames);
2904 void CheckCXXDefaultArguments(FunctionDecl *FD);
2905 void CheckExtraCXXDefaultArguments(Declarator &D);
2906 Scope *getNonFieldDeclScope(Scope *S);
2908 /// \name Name lookup
2910 /// These routines provide name lookup that is used during semantic
2911 /// analysis to resolve the various kinds of names (identifiers,
2912 /// overloaded operator names, constructor names, etc.) into zero or
2913 /// more declarations within a particular scope. The major entry
2914 /// points are LookupName, which performs unqualified name lookup,
2915 /// and LookupQualifiedName, which performs qualified name lookup.
2917 /// All name lookup is performed based on some specific criteria,
2918 /// which specify what names will be visible to name lookup and how
2919 /// far name lookup should work. These criteria are important both
2920 /// for capturing language semantics (certain lookups will ignore
2921 /// certain names, for example) and for performance, since name
2922 /// lookup is often a bottleneck in the compilation of C++. Name
2923 /// lookup criteria is specified via the LookupCriteria enumeration.
2925 /// The results of name lookup can vary based on the kind of name
2926 /// lookup performed, the current language, and the translation
2927 /// unit. In C, for example, name lookup will either return nothing
2928 /// (no entity found) or a single declaration. In C++, name lookup
2929 /// can additionally refer to a set of overloaded functions or
2930 /// result in an ambiguity. All of the possible results of name
2931 /// lookup are captured by the LookupResult class, which provides
2932 /// the ability to distinguish among them.
2935 /// @brief Describes the kind of name lookup to perform.
2936 enum LookupNameKind {
2937 /// Ordinary name lookup, which finds ordinary names (functions,
2938 /// variables, typedefs, etc.) in C and most kinds of names
2939 /// (functions, variables, members, types, etc.) in C++.
2940 LookupOrdinaryName = 0,
2941 /// Tag name lookup, which finds the names of enums, classes,
2942 /// structs, and unions.
2944 /// Label name lookup.
2946 /// Member name lookup, which finds the names of
2947 /// class/struct/union members.
2949 /// Look up of an operator name (e.g., operator+) for use with
2950 /// operator overloading. This lookup is similar to ordinary name
2951 /// lookup, but will ignore any declarations that are class members.
2953 /// Look up of a name that precedes the '::' scope resolution
2954 /// operator in C++. This lookup completely ignores operator, object,
2955 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2956 LookupNestedNameSpecifierName,
2957 /// Look up a namespace name within a C++ using directive or
2958 /// namespace alias definition, ignoring non-namespace names (C++
2959 /// [basic.lookup.udir]p1).
2960 LookupNamespaceName,
2961 /// Look up all declarations in a scope with the given name,
2962 /// including resolved using declarations. This is appropriate
2963 /// for checking redeclarations for a using declaration.
2964 LookupUsingDeclName,
2965 /// Look up an ordinary name that is going to be redeclared as a
2966 /// name with linkage. This lookup ignores any declarations that
2967 /// are outside of the current scope unless they have linkage. See
2968 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2969 LookupRedeclarationWithLinkage,
2970 /// Look up a friend of a local class. This lookup does not look
2971 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2972 LookupLocalFriendName,
2973 /// Look up the name of an Objective-C protocol.
2974 LookupObjCProtocolName,
2975 /// Look up implicit 'self' parameter of an objective-c method.
2976 LookupObjCImplicitSelfParam,
2977 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2978 LookupOMPReductionName,
2979 /// \brief Look up any declaration with any name.
2983 /// \brief Specifies whether (or how) name lookup is being performed for a
2984 /// redeclaration (vs. a reference).
2985 enum RedeclarationKind {
2986 /// \brief The lookup is a reference to this name that is not for the
2987 /// purpose of redeclaring the name.
2988 NotForRedeclaration = 0,
2989 /// \brief The lookup results will be used for redeclaration of a name,
2990 /// if an entity by that name already exists.
2994 /// \brief The possible outcomes of name lookup for a literal operator.
2995 enum LiteralOperatorLookupResult {
2996 /// \brief The lookup resulted in an error.
2998 /// \brief The lookup found a single 'cooked' literal operator, which
2999 /// expects a normal literal to be built and passed to it.
3001 /// \brief The lookup found a single 'raw' literal operator, which expects
3002 /// a string literal containing the spelling of the literal token.
3004 /// \brief The lookup found an overload set of literal operator templates,
3005 /// which expect the characters of the spelling of the literal token to be
3006 /// passed as a non-type template argument pack.
3008 /// \brief The lookup found an overload set of literal operator templates,
3009 /// which expect the character type and characters of the spelling of the
3010 /// string literal token to be passed as template arguments.
3014 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3015 CXXSpecialMember SM,
3022 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3023 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3024 TypoRecoveryCallback;
3027 bool CppLookupName(LookupResult &R, Scope *S);
3029 struct TypoExprState {
3030 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3031 TypoDiagnosticGenerator DiagHandler;
3032 TypoRecoveryCallback RecoveryHandler;
3034 TypoExprState(TypoExprState &&other) noexcept;
3035 TypoExprState &operator=(TypoExprState &&other) noexcept;
3038 /// \brief The set of unhandled TypoExprs and their associated state.
3039 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3041 /// \brief Creates a new TypoExpr AST node.
3042 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3043 TypoDiagnosticGenerator TDG,
3044 TypoRecoveryCallback TRC);
3046 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3048 // The boolean value will be true to indicate that the namespace was loaded
3049 // from an AST/PCH file, or false otherwise.
3050 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3052 /// \brief Whether we have already loaded known namespaces from an extenal
3054 bool LoadedExternalKnownNamespaces;
3056 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3057 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3058 /// should be skipped entirely.
3059 std::unique_ptr<TypoCorrectionConsumer>
3060 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3061 Sema::LookupNameKind LookupKind, Scope *S,
3063 std::unique_ptr<CorrectionCandidateCallback> CCC,
3064 DeclContext *MemberContext, bool EnteringContext,
3065 const ObjCObjectPointerType *OPT,
3066 bool ErrorRecovery);
3069 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3071 /// \brief Clears the state of the given TypoExpr.
3072 void clearDelayedTypo(TypoExpr *TE);
3074 /// \brief Look up a name, looking for a single declaration. Return
3075 /// null if the results were absent, ambiguous, or overloaded.
3077 /// It is preferable to use the elaborated form and explicitly handle
3078 /// ambiguity and overloaded.
3079 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3081 LookupNameKind NameKind,
3082 RedeclarationKind Redecl
3083 = NotForRedeclaration);
3084 bool LookupName(LookupResult &R, Scope *S,
3085 bool AllowBuiltinCreation = false);
3086 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3087 bool InUnqualifiedLookup = false);
3088 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3090 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3091 bool AllowBuiltinCreation = false,
3092 bool EnteringContext = false);
3093 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3094 RedeclarationKind Redecl
3095 = NotForRedeclaration);
3096 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3098 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3099 QualType T1, QualType T2,
3100 UnresolvedSetImpl &Functions);
3102 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3103 SourceLocation GnuLabelLoc = SourceLocation());
3105 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3106 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3107 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3109 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3110 bool RValueThis, unsigned ThisQuals);
3111 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3113 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3114 bool RValueThis, unsigned ThisQuals);
3115 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3117 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3118 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3119 ArrayRef<QualType> ArgTys,
3122 bool AllowStringTemplate);
3123 bool isKnownName(StringRef name);
3125 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3126 ArrayRef<Expr *> Args, ADLResult &Functions);
3128 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3129 VisibleDeclConsumer &Consumer,
3130 bool IncludeGlobalScope = true);
3131 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3132 VisibleDeclConsumer &Consumer,
3133 bool IncludeGlobalScope = true,
3134 bool IncludeDependentBases = false);
3136 enum CorrectTypoKind {
3137 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3138 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3141 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3142 Sema::LookupNameKind LookupKind,
3143 Scope *S, CXXScopeSpec *SS,
3144 std::unique_ptr<CorrectionCandidateCallback> CCC,
3145 CorrectTypoKind Mode,
3146 DeclContext *MemberContext = nullptr,
3147 bool EnteringContext = false,
3148 const ObjCObjectPointerType *OPT = nullptr,
3149 bool RecordFailure = true);
3151 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3152 Sema::LookupNameKind LookupKind, Scope *S,
3154 std::unique_ptr<CorrectionCandidateCallback> CCC,
3155 TypoDiagnosticGenerator TDG,
3156 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3157 DeclContext *MemberContext = nullptr,
3158 bool EnteringContext = false,
3159 const ObjCObjectPointerType *OPT = nullptr);
3161 /// \brief Process any TypoExprs in the given Expr and its children,
3162 /// generating diagnostics as appropriate and returning a new Expr if there
3163 /// were typos that were all successfully corrected and ExprError if one or
3164 /// more typos could not be corrected.
3166 /// \param E The Expr to check for TypoExprs.
3168 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3171 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3172 /// it is an acceptable/usable result from a single combination of typo
3173 /// corrections. As long as the filter returns ExprError, different
3174 /// combinations of corrections will be tried until all are exhausted.
3176 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3177 llvm::function_ref<ExprResult(Expr *)> Filter =
3178 [](Expr *E) -> ExprResult { return E; });
3181 CorrectDelayedTyposInExpr(Expr *E,
3182 llvm::function_ref<ExprResult(Expr *)> Filter) {
3183 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3187 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3188 llvm::function_ref<ExprResult(Expr *)> Filter =
3189 [](Expr *E) -> ExprResult { return E; }) {
3190 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3194 CorrectDelayedTyposInExpr(ExprResult ER,
3195 llvm::function_ref<ExprResult(Expr *)> Filter) {
3196 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3199 void diagnoseTypo(const TypoCorrection &Correction,
3200 const PartialDiagnostic &TypoDiag,
3201 bool ErrorRecovery = true);
3203 void diagnoseTypo(const TypoCorrection &Correction,
3204 const PartialDiagnostic &TypoDiag,
3205 const PartialDiagnostic &PrevNote,
3206 bool ErrorRecovery = true);
3208 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3210 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3211 ArrayRef<Expr *> Args,
3212 AssociatedNamespaceSet &AssociatedNamespaces,
3213 AssociatedClassSet &AssociatedClasses);
3215 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3216 bool ConsiderLinkage, bool AllowInlineNamespace);
3218 void DiagnoseAmbiguousLookup(LookupResult &Result);
3221 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3222 SourceLocation IdLoc,
3223 bool TypoCorrection = false);
3224 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3225 Scope *S, bool ForRedeclaration,
3226 SourceLocation Loc);
3227 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3229 void AddKnownFunctionAttributes(FunctionDecl *FD);
3231 // More parsing and symbol table subroutines.
3233 void ProcessPragmaWeak(Scope *S, Decl *D);
3234 // Decl attributes - this routine is the top level dispatcher.
3235 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3236 // Helper for delayed processing of attributes.
3237 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3238 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3239 bool IncludeCXX11Attributes = true);
3240 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3241 const AttributeList *AttrList);
3243 void checkUnusedDeclAttributes(Declarator &D);
3245 /// Determine if type T is a valid subject for a nonnull and similar
3246 /// attributes. By default, we look through references (the behavior used by
3247 /// nonnull), but if the second parameter is true, then we treat a reference
3249 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3251 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3252 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3253 const FunctionDecl *FD = nullptr);
3254 bool CheckNoReturnAttr(const AttributeList &attr);
3255 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3256 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3257 unsigned ArgNum, StringRef &Str,
3258 SourceLocation *ArgLocation = nullptr);
3259 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3260 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3261 bool checkMSInheritanceAttrOnDefinition(
3262 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3263 MSInheritanceAttr::Spelling SemanticSpelling);
3265 void CheckAlignasUnderalignment(Decl *D);
3267 /// Adjust the calling convention of a method to be the ABI default if it
3268 /// wasn't specified explicitly. This handles method types formed from
3269 /// function type typedefs and typename template arguments.
3270 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3271 SourceLocation Loc);
3273 // Check if there is an explicit attribute, but only look through parens.
3274 // The intent is to look for an attribute on the current declarator, but not
3275 // one that came from a typedef.
3276 bool hasExplicitCallingConv(QualType &T);
3278 /// Get the outermost AttributedType node that sets a calling convention.
3279 /// Valid types should not have multiple attributes with different CCs.
3280 const AttributedType *getCallingConvAttributedType(QualType T) const;
3282 /// Check whether a nullability type specifier can be added to the given
3285 /// \param type The type to which the nullability specifier will be
3286 /// added. On success, this type will be updated appropriately.
3288 /// \param nullability The nullability specifier to add.
3290 /// \param nullabilityLoc The location of the nullability specifier.
3292 /// \param isContextSensitive Whether this nullability specifier was
3293 /// written as a context-sensitive keyword (in an Objective-C
3294 /// method) or an Objective-C property attribute, rather than as an
3295 /// underscored type specifier.
3297 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3298 /// array type (e.g., because it will decay to a pointer).
3300 /// \returns true if nullability cannot be applied, false otherwise.
3301 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3302 SourceLocation nullabilityLoc,
3303 bool isContextSensitive,
3304 bool allowArrayTypes);
3306 /// \brief Stmt attributes - this routine is the top level dispatcher.
3307 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3310 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3311 ObjCMethodDecl *MethodDecl,
3312 bool IsProtocolMethodDecl);
3314 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3315 ObjCMethodDecl *Overridden,
3316 bool IsProtocolMethodDecl);
3318 /// WarnExactTypedMethods - This routine issues a warning if method
3319 /// implementation declaration matches exactly that of its declaration.
3320 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3321 ObjCMethodDecl *MethodDecl,
3322 bool IsProtocolMethodDecl);
3324 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3326 /// CheckImplementationIvars - This routine checks if the instance variables
3327 /// listed in the implelementation match those listed in the interface.
3328 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3329 ObjCIvarDecl **Fields, unsigned nIvars,
3330 SourceLocation Loc);
3332 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3333 /// remains unimplemented in the class or category \@implementation.
3334 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3335 ObjCContainerDecl* IDecl,
3336 bool IncompleteImpl = false);
3338 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3339 /// which must be implemented by this implementation.
3340 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3341 ObjCContainerDecl *CDecl,
3342 bool SynthesizeProperties);
3344 /// Diagnose any null-resettable synthesized setters.
3345 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3347 /// DefaultSynthesizeProperties - This routine default synthesizes all
3348 /// properties which must be synthesized in the class's \@implementation.
3349 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3350 ObjCInterfaceDecl *IDecl);
3351 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3353 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3354 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3355 /// declared in class 'IFace'.
3356 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3357 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3359 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3360 /// backs the property is not used in the property's accessor.
3361 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3362 const ObjCImplementationDecl *ImplD);
3364 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3365 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3366 /// It also returns ivar's property on success.
3367 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3368 const ObjCPropertyDecl *&PDecl) const;
3370 /// Called by ActOnProperty to handle \@property declarations in
3371 /// class extensions.
3372 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3373 SourceLocation AtLoc,
3374 SourceLocation LParenLoc,
3375 FieldDeclarator &FD,
3377 SourceLocation GetterNameLoc,
3379 SourceLocation SetterNameLoc,
3380 const bool isReadWrite,
3381 unsigned &Attributes,
3382 const unsigned AttributesAsWritten,
3384 TypeSourceInfo *TSI,
3385 tok::ObjCKeywordKind MethodImplKind);
3387 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3388 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3389 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3390 ObjCContainerDecl *CDecl,
3391 SourceLocation AtLoc,
3392 SourceLocation LParenLoc,
3393 FieldDeclarator &FD,
3395 SourceLocation GetterNameLoc,
3397 SourceLocation SetterNameLoc,
3398 const bool isReadWrite,
3399 const unsigned Attributes,
3400 const unsigned AttributesAsWritten,
3402 TypeSourceInfo *TSI,
3403 tok::ObjCKeywordKind MethodImplKind,
3404 DeclContext *lexicalDC = nullptr);
3406 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3407 /// warning) when atomic property has one but not the other user-declared
3408 /// setter or getter.
3409 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3410 ObjCInterfaceDecl* IDecl);
3412 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3414 void DiagnoseMissingDesignatedInitOverrides(
3415 const ObjCImplementationDecl *ImplD,
3416 const ObjCInterfaceDecl *IFD);
3418 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3420 enum MethodMatchStrategy {
3425 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3426 /// true, or false, accordingly.
3427 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3428 const ObjCMethodDecl *PrevMethod,
3429 MethodMatchStrategy strategy = MMS_strict);
3431 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3432 /// or protocol against those declared in their implementations.
3433 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3434 const SelectorSet &ClsMap,
3435 SelectorSet &InsMapSeen,
3436 SelectorSet &ClsMapSeen,
3437 ObjCImplDecl* IMPDecl,
3438 ObjCContainerDecl* IDecl,
3439 bool &IncompleteImpl,
3440 bool ImmediateClass,
3441 bool WarnCategoryMethodImpl=false);
3443 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3444 /// category matches with those implemented in its primary class and
3445 /// warns each time an exact match is found.
3446 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3448 /// \brief Add the given method to the list of globally-known methods.
3449 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3452 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3453 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3454 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3456 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3457 /// optionally warns if there are multiple signatures.
3458 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3459 bool receiverIdOrClass,
3463 /// \brief - Returns instance or factory methods in global method pool for
3464 /// given selector. It checks the desired kind first, if none is found, and
3465 /// parameter checkTheOther is set, it then checks the other kind. If no such
3466 /// method or only one method is found, function returns false; otherwise, it
3469 CollectMultipleMethodsInGlobalPool(Selector Sel,
3470 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3471 bool InstanceFirst, bool CheckTheOther,
3472 const ObjCObjectType *TypeBound = nullptr);
3475 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3476 SourceRange R, bool receiverIdOrClass,
3477 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3480 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3481 Selector Sel, SourceRange R,
3482 bool receiverIdOrClass);
3485 /// \brief - Returns a selector which best matches given argument list or
3486 /// nullptr if none could be found
3487 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3489 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3492 /// \brief Record the typo correction failure and return an empty correction.
3493 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3494 bool RecordFailure = true) {
3496 TypoCorrectionFailures[Typo].insert(TypoLoc);
3497 return TypoCorrection();
3501 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3502 /// unit are added to a global pool. This allows us to efficiently associate
3503 /// a selector with a method declaraation for purposes of typechecking
3504 /// messages sent to "id" (where the class of the object is unknown).
3505 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3506 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3509 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3510 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3511 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3514 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3516 void AddAnyMethodToGlobalPool(Decl *D);
3518 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3519 /// there are multiple signatures.
3520 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3521 bool receiverIdOrClass=false) {
3522 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3526 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3527 /// there are multiple signatures.
3528 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3529 bool receiverIdOrClass=false) {
3530 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3534 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3535 QualType ObjectType=QualType());
3536 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3538 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3540 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3542 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3543 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3545 //===--------------------------------------------------------------------===//
3546 // Statement Parsing Callbacks: SemaStmt.cpp.
3550 FullExprArg() : E(nullptr) { }
3551 FullExprArg(Sema &actions) : E(nullptr) { }
3553 ExprResult release() {
3557 Expr *get() const { return E; }
3559 Expr *operator->() {
3564 // FIXME: No need to make the entire Sema class a friend when it's just
3565 // Sema::MakeFullExpr that needs access to the constructor below.
3568 explicit FullExprArg(Expr *expr) : E(expr) {}
3573 FullExprArg MakeFullExpr(Expr *Arg) {
3574 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3576 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3577 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3579 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3581 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3582 /*DiscardedValue*/ true);
3583 return FullExprArg(FE.get());
3586 StmtResult ActOnExprStmt(ExprResult Arg);
3587 StmtResult ActOnExprStmtError();
3589 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3590 bool HasLeadingEmptyMacro = false);
3592 void ActOnStartOfCompoundStmt();
3593 void ActOnFinishOfCompoundStmt();
3594 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3595 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3597 /// \brief A RAII object to enter scope of a compound statement.
3598 class CompoundScopeRAII {
3600 CompoundScopeRAII(Sema &S): S(S) {
3601 S.ActOnStartOfCompoundStmt();
3604 ~CompoundScopeRAII() {
3605 S.ActOnFinishOfCompoundStmt();
3612 /// An RAII helper that pops function a function scope on exit.
3613 struct FunctionScopeRAII {
3616 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3617 ~FunctionScopeRAII() {
3619 S.PopFunctionScopeInfo();
3621 void disable() { Active = false; }
3624 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3625 SourceLocation StartLoc,
3626 SourceLocation EndLoc);
3627 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3628 StmtResult ActOnForEachLValueExpr(Expr *E);
3629 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3630 SourceLocation DotDotDotLoc, Expr *RHSVal,
3631 SourceLocation ColonLoc);
3632 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3634 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3635 SourceLocation ColonLoc,
3636 Stmt *SubStmt, Scope *CurScope);
3637 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3638 SourceLocation ColonLoc, Stmt *SubStmt);
3640 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3641 ArrayRef<const Attr*> Attrs,
3644 class ConditionResult;
3645 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3647 ConditionResult Cond, Stmt *ThenVal,
3648 SourceLocation ElseLoc, Stmt *ElseVal);
3649 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3651 ConditionResult Cond, Stmt *ThenVal,
3652 SourceLocation ElseLoc, Stmt *ElseVal);
3653 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3655 ConditionResult Cond);
3656 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3657 Stmt *Switch, Stmt *Body);
3658 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3660 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3661 SourceLocation WhileLoc, SourceLocation CondLParen,
3662 Expr *Cond, SourceLocation CondRParen);
3664 StmtResult ActOnForStmt(SourceLocation ForLoc,
3665 SourceLocation LParenLoc,
3667 ConditionResult Second,
3669 SourceLocation RParenLoc,
3671 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3673 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3674 Stmt *First, Expr *collection,
3675 SourceLocation RParenLoc);
3676 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3678 enum BuildForRangeKind {
3679 /// Initial building of a for-range statement.
3681 /// Instantiation or recovery rebuild of a for-range statement. Don't
3682 /// attempt any typo-correction.
3684 /// Determining whether a for-range statement could be built. Avoid any
3685 /// unnecessary or irreversible actions.
3689 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3690 SourceLocation CoawaitLoc,
3692 SourceLocation ColonLoc, Expr *Collection,
3693 SourceLocation RParenLoc,
3694 BuildForRangeKind Kind);
3695 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3696 SourceLocation CoawaitLoc,
3697 SourceLocation ColonLoc,
3698 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3699 Expr *Cond, Expr *Inc,
3701 SourceLocation RParenLoc,
3702 BuildForRangeKind Kind);
3703 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3705 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3706 SourceLocation LabelLoc,
3707 LabelDecl *TheDecl);
3708 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3709 SourceLocation StarLoc,
3711 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3712 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3714 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3715 CapturedRegionKind Kind, unsigned NumParams);
3716 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3717 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3718 CapturedRegionKind Kind,
3719 ArrayRef<CapturedParamNameType> Params);
3720 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3721 void ActOnCapturedRegionError();
3722 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3724 unsigned NumParams);
3725 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3726 bool AllowParamOrMoveConstructible);
3727 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3728 bool AllowParamOrMoveConstructible);
3730 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3732 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3733 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3735 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3736 bool IsVolatile, unsigned NumOutputs,
3737 unsigned NumInputs, IdentifierInfo **Names,
3738 MultiExprArg Constraints, MultiExprArg Exprs,
3739 Expr *AsmString, MultiExprArg Clobbers,
3740 SourceLocation RParenLoc);
3742 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3743 SourceLocation TemplateKWLoc,
3745 llvm::InlineAsmIdentifierInfo &Info,
3746 bool IsUnevaluatedContext);
3747 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3748 unsigned &Offset, SourceLocation AsmLoc);
3749 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3750 llvm::InlineAsmIdentifierInfo &Info,
3751 SourceLocation AsmLoc);
3752 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3753 ArrayRef<Token> AsmToks,
3754 StringRef AsmString,
3755 unsigned NumOutputs, unsigned NumInputs,
3756 ArrayRef<StringRef> Constraints,
3757 ArrayRef<StringRef> Clobbers,
3758 ArrayRef<Expr*> Exprs,
3759 SourceLocation EndLoc);
3760 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3761 SourceLocation Location,
3764 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3765 SourceLocation StartLoc,
3766 SourceLocation IdLoc, IdentifierInfo *Id,
3767 bool Invalid = false);
3769 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3771 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3772 Decl *Parm, Stmt *Body);
3774 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3776 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3777 MultiStmtArg Catch, Stmt *Finally);
3779 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3780 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3782 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3784 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3788 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3790 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3791 SourceLocation StartLoc,
3792 SourceLocation IdLoc,
3793 IdentifierInfo *Id);
3795 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3797 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3798 Decl *ExDecl, Stmt *HandlerBlock);
3799 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3800 ArrayRef<Stmt *> Handlers);
3802 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3803 SourceLocation TryLoc, Stmt *TryBlock,
3805 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3808 void ActOnStartSEHFinallyBlock();
3809 void ActOnAbortSEHFinallyBlock();
3810 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3811 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3813 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3815 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3817 /// \brief If it's a file scoped decl that must warn if not used, keep track
3819 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3821 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3822 /// whose result is unused, warn.
3823 void DiagnoseUnusedExprResult(const Stmt *S);
3824 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3825 void DiagnoseUnusedDecl(const NamedDecl *ND);
3827 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3828 /// statement as a \p Body, and it is located on the same line.
3830 /// This helps prevent bugs due to typos, such as:
3833 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3837 /// Warn if a for/while loop statement \p S, which is followed by
3838 /// \p PossibleBody, has a suspicious null statement as a body.
3839 void DiagnoseEmptyLoopBody(const Stmt *S,
3840 const Stmt *PossibleBody);
3842 /// Warn if a value is moved to itself.
3843 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3844 SourceLocation OpLoc);
3846 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3848 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3849 SourceLocation Loc);
3851 /// Warn when implicitly casting 0 to nullptr.
3852 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3854 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3855 return DelayedDiagnostics.push(pool);
3857 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3859 typedef ProcessingContextState ParsingClassState;
3860 ParsingClassState PushParsingClass() {
3861 return DelayedDiagnostics.pushUndelayed();
3863 void PopParsingClass(ParsingClassState state) {
3864 DelayedDiagnostics.popUndelayed(state);
3867 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3869 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3870 StringRef Message, SourceLocation Loc,
3871 const ObjCInterfaceDecl *UnknownObjCClass,
3872 const ObjCPropertyDecl *ObjCProperty,
3873 bool ObjCPropertyAccess);
3875 bool makeUnavailableInSystemHeader(SourceLocation loc,
3876 UnavailableAttr::ImplicitReason reason);
3878 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3879 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3881 //===--------------------------------------------------------------------===//
3882 // Expression Parsing Callbacks: SemaExpr.cpp.
3884 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3885 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3886 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3887 bool ObjCPropertyAccess=false);
3888 void NoteDeletedFunction(FunctionDecl *FD);
3889 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3890 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3891 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3892 ObjCMethodDecl *Getter,
3893 SourceLocation Loc);
3894 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3895 ArrayRef<Expr *> Args);
3897 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3898 Decl *LambdaContextDecl = nullptr,
3899 bool IsDecltype = false);
3900 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3901 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3902 ReuseLambdaContextDecl_t,
3903 bool IsDecltype = false);
3904 void PopExpressionEvaluationContext();
3906 void DiscardCleanupsInEvaluationContext();
3908 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3909 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3911 ExprResult ActOnConstantExpression(ExprResult Res);
3913 // Functions for marking a declaration referenced. These functions also
3914 // contain the relevant logic for marking if a reference to a function or
3915 // variable is an odr-use (in the C++11 sense). There are separate variants
3916 // for expressions referring to a decl; these exist because odr-use marking
3917 // needs to be delayed for some constant variables when we build one of the
3918 // named expressions.
3920 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3921 // should usually be true. This only needs to be set to false if the lack of
3922 // odr-use cannot be determined from the current context (for instance,
3923 // because the name denotes a virtual function and was written without an
3924 // explicit nested-name-specifier).
3925 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3926 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3927 bool MightBeOdrUse = true);
3928 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3929 void MarkDeclRefReferenced(DeclRefExpr *E);
3930 void MarkMemberReferenced(MemberExpr *E);
3932 void UpdateMarkingForLValueToRValue(Expr *E);
3933 void CleanupVarDeclMarking();
3935 enum TryCaptureKind {
3936 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3939 /// \brief Try to capture the given variable.
3941 /// \param Var The variable to capture.
3943 /// \param Loc The location at which the capture occurs.
3945 /// \param Kind The kind of capture, which may be implicit (for either a
3946 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3948 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3949 /// an explicit lambda capture.
3951 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3952 /// captures or diagnose errors. If false, this routine merely check whether
3953 /// the capture can occur without performing the capture itself or complaining
3954 /// if the variable cannot be captured.
3956 /// \param CaptureType Will be set to the type of the field used to capture
3957 /// this variable in the innermost block or lambda. Only valid when the
3958 /// variable can be captured.
3960 /// \param DeclRefType Will be set to the type of a reference to the capture
3961 /// from within the current scope. Only valid when the variable can be
3964 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3965 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3966 /// This is useful when enclosing lambdas must speculatively capture
3967 /// variables that may or may not be used in certain specializations of
3968 /// a nested generic lambda.
3970 /// \returns true if an error occurred (i.e., the variable cannot be
3971 /// captured) and false if the capture succeeded.
3972 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3973 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3974 QualType &CaptureType,
3975 QualType &DeclRefType,
3976 const unsigned *const FunctionScopeIndexToStopAt);
3978 /// \brief Try to capture the given variable.
3979 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3980 TryCaptureKind Kind = TryCapture_Implicit,
3981 SourceLocation EllipsisLoc = SourceLocation());
3983 /// \brief Checks if the variable must be captured.
3984 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3986 /// \brief Given a variable, determine the type that a reference to that
3987 /// variable will have in the given scope.
3988 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3990 /// Mark all of the declarations referenced within a particular AST node as
3991 /// referenced. Used when template instantiation instantiates a non-dependent
3992 /// type -- entities referenced by the type are now referenced.
3993 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3994 void MarkDeclarationsReferencedInExpr(Expr *E,
3995 bool SkipLocalVariables = false);
3997 /// \brief Try to recover by turning the given expression into a
3998 /// call. Returns true if recovery was attempted or an error was
3999 /// emitted; this may also leave the ExprResult invalid.
4000 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4001 bool ForceComplain = false,
4002 bool (*IsPlausibleResult)(QualType) = nullptr);
4004 /// \brief Figure out if an expression could be turned into a call.
4005 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4006 UnresolvedSetImpl &NonTemplateOverloads);
4008 /// \brief Conditionally issue a diagnostic based on the current
4009 /// evaluation context.
4011 /// \param Statement If Statement is non-null, delay reporting the
4012 /// diagnostic until the function body is parsed, and then do a basic
4013 /// reachability analysis to determine if the statement is reachable.
4014 /// If it is unreachable, the diagnostic will not be emitted.
4015 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4016 const PartialDiagnostic &PD);
4018 // Primary Expressions.
4019 SourceRange getExprRange(Expr *E) const;
4021 ExprResult ActOnIdExpression(
4022 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4023 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4024 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4025 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4027 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4028 TemplateArgumentListInfo &Buffer,
4029 DeclarationNameInfo &NameInfo,
4030 const TemplateArgumentListInfo *&TemplateArgs);
4033 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4034 std::unique_ptr<CorrectionCandidateCallback> CCC,
4035 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4036 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4038 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4040 bool AllowBuiltinCreation=false);
4042 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4043 SourceLocation TemplateKWLoc,
4044 const DeclarationNameInfo &NameInfo,
4045 bool isAddressOfOperand,
4046 const TemplateArgumentListInfo *TemplateArgs);
4048 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4051 const CXXScopeSpec *SS = nullptr);
4053 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4054 const DeclarationNameInfo &NameInfo,
4055 const CXXScopeSpec *SS = nullptr,
4056 NamedDecl *FoundD = nullptr,
4057 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4059 BuildAnonymousStructUnionMemberReference(
4060 const CXXScopeSpec &SS,
4061 SourceLocation nameLoc,
4062 IndirectFieldDecl *indirectField,
4063 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4064 Expr *baseObjectExpr = nullptr,
4065 SourceLocation opLoc = SourceLocation());
4067 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4068 SourceLocation TemplateKWLoc,
4070 const TemplateArgumentListInfo *TemplateArgs,
4072 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4073 SourceLocation TemplateKWLoc,
4075 const TemplateArgumentListInfo *TemplateArgs,
4076 bool IsDefiniteInstance,
4078 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4079 const LookupResult &R,
4080 bool HasTrailingLParen);
4083 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4084 const DeclarationNameInfo &NameInfo,
4085 bool IsAddressOfOperand, const Scope *S,
4086 TypeSourceInfo **RecoveryTSI = nullptr);
4088 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4089 SourceLocation TemplateKWLoc,
4090 const DeclarationNameInfo &NameInfo,
4091 const TemplateArgumentListInfo *TemplateArgs);
4093 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4096 bool AcceptInvalidDecl = false);
4097 ExprResult BuildDeclarationNameExpr(
4098 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4099 NamedDecl *FoundD = nullptr,
4100 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4101 bool AcceptInvalidDecl = false);
4103 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4104 DeclarationNameInfo &SuffixInfo,
4105 ArrayRef<Expr *> Args,
4106 SourceLocation LitEndLoc,
4107 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4109 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4110 PredefinedExpr::IdentType IT);
4111 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4112 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4114 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4116 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4117 ExprResult ActOnCharacterConstant(const Token &Tok,
4118 Scope *UDLScope = nullptr);
4119 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4120 ExprResult ActOnParenListExpr(SourceLocation L,
4124 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4125 /// fragments (e.g. "foo" "bar" L"baz").
4126 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4127 Scope *UDLScope = nullptr);
4129 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4130 SourceLocation DefaultLoc,
4131 SourceLocation RParenLoc,
4132 Expr *ControllingExpr,
4133 ArrayRef<ParsedType> ArgTypes,
4134 ArrayRef<Expr *> ArgExprs);
4135 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4136 SourceLocation DefaultLoc,
4137 SourceLocation RParenLoc,
4138 Expr *ControllingExpr,
4139 ArrayRef<TypeSourceInfo *> Types,
4140 ArrayRef<Expr *> Exprs);
4142 // Binary/Unary Operators. 'Tok' is the token for the operator.
4143 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4145 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4146 UnaryOperatorKind Opc, Expr *Input);
4147 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4148 tok::TokenKind Op, Expr *Input);
4150 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4152 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4153 SourceLocation OpLoc,
4154 UnaryExprOrTypeTrait ExprKind,
4156 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4157 UnaryExprOrTypeTrait ExprKind);
4159 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4160 UnaryExprOrTypeTrait ExprKind,
4161 bool IsType, void *TyOrEx,
4162 SourceRange ArgRange);
4164 ExprResult CheckPlaceholderExpr(Expr *E);
4165 bool CheckVecStepExpr(Expr *E);
4167 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4168 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4169 SourceRange ExprRange,
4170 UnaryExprOrTypeTrait ExprKind);
4171 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4172 SourceLocation OpLoc,
4173 IdentifierInfo &Name,
4174 SourceLocation NameLoc,
4175 SourceLocation RParenLoc);
4176 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4177 tok::TokenKind Kind, Expr *Input);
4179 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4180 Expr *Idx, SourceLocation RLoc);
4181 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4182 Expr *Idx, SourceLocation RLoc);
4183 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4184 Expr *LowerBound, SourceLocation ColonLoc,
4185 Expr *Length, SourceLocation RBLoc);
4187 // This struct is for use by ActOnMemberAccess to allow
4188 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4189 // changing the access operator from a '.' to a '->' (to see if that is the
4190 // change needed to fix an error about an unknown member, e.g. when the class
4191 // defines a custom operator->).
4192 struct ActOnMemberAccessExtraArgs {
4198 ExprResult BuildMemberReferenceExpr(
4199 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4200 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4201 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4202 const TemplateArgumentListInfo *TemplateArgs,
4204 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4207 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4208 bool IsArrow, const CXXScopeSpec &SS,
4209 SourceLocation TemplateKWLoc,
4210 NamedDecl *FirstQualifierInScope, LookupResult &R,
4211 const TemplateArgumentListInfo *TemplateArgs,
4213 bool SuppressQualifierCheck = false,
4214 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4216 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4217 SourceLocation OpLoc,
4218 const CXXScopeSpec &SS, FieldDecl *Field,
4219 DeclAccessPair FoundDecl,
4220 const DeclarationNameInfo &MemberNameInfo);
4222 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4224 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4225 const CXXScopeSpec &SS,
4226 const LookupResult &R);
4228 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4229 bool IsArrow, SourceLocation OpLoc,
4230 const CXXScopeSpec &SS,
4231 SourceLocation TemplateKWLoc,
4232 NamedDecl *FirstQualifierInScope,
4233 const DeclarationNameInfo &NameInfo,
4234 const TemplateArgumentListInfo *TemplateArgs);
4236 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4237 SourceLocation OpLoc,
4238 tok::TokenKind OpKind,
4240 SourceLocation TemplateKWLoc,
4241 UnqualifiedId &Member,
4244 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4245 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4246 FunctionDecl *FDecl,
4247 const FunctionProtoType *Proto,
4248 ArrayRef<Expr *> Args,
4249 SourceLocation RParenLoc,
4250 bool ExecConfig = false);
4251 void CheckStaticArrayArgument(SourceLocation CallLoc,
4253 const Expr *ArgExpr);
4255 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4256 /// This provides the location of the left/right parens and a list of comma
4258 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4259 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4260 Expr *ExecConfig = nullptr,
4261 bool IsExecConfig = false);
4262 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4263 SourceLocation LParenLoc,
4264 ArrayRef<Expr *> Arg,
4265 SourceLocation RParenLoc,
4266 Expr *Config = nullptr,
4267 bool IsExecConfig = false);
4269 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4270 MultiExprArg ExecConfig,
4271 SourceLocation GGGLoc);
4273 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4274 Declarator &D, ParsedType &Ty,
4275 SourceLocation RParenLoc, Expr *CastExpr);
4276 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4278 SourceLocation RParenLoc,
4280 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4282 /// \brief Build an altivec or OpenCL literal.
4283 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4284 SourceLocation RParenLoc, Expr *E,
4285 TypeSourceInfo *TInfo);
4287 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4289 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4291 SourceLocation RParenLoc,
4294 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4295 TypeSourceInfo *TInfo,
4296 SourceLocation RParenLoc,
4299 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4300 MultiExprArg InitArgList,
4301 SourceLocation RBraceLoc);
4303 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4309 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4312 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4313 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4314 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4315 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4316 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4317 Expr *LHSExpr, Expr *RHSExpr);
4319 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4321 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4322 /// in the case of a the GNU conditional expr extension.
4323 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4324 SourceLocation ColonLoc,
4325 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4327 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4328 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4329 LabelDecl *TheDecl);
4331 void ActOnStartStmtExpr();
4332 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4333 SourceLocation RPLoc); // "({..})"
4334 void ActOnStmtExprError();
4336 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4337 struct OffsetOfComponent {
4338 SourceLocation LocStart, LocEnd;
4339 bool isBrackets; // true if [expr], false if .ident
4341 IdentifierInfo *IdentInfo;
4346 /// __builtin_offsetof(type, a.b[123][456].c)
4347 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4348 TypeSourceInfo *TInfo,
4349 ArrayRef<OffsetOfComponent> Components,
4350 SourceLocation RParenLoc);
4351 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4352 SourceLocation BuiltinLoc,
4353 SourceLocation TypeLoc,
4354 ParsedType ParsedArgTy,
4355 ArrayRef<OffsetOfComponent> Components,
4356 SourceLocation RParenLoc);
4358 // __builtin_choose_expr(constExpr, expr1, expr2)
4359 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4360 Expr *CondExpr, Expr *LHSExpr,
4361 Expr *RHSExpr, SourceLocation RPLoc);
4363 // __builtin_va_arg(expr, type)
4364 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4365 SourceLocation RPLoc);
4366 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4367 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4370 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4372 bool CheckCaseExpression(Expr *E);
4374 /// \brief Describes the result of an "if-exists" condition check.
4375 enum IfExistsResult {
4376 /// \brief The symbol exists.
4379 /// \brief The symbol does not exist.
4382 /// \brief The name is a dependent name, so the results will differ
4383 /// from one instantiation to the next.
4386 /// \brief An error occurred.
4391 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4392 const DeclarationNameInfo &TargetNameInfo);
4395 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4396 bool IsIfExists, CXXScopeSpec &SS,
4397 UnqualifiedId &Name);
4399 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4401 NestedNameSpecifierLoc QualifierLoc,
4402 DeclarationNameInfo NameInfo,
4404 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4406 CXXScopeSpec &SS, UnqualifiedId &Name,
4409 //===------------------------- "Block" Extension ------------------------===//
4411 /// ActOnBlockStart - This callback is invoked when a block literal is
4413 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4415 /// ActOnBlockArguments - This callback allows processing of block arguments.
4416 /// If there are no arguments, this is still invoked.
4417 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4420 /// ActOnBlockError - If there is an error parsing a block, this callback
4421 /// is invoked to pop the information about the block from the action impl.
4422 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4424 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4425 /// literal was successfully completed. ^(int x){...}
4426 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4429 //===---------------------------- Clang Extensions ----------------------===//
4431 /// __builtin_convertvector(...)
4432 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4433 SourceLocation BuiltinLoc,
4434 SourceLocation RParenLoc);
4436 //===---------------------------- OpenCL Features -----------------------===//
4438 /// __builtin_astype(...)
4439 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4440 SourceLocation BuiltinLoc,
4441 SourceLocation RParenLoc);
4443 //===---------------------------- C++ Features --------------------------===//
4445 // Act on C++ namespaces
4446 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4447 SourceLocation NamespaceLoc,
4448 SourceLocation IdentLoc,
4449 IdentifierInfo *Ident,
4450 SourceLocation LBrace,
4451 AttributeList *AttrList,
4452 UsingDirectiveDecl * &UsingDecl);
4453 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4455 NamespaceDecl *getStdNamespace() const;
4456 NamespaceDecl *getOrCreateStdNamespace();
4458 NamespaceDecl *lookupStdExperimentalNamespace();
4460 CXXRecordDecl *getStdBadAlloc() const;
4461 EnumDecl *getStdAlignValT() const;
4463 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4464 /// it is and Element is not NULL, assigns the element type to Element.
4465 bool isStdInitializerList(QualType Ty, QualType *Element);
4467 /// \brief Looks for the std::initializer_list template and instantiates it
4468 /// with Element, or emits an error if it's not found.
4470 /// \returns The instantiated template, or null on error.
4471 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4473 /// \brief Determine whether Ctor is an initializer-list constructor, as
4474 /// defined in [dcl.init.list]p2.
4475 bool isInitListConstructor(const FunctionDecl *Ctor);
4477 Decl *ActOnUsingDirective(Scope *CurScope,
4478 SourceLocation UsingLoc,
4479 SourceLocation NamespcLoc,
4481 SourceLocation IdentLoc,
4482 IdentifierInfo *NamespcName,
4483 AttributeList *AttrList);
4485 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4487 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4488 SourceLocation NamespaceLoc,
4489 SourceLocation AliasLoc,
4490 IdentifierInfo *Alias,
4492 SourceLocation IdentLoc,
4493 IdentifierInfo *Ident);
4495 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4496 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4497 const LookupResult &PreviousDecls,
4498 UsingShadowDecl *&PrevShadow);
4499 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4501 UsingShadowDecl *PrevDecl);
4503 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4504 bool HasTypenameKeyword,
4505 const CXXScopeSpec &SS,
4506 SourceLocation NameLoc,
4507 const LookupResult &Previous);
4508 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4510 const CXXScopeSpec &SS,
4511 const DeclarationNameInfo &NameInfo,
4512 SourceLocation NameLoc);
4514 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4515 SourceLocation UsingLoc,
4516 bool HasTypenameKeyword,
4517 SourceLocation TypenameLoc,
4519 DeclarationNameInfo NameInfo,
4520 SourceLocation EllipsisLoc,
4521 AttributeList *AttrList,
4522 bool IsInstantiation);
4523 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4524 ArrayRef<NamedDecl *> Expansions);
4526 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4528 /// Given a derived-class using shadow declaration for a constructor and the
4529 /// correspnding base class constructor, find or create the implicit
4530 /// synthesized derived class constructor to use for this initialization.
4531 CXXConstructorDecl *
4532 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4533 ConstructorUsingShadowDecl *DerivedShadow);
4535 Decl *ActOnUsingDeclaration(Scope *CurScope,
4537 SourceLocation UsingLoc,
4538 SourceLocation TypenameLoc,
4540 UnqualifiedId &Name,
4541 SourceLocation EllipsisLoc,
4542 AttributeList *AttrList);
4543 Decl *ActOnAliasDeclaration(Scope *CurScope,
4545 MultiTemplateParamsArg TemplateParams,
4546 SourceLocation UsingLoc,
4547 UnqualifiedId &Name,
4548 AttributeList *AttrList,
4550 Decl *DeclFromDeclSpec);
4552 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4553 /// including handling of its default argument expressions.
4555 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4557 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4558 NamedDecl *FoundDecl,
4559 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4560 bool HadMultipleCandidates, bool IsListInitialization,
4561 bool IsStdInitListInitialization,
4562 bool RequiresZeroInit, unsigned ConstructKind,
4563 SourceRange ParenRange);
4565 /// Build a CXXConstructExpr whose constructor has already been resolved if
4566 /// it denotes an inherited constructor.
4568 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4569 CXXConstructorDecl *Constructor, bool Elidable,
4571 bool HadMultipleCandidates, bool IsListInitialization,
4572 bool IsStdInitListInitialization,
4573 bool RequiresZeroInit, unsigned ConstructKind,
4574 SourceRange ParenRange);
4576 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4577 // the constructor can be elidable?
4579 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4580 NamedDecl *FoundDecl,
4581 CXXConstructorDecl *Constructor, bool Elidable,
4582 MultiExprArg Exprs, bool HadMultipleCandidates,
4583 bool IsListInitialization,
4584 bool IsStdInitListInitialization, bool RequiresZeroInit,
4585 unsigned ConstructKind, SourceRange ParenRange);
4587 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4590 /// Instantiate or parse a C++ default argument expression as necessary.
4591 /// Return true on error.
4592 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4593 ParmVarDecl *Param);
4595 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4596 /// the default expr if needed.
4597 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4599 ParmVarDecl *Param);
4601 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4602 /// constructed variable.
4603 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4605 /// \brief Helper class that collects exception specifications for
4606 /// implicitly-declared special member functions.
4607 class ImplicitExceptionSpecification {
4608 // Pointer to allow copying
4610 // We order exception specifications thus:
4611 // noexcept is the most restrictive, but is only used in C++11.
4612 // throw() comes next.
4613 // Then a throw(collected exceptions)
4614 // Finally no specification, which is expressed as noexcept(false).
4615 // throw(...) is used instead if any called function uses it.
4616 ExceptionSpecificationType ComputedEST;
4617 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4618 SmallVector<QualType, 4> Exceptions;
4620 void ClearExceptions() {
4621 ExceptionsSeen.clear();
4626 explicit ImplicitExceptionSpecification(Sema &Self)
4627 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4628 if (!Self.getLangOpts().CPlusPlus11)
4629 ComputedEST = EST_DynamicNone;
4632 /// \brief Get the computed exception specification type.
4633 ExceptionSpecificationType getExceptionSpecType() const {
4634 assert(ComputedEST != EST_ComputedNoexcept &&
4635 "noexcept(expr) should not be a possible result");
4639 /// \brief The number of exceptions in the exception specification.
4640 unsigned size() const { return Exceptions.size(); }
4642 /// \brief The set of exceptions in the exception specification.
4643 const QualType *data() const { return Exceptions.data(); }
4645 /// \brief Integrate another called method into the collected data.
4646 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4648 /// \brief Integrate an invoked expression into the collected data.
4649 void CalledExpr(Expr *E);
4651 /// \brief Overwrite an EPI's exception specification with this
4652 /// computed exception specification.
4653 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4654 FunctionProtoType::ExceptionSpecInfo ESI;
4655 ESI.Type = getExceptionSpecType();
4656 if (ESI.Type == EST_Dynamic) {
4657 ESI.Exceptions = Exceptions;
4658 } else if (ESI.Type == EST_None) {
4659 /// C++11 [except.spec]p14:
4660 /// The exception-specification is noexcept(false) if the set of
4661 /// potential exceptions of the special member function contains "any"
4662 ESI.Type = EST_ComputedNoexcept;
4663 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4664 tok::kw_false).get();
4670 /// \brief Determine what sort of exception specification a defaulted
4671 /// copy constructor of a class will have.
4672 ImplicitExceptionSpecification
4673 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4676 /// \brief Determine what sort of exception specification a defaulted
4677 /// default constructor of a class will have, and whether the parameter
4679 ImplicitExceptionSpecification
4680 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4682 /// \brief Determine what sort of exception specification a defautled
4683 /// copy assignment operator of a class will have, and whether the
4684 /// parameter will be const.
4685 ImplicitExceptionSpecification
4686 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4688 /// \brief Determine what sort of exception specification a defaulted move
4689 /// constructor of a class will have.
4690 ImplicitExceptionSpecification
4691 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4693 /// \brief Determine what sort of exception specification a defaulted move
4694 /// assignment operator of a class will have.
4695 ImplicitExceptionSpecification
4696 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4698 /// \brief Determine what sort of exception specification a defaulted
4699 /// destructor of a class will have.
4700 ImplicitExceptionSpecification
4701 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4703 /// \brief Determine what sort of exception specification an inheriting
4704 /// constructor of a class will have.
4705 ImplicitExceptionSpecification
4706 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4707 CXXConstructorDecl *CD);
4709 /// \brief Evaluate the implicit exception specification for a defaulted
4710 /// special member function.
4711 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4713 /// \brief Check the given exception-specification and update the
4714 /// exception specification information with the results.
4715 void checkExceptionSpecification(bool IsTopLevel,
4716 ExceptionSpecificationType EST,
4717 ArrayRef<ParsedType> DynamicExceptions,
4718 ArrayRef<SourceRange> DynamicExceptionRanges,
4720 SmallVectorImpl<QualType> &Exceptions,
4721 FunctionProtoType::ExceptionSpecInfo &ESI);
4723 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4724 /// parse an exception specification to work around a libstdc++ bug.
4725 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4727 /// \brief Add an exception-specification to the given member function
4728 /// (or member function template). The exception-specification was parsed
4729 /// after the method itself was declared.
4730 void actOnDelayedExceptionSpecification(Decl *Method,
4731 ExceptionSpecificationType EST,
4732 SourceRange SpecificationRange,
4733 ArrayRef<ParsedType> DynamicExceptions,
4734 ArrayRef<SourceRange> DynamicExceptionRanges,
4735 Expr *NoexceptExpr);
4737 class InheritedConstructorInfo;
4739 /// \brief Determine if a special member function should have a deleted
4740 /// definition when it is defaulted.
4741 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4742 InheritedConstructorInfo *ICI = nullptr,
4743 bool Diagnose = false);
4745 /// \brief Declare the implicit default constructor for the given class.
4747 /// \param ClassDecl The class declaration into which the implicit
4748 /// default constructor will be added.
4750 /// \returns The implicitly-declared default constructor.
4751 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4752 CXXRecordDecl *ClassDecl);
4754 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4755 /// defining this constructor as the default constructor.
4756 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4757 CXXConstructorDecl *Constructor);
4759 /// \brief Declare the implicit destructor for the given class.
4761 /// \param ClassDecl The class declaration into which the implicit
4762 /// destructor will be added.
4764 /// \returns The implicitly-declared destructor.
4765 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4767 /// DefineImplicitDestructor - Checks for feasibility of
4768 /// defining this destructor as the default destructor.
4769 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4770 CXXDestructorDecl *Destructor);
4772 /// \brief Build an exception spec for destructors that don't have one.
4774 /// C++11 says that user-defined destructors with no exception spec get one
4775 /// that looks as if the destructor was implicitly declared.
4776 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4777 CXXDestructorDecl *Destructor);
4779 /// \brief Define the specified inheriting constructor.
4780 void DefineInheritingConstructor(SourceLocation UseLoc,
4781 CXXConstructorDecl *Constructor);
4783 /// \brief Declare the implicit copy constructor for the given class.
4785 /// \param ClassDecl The class declaration into which the implicit
4786 /// copy constructor will be added.
4788 /// \returns The implicitly-declared copy constructor.
4789 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4791 /// DefineImplicitCopyConstructor - Checks for feasibility of
4792 /// defining this constructor as the copy constructor.
4793 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4794 CXXConstructorDecl *Constructor);
4796 /// \brief Declare the implicit move constructor for the given class.
4798 /// \param ClassDecl The Class declaration into which the implicit
4799 /// move constructor will be added.
4801 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4803 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4805 /// DefineImplicitMoveConstructor - Checks for feasibility of
4806 /// defining this constructor as the move constructor.
4807 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4808 CXXConstructorDecl *Constructor);
4810 /// \brief Declare the implicit copy assignment operator for the given class.
4812 /// \param ClassDecl The class declaration into which the implicit
4813 /// copy assignment operator will be added.
4815 /// \returns The implicitly-declared copy assignment operator.
4816 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4818 /// \brief Defines an implicitly-declared copy assignment operator.
4819 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4820 CXXMethodDecl *MethodDecl);
4822 /// \brief Declare the implicit move assignment operator for the given class.
4824 /// \param ClassDecl The Class declaration into which the implicit
4825 /// move assignment operator will be added.
4827 /// \returns The implicitly-declared move assignment operator, or NULL if it
4828 /// wasn't declared.
4829 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4831 /// \brief Defines an implicitly-declared move assignment operator.
4832 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4833 CXXMethodDecl *MethodDecl);
4835 /// \brief Force the declaration of any implicitly-declared members of this
4837 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4839 /// \brief Check a completed declaration of an implicit special member.
4840 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4842 /// \brief Determine whether the given function is an implicitly-deleted
4843 /// special member function.
4844 bool isImplicitlyDeleted(FunctionDecl *FD);
4846 /// \brief Check whether 'this' shows up in the type of a static member
4847 /// function after the (naturally empty) cv-qualifier-seq would be.
4849 /// \returns true if an error occurred.
4850 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4852 /// \brief Whether this' shows up in the exception specification of a static
4853 /// member function.
4854 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4856 /// \brief Check whether 'this' shows up in the attributes of the given
4857 /// static member function.
4859 /// \returns true if an error occurred.
4860 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4862 /// MaybeBindToTemporary - If the passed in expression has a record type with
4863 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4864 /// it simply returns the passed in expression.
4865 ExprResult MaybeBindToTemporary(Expr *E);
4867 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4868 MultiExprArg ArgsPtr,
4870 SmallVectorImpl<Expr*> &ConvertedArgs,
4871 bool AllowExplicit = false,
4872 bool IsListInitialization = false);
4874 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4875 SourceLocation NameLoc,
4876 IdentifierInfo &Name);
4878 ParsedType getDestructorName(SourceLocation TildeLoc,
4879 IdentifierInfo &II, SourceLocation NameLoc,
4880 Scope *S, CXXScopeSpec &SS,
4881 ParsedType ObjectType,
4882 bool EnteringContext);
4884 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4885 ParsedType ObjectType);
4887 // Checks that reinterpret casts don't have undefined behavior.
4888 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4889 bool IsDereference, SourceRange Range);
4891 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4892 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4893 tok::TokenKind Kind,
4894 SourceLocation LAngleBracketLoc,
4896 SourceLocation RAngleBracketLoc,
4897 SourceLocation LParenLoc,
4899 SourceLocation RParenLoc);
4901 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4902 tok::TokenKind Kind,
4905 SourceRange AngleBrackets,
4906 SourceRange Parens);
4908 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4909 SourceLocation TypeidLoc,
4910 TypeSourceInfo *Operand,
4911 SourceLocation RParenLoc);
4912 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4913 SourceLocation TypeidLoc,
4915 SourceLocation RParenLoc);
4917 /// ActOnCXXTypeid - Parse typeid( something ).
4918 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4919 SourceLocation LParenLoc, bool isType,
4921 SourceLocation RParenLoc);
4923 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4924 SourceLocation TypeidLoc,
4925 TypeSourceInfo *Operand,
4926 SourceLocation RParenLoc);
4927 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4928 SourceLocation TypeidLoc,
4930 SourceLocation RParenLoc);
4932 /// ActOnCXXUuidof - Parse __uuidof( something ).
4933 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4934 SourceLocation LParenLoc, bool isType,
4936 SourceLocation RParenLoc);
4938 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4939 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4940 tok::TokenKind Operator,
4941 SourceLocation EllipsisLoc, Expr *RHS,
4942 SourceLocation RParenLoc);
4943 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4944 BinaryOperatorKind Operator,
4945 SourceLocation EllipsisLoc, Expr *RHS,
4946 SourceLocation RParenLoc);
4947 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4948 BinaryOperatorKind Operator);
4950 //// ActOnCXXThis - Parse 'this' pointer.
4951 ExprResult ActOnCXXThis(SourceLocation loc);
4953 /// \brief Try to retrieve the type of the 'this' pointer.
4955 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4956 QualType getCurrentThisType();
4958 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4959 /// current context not being a non-static member function. In such cases,
4960 /// this provides the type used for 'this'.
4961 QualType CXXThisTypeOverride;
4963 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4964 /// to be used, with the given qualifiers on the current class type.
4965 class CXXThisScopeRAII {
4967 QualType OldCXXThisTypeOverride;
4971 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4972 /// using the given declaration (which is either a class template or a
4973 /// class) along with the given qualifiers.
4974 /// along with the qualifiers placed on '*this'.
4975 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4976 bool Enabled = true);
4978 ~CXXThisScopeRAII();
4981 /// \brief Make sure the value of 'this' is actually available in the current
4982 /// context, if it is a potentially evaluated context.
4984 /// \param Loc The location at which the capture of 'this' occurs.
4986 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4989 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4990 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4991 /// This is useful when enclosing lambdas must speculatively capture
4992 /// 'this' that may or may not be used in certain specializations of
4993 /// a nested generic lambda (depending on whether the name resolves to
4994 /// a non-static member function or a static function).
4995 /// \return returns 'true' if failed, 'false' if success.
4996 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4997 bool BuildAndDiagnose = true,
4998 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4999 bool ByCopy = false);
5001 /// \brief Determine whether the given type is the type of *this that is used
5002 /// outside of the body of a member function for a type that is currently
5004 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5006 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5007 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5010 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5011 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5014 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5015 SourceLocation AtLoc, SourceLocation RParen);
5017 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5018 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5020 //// ActOnCXXThrow - Parse throw expressions.
5021 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5022 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5023 bool IsThrownVarInScope);
5024 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5026 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5027 /// Can be interpreted either as function-style casting ("int(x)")
5028 /// or class type construction ("ClassType(x,y,z)")
5029 /// or creation of a value-initialized type ("int()").
5030 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5031 SourceLocation LParenLoc,
5033 SourceLocation RParenLoc);
5035 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5036 SourceLocation LParenLoc,
5038 SourceLocation RParenLoc);
5040 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5041 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5042 SourceLocation PlacementLParen,
5043 MultiExprArg PlacementArgs,
5044 SourceLocation PlacementRParen,
5045 SourceRange TypeIdParens, Declarator &D,
5047 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5048 SourceLocation PlacementLParen,
5049 MultiExprArg PlacementArgs,
5050 SourceLocation PlacementRParen,
5051 SourceRange TypeIdParens,
5053 TypeSourceInfo *AllocTypeInfo,
5055 SourceRange DirectInitRange,
5058 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5060 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5061 bool UseGlobal, QualType AllocType, bool IsArray,
5062 bool &PassAlignment, MultiExprArg PlaceArgs,
5063 FunctionDecl *&OperatorNew,
5064 FunctionDecl *&OperatorDelete);
5065 void DeclareGlobalNewDelete();
5066 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5067 ArrayRef<QualType> Params);
5069 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5070 DeclarationName Name, FunctionDecl* &Operator,
5071 bool Diagnose = true);
5072 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5073 bool CanProvideSize,
5075 DeclarationName Name);
5076 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5079 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5080 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5081 bool UseGlobal, bool ArrayForm,
5083 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5084 bool IsDelete, bool CallCanBeVirtual,
5085 bool WarnOnNonAbstractTypes,
5086 SourceLocation DtorLoc);
5088 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5089 Expr *Operand, SourceLocation RParen);
5090 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5091 SourceLocation RParen);
5093 /// \brief Parsed one of the type trait support pseudo-functions.
5094 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5095 ArrayRef<ParsedType> Args,
5096 SourceLocation RParenLoc);
5097 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5098 ArrayRef<TypeSourceInfo *> Args,
5099 SourceLocation RParenLoc);
5101 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5102 /// pseudo-functions.
5103 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5104 SourceLocation KWLoc,
5107 SourceLocation RParen);
5109 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5110 SourceLocation KWLoc,
5111 TypeSourceInfo *TSInfo,
5113 SourceLocation RParen);
5115 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5116 /// pseudo-functions.
5117 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5118 SourceLocation KWLoc,
5120 SourceLocation RParen);
5122 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5123 SourceLocation KWLoc,
5125 SourceLocation RParen);
5127 ExprResult ActOnStartCXXMemberReference(Scope *S,
5129 SourceLocation OpLoc,
5130 tok::TokenKind OpKind,
5131 ParsedType &ObjectType,
5132 bool &MayBePseudoDestructor);
5134 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5135 SourceLocation OpLoc,
5136 tok::TokenKind OpKind,
5137 const CXXScopeSpec &SS,
5138 TypeSourceInfo *ScopeType,
5139 SourceLocation CCLoc,
5140 SourceLocation TildeLoc,
5141 PseudoDestructorTypeStorage DestroyedType);
5143 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5144 SourceLocation OpLoc,
5145 tok::TokenKind OpKind,
5147 UnqualifiedId &FirstTypeName,
5148 SourceLocation CCLoc,
5149 SourceLocation TildeLoc,
5150 UnqualifiedId &SecondTypeName);
5152 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5153 SourceLocation OpLoc,
5154 tok::TokenKind OpKind,
5155 SourceLocation TildeLoc,
5156 const DeclSpec& DS);
5158 /// MaybeCreateExprWithCleanups - If the current full-expression
5159 /// requires any cleanups, surround it with a ExprWithCleanups node.
5160 /// Otherwise, just returns the passed-in expression.
5161 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5162 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5163 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5165 MaterializeTemporaryExpr *
5166 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5167 bool BoundToLvalueReference);
5169 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5170 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5171 : SourceLocation());
5173 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5174 bool DiscardedValue = false,
5175 bool IsConstexpr = false,
5176 bool IsLambdaInitCaptureInitializer = false);
5177 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5179 // Marks SS invalid if it represents an incomplete type.
5180 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5182 DeclContext *computeDeclContext(QualType T);
5183 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5184 bool EnteringContext = false);
5185 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5186 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5188 /// \brief The parser has parsed a global nested-name-specifier '::'.
5190 /// \param CCLoc The location of the '::'.
5192 /// \param SS The nested-name-specifier, which will be updated in-place
5193 /// to reflect the parsed nested-name-specifier.
5195 /// \returns true if an error occurred, false otherwise.
5196 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5198 /// \brief The parser has parsed a '__super' nested-name-specifier.
5200 /// \param SuperLoc The location of the '__super' keyword.
5202 /// \param ColonColonLoc The location of the '::'.
5204 /// \param SS The nested-name-specifier, which will be updated in-place
5205 /// to reflect the parsed nested-name-specifier.
5207 /// \returns true if an error occurred, false otherwise.
5208 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5209 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5211 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5212 bool *CanCorrect = nullptr);
5213 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5215 /// \brief Keeps information about an identifier in a nested-name-spec.
5217 struct NestedNameSpecInfo {
5218 /// \brief The type of the object, if we're parsing nested-name-specifier in
5219 /// a member access expression.
5220 ParsedType ObjectType;
5222 /// \brief The identifier preceding the '::'.
5223 IdentifierInfo *Identifier;
5225 /// \brief The location of the identifier.
5226 SourceLocation IdentifierLoc;
5228 /// \brief The location of the '::'.
5229 SourceLocation CCLoc;
5231 /// \brief Creates info object for the most typical case.
5232 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5233 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5234 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5235 CCLoc(ColonColonLoc) {
5238 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5239 SourceLocation ColonColonLoc, QualType ObjectType)
5240 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5241 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5245 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5246 NestedNameSpecInfo &IdInfo);
5248 bool BuildCXXNestedNameSpecifier(Scope *S,
5249 NestedNameSpecInfo &IdInfo,
5250 bool EnteringContext,
5252 NamedDecl *ScopeLookupResult,
5253 bool ErrorRecoveryLookup,
5254 bool *IsCorrectedToColon = nullptr,
5255 bool OnlyNamespace = false);
5257 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5259 /// \param S The scope in which this nested-name-specifier occurs.
5261 /// \param IdInfo Parser information about an identifier in the
5262 /// nested-name-spec.
5264 /// \param EnteringContext Whether we're entering the context nominated by
5265 /// this nested-name-specifier.
5267 /// \param SS The nested-name-specifier, which is both an input
5268 /// parameter (the nested-name-specifier before this type) and an
5269 /// output parameter (containing the full nested-name-specifier,
5270 /// including this new type).
5272 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5273 /// error recovery. In this case do not emit error message.
5275 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5276 /// are allowed. The bool value pointed by this parameter is set to 'true'
5277 /// if the identifier is treated as if it was followed by ':', not '::'.
5279 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5281 /// \returns true if an error occurred, false otherwise.
5282 bool ActOnCXXNestedNameSpecifier(Scope *S,
5283 NestedNameSpecInfo &IdInfo,
5284 bool EnteringContext,
5286 bool ErrorRecoveryLookup = false,
5287 bool *IsCorrectedToColon = nullptr,
5288 bool OnlyNamespace = false);
5290 ExprResult ActOnDecltypeExpression(Expr *E);
5292 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5294 SourceLocation ColonColonLoc);
5296 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5297 NestedNameSpecInfo &IdInfo,
5298 bool EnteringContext);
5300 /// \brief The parser has parsed a nested-name-specifier
5301 /// 'template[opt] template-name < template-args >::'.
5303 /// \param S The scope in which this nested-name-specifier occurs.
5305 /// \param SS The nested-name-specifier, which is both an input
5306 /// parameter (the nested-name-specifier before this type) and an
5307 /// output parameter (containing the full nested-name-specifier,
5308 /// including this new type).
5310 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5311 /// \param TemplateName the template name.
5312 /// \param TemplateNameLoc The location of the template name.
5313 /// \param LAngleLoc The location of the opening angle bracket ('<').
5314 /// \param TemplateArgs The template arguments.
5315 /// \param RAngleLoc The location of the closing angle bracket ('>').
5316 /// \param CCLoc The location of the '::'.
5318 /// \param EnteringContext Whether we're entering the context of the
5319 /// nested-name-specifier.
5322 /// \returns true if an error occurred, false otherwise.
5323 bool ActOnCXXNestedNameSpecifier(Scope *S,
5325 SourceLocation TemplateKWLoc,
5326 TemplateTy TemplateName,
5327 SourceLocation TemplateNameLoc,
5328 SourceLocation LAngleLoc,
5329 ASTTemplateArgsPtr TemplateArgs,
5330 SourceLocation RAngleLoc,
5331 SourceLocation CCLoc,
5332 bool EnteringContext);
5334 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5335 /// that the parser can use later to reconstruct the given
5336 /// nested-name-specifier.
5338 /// \param SS A nested-name-specifier.
5340 /// \returns A pointer containing all of the information in the
5341 /// nested-name-specifier \p SS.
5342 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5344 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5345 /// the nested-name-specifier structure.
5347 /// \param Annotation The annotation pointer, produced by
5348 /// \c SaveNestedNameSpecifierAnnotation().
5350 /// \param AnnotationRange The source range corresponding to the annotation.
5352 /// \param SS The nested-name-specifier that will be updated with the contents
5353 /// of the annotation pointer.
5354 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5355 SourceRange AnnotationRange,
5358 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5360 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5361 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5362 /// After this method is called, according to [C++ 3.4.3p3], names should be
5363 /// looked up in the declarator-id's scope, until the declarator is parsed and
5364 /// ActOnCXXExitDeclaratorScope is called.
5365 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5366 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5368 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5369 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5370 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5371 /// Used to indicate that names should revert to being looked up in the
5373 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5375 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5376 /// initializer for the declaration 'Dcl'.
5377 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5378 /// static data member of class X, names should be looked up in the scope of
5380 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5382 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5383 /// initializer for the declaration 'Dcl'.
5384 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5386 /// \brief Create a new lambda closure type.
5387 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5388 TypeSourceInfo *Info,
5389 bool KnownDependent,
5390 LambdaCaptureDefault CaptureDefault);
5392 /// \brief Start the definition of a lambda expression.
5393 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5394 SourceRange IntroducerRange,
5395 TypeSourceInfo *MethodType,
5396 SourceLocation EndLoc,
5397 ArrayRef<ParmVarDecl *> Params,
5398 bool IsConstexprSpecified);
5400 /// \brief Endow the lambda scope info with the relevant properties.
5401 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5402 CXXMethodDecl *CallOperator,
5403 SourceRange IntroducerRange,
5404 LambdaCaptureDefault CaptureDefault,
5405 SourceLocation CaptureDefaultLoc,
5406 bool ExplicitParams,
5407 bool ExplicitResultType,
5410 /// \brief Perform initialization analysis of the init-capture and perform
5411 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5412 /// not being used to initialize a reference.
5413 ParsedType actOnLambdaInitCaptureInitialization(
5414 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5415 LambdaCaptureInitKind InitKind, Expr *&Init) {
5416 return ParsedType::make(buildLambdaInitCaptureInitialization(
5417 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5419 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5421 bool DirectInit, Expr *&Init);
5423 /// \brief Create a dummy variable within the declcontext of the lambda's
5424 /// call operator, for name lookup purposes for a lambda init capture.
5426 /// CodeGen handles emission of lambda captures, ignoring these dummy
5427 /// variables appropriately.
5428 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5429 QualType InitCaptureType,
5431 unsigned InitStyle, Expr *Init);
5433 /// \brief Build the implicit field for an init-capture.
5434 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5436 /// \brief Note that we have finished the explicit captures for the
5438 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5440 /// \brief Introduce the lambda parameters into scope.
5441 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5443 /// \brief Deduce a block or lambda's return type based on the return
5444 /// statements present in the body.
5445 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5447 /// ActOnStartOfLambdaDefinition - This is called just before we start
5448 /// parsing the body of a lambda; it analyzes the explicit captures and
5449 /// arguments, and sets up various data-structures for the body of the
5451 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5452 Declarator &ParamInfo, Scope *CurScope);
5454 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5455 /// is invoked to pop the information about the lambda.
5456 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5457 bool IsInstantiation = false);
5459 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5460 /// was successfully completed.
5461 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5464 /// \brief Does copying/destroying the captured variable have side effects?
5465 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5467 /// \brief Diagnose if an explicit lambda capture is unused.
5468 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5470 /// \brief Complete a lambda-expression having processed and attached the
5472 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5473 sema::LambdaScopeInfo *LSI);
5475 /// \brief Define the "body" of the conversion from a lambda object to a
5476 /// function pointer.
5478 /// This routine doesn't actually define a sensible body; rather, it fills
5479 /// in the initialization expression needed to copy the lambda object into
5480 /// the block, and IR generation actually generates the real body of the
5481 /// block pointer conversion.
5482 void DefineImplicitLambdaToFunctionPointerConversion(
5483 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5485 /// \brief Define the "body" of the conversion from a lambda object to a
5488 /// This routine doesn't actually define a sensible body; rather, it fills
5489 /// in the initialization expression needed to copy the lambda object into
5490 /// the block, and IR generation actually generates the real body of the
5491 /// block pointer conversion.
5492 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5493 CXXConversionDecl *Conv);
5495 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5496 SourceLocation ConvLocation,
5497 CXXConversionDecl *Conv,
5500 // ParseObjCStringLiteral - Parse Objective-C string literals.
5501 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5502 ArrayRef<Expr *> Strings);
5504 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5506 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5507 /// numeric literal expression. Type of the expression will be "NSNumber *"
5508 /// or "id" if NSNumber is unavailable.
5509 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5510 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5512 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5514 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5515 /// '@' prefixed parenthesized expression. The type of the expression will
5516 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5517 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5518 /// "const char *" or C structure with attribute 'objc_boxable'.
5519 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5521 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5523 ObjCMethodDecl *getterMethod,
5524 ObjCMethodDecl *setterMethod);
5526 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5527 MutableArrayRef<ObjCDictionaryElement> Elements);
5529 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5530 TypeSourceInfo *EncodedTypeInfo,
5531 SourceLocation RParenLoc);
5532 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5533 CXXConversionDecl *Method,
5534 bool HadMultipleCandidates);
5536 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5537 SourceLocation EncodeLoc,
5538 SourceLocation LParenLoc,
5540 SourceLocation RParenLoc);
5542 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5543 ExprResult ParseObjCSelectorExpression(Selector Sel,
5544 SourceLocation AtLoc,
5545 SourceLocation SelLoc,
5546 SourceLocation LParenLoc,
5547 SourceLocation RParenLoc,
5548 bool WarnMultipleSelectors);
5550 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5551 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5552 SourceLocation AtLoc,
5553 SourceLocation ProtoLoc,
5554 SourceLocation LParenLoc,
5555 SourceLocation ProtoIdLoc,
5556 SourceLocation RParenLoc);
5558 //===--------------------------------------------------------------------===//
5561 Decl *ActOnStartLinkageSpecification(Scope *S,
5562 SourceLocation ExternLoc,
5564 SourceLocation LBraceLoc);
5565 Decl *ActOnFinishLinkageSpecification(Scope *S,
5567 SourceLocation RBraceLoc);
5570 //===--------------------------------------------------------------------===//
5573 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5574 const CXXScopeSpec *SS = nullptr);
5575 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5577 bool ActOnAccessSpecifier(AccessSpecifier Access,
5578 SourceLocation ASLoc,
5579 SourceLocation ColonLoc,
5580 AttributeList *Attrs = nullptr);
5582 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5584 MultiTemplateParamsArg TemplateParameterLists,
5585 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5586 InClassInitStyle InitStyle);
5588 void ActOnStartCXXInClassMemberInitializer();
5589 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5590 SourceLocation EqualLoc,
5593 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5596 IdentifierInfo *MemberOrBase,
5597 ParsedType TemplateTypeTy,
5599 SourceLocation IdLoc,
5600 SourceLocation LParenLoc,
5601 ArrayRef<Expr *> Args,
5602 SourceLocation RParenLoc,
5603 SourceLocation EllipsisLoc);
5605 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5608 IdentifierInfo *MemberOrBase,
5609 ParsedType TemplateTypeTy,
5611 SourceLocation IdLoc,
5613 SourceLocation EllipsisLoc);
5615 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5618 IdentifierInfo *MemberOrBase,
5619 ParsedType TemplateTypeTy,
5621 SourceLocation IdLoc,
5623 SourceLocation EllipsisLoc);
5625 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5627 SourceLocation IdLoc);
5629 MemInitResult BuildBaseInitializer(QualType BaseType,
5630 TypeSourceInfo *BaseTInfo,
5632 CXXRecordDecl *ClassDecl,
5633 SourceLocation EllipsisLoc);
5635 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5637 CXXRecordDecl *ClassDecl);
5639 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5640 CXXCtorInitializer *Initializer);
5642 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5643 ArrayRef<CXXCtorInitializer *> Initializers = None);
5645 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5648 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5649 /// mark all the non-trivial destructors of its members and bases as
5651 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5652 CXXRecordDecl *Record);
5654 /// \brief The list of classes whose vtables have been used within
5655 /// this translation unit, and the source locations at which the
5656 /// first use occurred.
5657 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5659 /// \brief The list of vtables that are required but have not yet been
5661 SmallVector<VTableUse, 16> VTableUses;
5663 /// \brief The set of classes whose vtables have been used within
5664 /// this translation unit, and a bit that will be true if the vtable is
5665 /// required to be emitted (otherwise, it should be emitted only if needed
5666 /// by code generation).
5667 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5669 /// \brief Load any externally-stored vtable uses.
5670 void LoadExternalVTableUses();
5672 /// \brief Note that the vtable for the given class was used at the
5674 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5675 bool DefinitionRequired = false);
5677 /// \brief Mark the exception specifications of all virtual member functions
5678 /// in the given class as needed.
5679 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5680 const CXXRecordDecl *RD);
5682 /// MarkVirtualMembersReferenced - Will mark all members of the given
5683 /// CXXRecordDecl referenced.
5684 void MarkVirtualMembersReferenced(SourceLocation Loc,
5685 const CXXRecordDecl *RD);
5687 /// \brief Define all of the vtables that have been used in this
5688 /// translation unit and reference any virtual members used by those
5691 /// \returns true if any work was done, false otherwise.
5692 bool DefineUsedVTables();
5694 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5696 void ActOnMemInitializers(Decl *ConstructorDecl,
5697 SourceLocation ColonLoc,
5698 ArrayRef<CXXCtorInitializer*> MemInits,
5701 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5702 /// ensure that referenceDLLExportedClassMethods is called some point later
5703 /// when all outer classes of Class are complete.
5704 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5706 void referenceDLLExportedClassMethods();
5708 void propagateDLLAttrToBaseClassTemplate(
5709 CXXRecordDecl *Class, Attr *ClassAttr,
5710 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5711 SourceLocation BaseLoc);
5713 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5714 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5716 SourceLocation LBrac,
5717 SourceLocation RBrac,
5718 AttributeList *AttrList);
5719 void ActOnFinishCXXMemberDecls();
5720 void ActOnFinishCXXNonNestedClass(Decl *D);
5722 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5723 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5724 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5725 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5726 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5727 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5728 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5729 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5730 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5731 CachedTokens &Toks);
5732 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5733 bool IsInsideALocalClassWithinATemplateFunction();
5735 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5737 Expr *AssertMessageExpr,
5738 SourceLocation RParenLoc);
5739 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5741 StringLiteral *AssertMessageExpr,
5742 SourceLocation RParenLoc,
5745 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5746 SourceLocation FriendLoc,
5747 TypeSourceInfo *TSInfo);
5748 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5749 MultiTemplateParamsArg TemplateParams);
5750 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5751 MultiTemplateParamsArg TemplateParams);
5753 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5755 void CheckConstructor(CXXConstructorDecl *Constructor);
5756 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5758 bool CheckDestructor(CXXDestructorDecl *Destructor);
5759 void CheckConversionDeclarator(Declarator &D, QualType &R,
5761 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5762 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5764 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5766 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5767 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5768 const FunctionProtoType *T);
5769 void CheckDelayedMemberExceptionSpecs();
5771 //===--------------------------------------------------------------------===//
5772 // C++ Derived Classes
5775 /// ActOnBaseSpecifier - Parsed a base specifier
5776 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5777 SourceRange SpecifierRange,
5778 bool Virtual, AccessSpecifier Access,
5779 TypeSourceInfo *TInfo,
5780 SourceLocation EllipsisLoc);
5782 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5783 SourceRange SpecifierRange,
5784 ParsedAttributes &Attrs,
5785 bool Virtual, AccessSpecifier Access,
5786 ParsedType basetype,
5787 SourceLocation BaseLoc,
5788 SourceLocation EllipsisLoc);
5790 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5791 MutableArrayRef<CXXBaseSpecifier *> Bases);
5792 void ActOnBaseSpecifiers(Decl *ClassDecl,
5793 MutableArrayRef<CXXBaseSpecifier *> Bases);
5795 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5796 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5797 CXXBasePaths &Paths);
5799 // FIXME: I don't like this name.
5800 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5802 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5803 SourceLocation Loc, SourceRange Range,
5804 CXXCastPath *BasePath = nullptr,
5805 bool IgnoreAccess = false);
5806 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5807 unsigned InaccessibleBaseID,
5808 unsigned AmbigiousBaseConvID,
5809 SourceLocation Loc, SourceRange Range,
5810 DeclarationName Name,
5811 CXXCastPath *BasePath,
5812 bool IgnoreAccess = false);
5814 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5816 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5817 const CXXMethodDecl *Old);
5819 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5820 /// covariant, according to C++ [class.virtual]p5.
5821 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5822 const CXXMethodDecl *Old);
5824 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5825 /// spec is a subset of base spec.
5826 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5827 const CXXMethodDecl *Old);
5829 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5831 /// CheckOverrideControl - Check C++11 override control semantics.
5832 void CheckOverrideControl(NamedDecl *D);
5834 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5835 /// not used in the declaration of an overriding method.
5836 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5838 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5839 /// overrides a virtual member function marked 'final', according to
5840 /// C++11 [class.virtual]p4.
5841 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5842 const CXXMethodDecl *Old);
5845 //===--------------------------------------------------------------------===//
5846 // C++ Access Control
5856 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5857 NamedDecl *PrevMemberDecl,
5858 AccessSpecifier LexicalAS);
5860 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5861 DeclAccessPair FoundDecl);
5862 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5863 DeclAccessPair FoundDecl);
5864 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5865 SourceRange PlacementRange,
5866 CXXRecordDecl *NamingClass,
5867 DeclAccessPair FoundDecl,
5868 bool Diagnose = true);
5869 AccessResult CheckConstructorAccess(SourceLocation Loc,
5870 CXXConstructorDecl *D,
5871 DeclAccessPair FoundDecl,
5872 const InitializedEntity &Entity,
5873 bool IsCopyBindingRefToTemp = false);
5874 AccessResult CheckConstructorAccess(SourceLocation Loc,
5875 CXXConstructorDecl *D,
5876 DeclAccessPair FoundDecl,
5877 const InitializedEntity &Entity,
5878 const PartialDiagnostic &PDiag);
5879 AccessResult CheckDestructorAccess(SourceLocation Loc,
5880 CXXDestructorDecl *Dtor,
5881 const PartialDiagnostic &PDiag,
5882 QualType objectType = QualType());
5883 AccessResult CheckFriendAccess(NamedDecl *D);
5884 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5885 CXXRecordDecl *NamingClass,
5886 DeclAccessPair Found);
5887 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5890 DeclAccessPair FoundDecl);
5891 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5892 DeclAccessPair FoundDecl);
5893 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5894 QualType Base, QualType Derived,
5895 const CXXBasePath &Path,
5897 bool ForceCheck = false,
5898 bool ForceUnprivileged = false);
5899 void CheckLookupAccess(const LookupResult &R);
5900 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5901 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5902 AccessSpecifier access,
5903 QualType objectType);
5905 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5906 const MultiLevelTemplateArgumentList &TemplateArgs);
5907 void PerformDependentDiagnostics(const DeclContext *Pattern,
5908 const MultiLevelTemplateArgumentList &TemplateArgs);
5910 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5912 /// \brief When true, access checking violations are treated as SFINAE
5913 /// failures rather than hard errors.
5914 bool AccessCheckingSFINAE;
5916 enum AbstractDiagSelID {
5920 AbstractVariableType,
5923 AbstractSynthesizedIvarType,
5927 bool isAbstractType(SourceLocation Loc, QualType T);
5928 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5929 TypeDiagnoser &Diagnoser);
5930 template <typename... Ts>
5931 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5932 const Ts &...Args) {
5933 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5934 return RequireNonAbstractType(Loc, T, Diagnoser);
5937 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5939 //===--------------------------------------------------------------------===//
5940 // C++ Overloaded Operators [C++ 13.5]
5943 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5945 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5947 //===--------------------------------------------------------------------===//
5948 // C++ Templates [C++ 14]
5950 void FilterAcceptableTemplateNames(LookupResult &R,
5951 bool AllowFunctionTemplates = true);
5952 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5953 bool AllowFunctionTemplates = true);
5955 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5956 QualType ObjectType, bool EnteringContext,
5957 bool &MemberOfUnknownSpecialization);
5959 TemplateNameKind isTemplateName(Scope *S,
5961 bool hasTemplateKeyword,
5962 UnqualifiedId &Name,
5963 ParsedType ObjectType,
5964 bool EnteringContext,
5965 TemplateTy &Template,
5966 bool &MemberOfUnknownSpecialization);
5968 /// Determine whether a particular identifier might be the name in a C++1z
5969 /// deduction-guide declaration.
5970 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5971 SourceLocation NameLoc,
5972 ParsedTemplateTy *Template = nullptr);
5974 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5975 SourceLocation IILoc,
5977 const CXXScopeSpec *SS,
5978 TemplateTy &SuggestedTemplate,
5979 TemplateNameKind &SuggestedKind);
5981 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5982 NamedDecl *Instantiation,
5983 bool InstantiatedFromMember,
5984 const NamedDecl *Pattern,
5985 const NamedDecl *PatternDef,
5986 TemplateSpecializationKind TSK,
5987 bool Complain = true);
5989 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5990 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5992 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5993 SourceLocation EllipsisLoc,
5994 SourceLocation KeyLoc,
5995 IdentifierInfo *ParamName,
5996 SourceLocation ParamNameLoc,
5997 unsigned Depth, unsigned Position,
5998 SourceLocation EqualLoc,
5999 ParsedType DefaultArg);
6001 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6002 SourceLocation Loc);
6003 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6005 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6008 SourceLocation EqualLoc,
6010 Decl *ActOnTemplateTemplateParameter(Scope *S,
6011 SourceLocation TmpLoc,
6012 TemplateParameterList *Params,
6013 SourceLocation EllipsisLoc,
6014 IdentifierInfo *ParamName,
6015 SourceLocation ParamNameLoc,
6018 SourceLocation EqualLoc,
6019 ParsedTemplateArgument DefaultArg);
6021 TemplateParameterList *
6022 ActOnTemplateParameterList(unsigned Depth,
6023 SourceLocation ExportLoc,
6024 SourceLocation TemplateLoc,
6025 SourceLocation LAngleLoc,
6026 ArrayRef<Decl *> Params,
6027 SourceLocation RAngleLoc,
6028 Expr *RequiresClause);
6030 /// \brief The context in which we are checking a template parameter list.
6031 enum TemplateParamListContext {
6034 TPC_FunctionTemplate,
6035 TPC_ClassTemplateMember,
6036 TPC_FriendClassTemplate,
6037 TPC_FriendFunctionTemplate,
6038 TPC_FriendFunctionTemplateDefinition,
6039 TPC_TypeAliasTemplate
6042 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6043 TemplateParameterList *OldParams,
6044 TemplateParamListContext TPC);
6045 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6046 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6047 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6048 ArrayRef<TemplateParameterList *> ParamLists,
6049 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6051 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6052 SourceLocation KWLoc, CXXScopeSpec &SS,
6053 IdentifierInfo *Name, SourceLocation NameLoc,
6054 AttributeList *Attr,
6055 TemplateParameterList *TemplateParams,
6057 SourceLocation ModulePrivateLoc,
6058 SourceLocation FriendLoc,
6059 unsigned NumOuterTemplateParamLists,
6060 TemplateParameterList **OuterTemplateParamLists,
6061 SkipBodyInfo *SkipBody = nullptr);
6063 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6065 SourceLocation Loc);
6067 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6068 TemplateArgumentListInfo &Out);
6070 void NoteAllFoundTemplates(TemplateName Name);
6072 QualType CheckTemplateIdType(TemplateName Template,
6073 SourceLocation TemplateLoc,
6074 TemplateArgumentListInfo &TemplateArgs);
6077 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6078 TemplateTy Template, IdentifierInfo *TemplateII,
6079 SourceLocation TemplateIILoc,
6080 SourceLocation LAngleLoc,
6081 ASTTemplateArgsPtr TemplateArgs,
6082 SourceLocation RAngleLoc,
6083 bool IsCtorOrDtorName = false,
6084 bool IsClassName = false);
6086 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6087 /// such as \c class T::template apply<U>.
6088 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6089 TypeSpecifierType TagSpec,
6090 SourceLocation TagLoc,
6092 SourceLocation TemplateKWLoc,
6093 TemplateTy TemplateD,
6094 SourceLocation TemplateLoc,
6095 SourceLocation LAngleLoc,
6096 ASTTemplateArgsPtr TemplateArgsIn,
6097 SourceLocation RAngleLoc);
6099 DeclResult ActOnVarTemplateSpecialization(
6100 Scope *S, Declarator &D, TypeSourceInfo *DI,
6101 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6102 StorageClass SC, bool IsPartialSpecialization);
6104 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6105 SourceLocation TemplateLoc,
6106 SourceLocation TemplateNameLoc,
6107 const TemplateArgumentListInfo &TemplateArgs);
6109 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6110 const DeclarationNameInfo &NameInfo,
6111 VarTemplateDecl *Template,
6112 SourceLocation TemplateLoc,
6113 const TemplateArgumentListInfo *TemplateArgs);
6115 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6116 SourceLocation TemplateKWLoc,
6119 const TemplateArgumentListInfo *TemplateArgs);
6121 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6122 SourceLocation TemplateKWLoc,
6123 const DeclarationNameInfo &NameInfo,
6124 const TemplateArgumentListInfo *TemplateArgs);
6126 TemplateNameKind ActOnDependentTemplateName(
6127 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6128 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6129 TemplateTy &Template, bool AllowInjectedClassName = false);
6132 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6133 SourceLocation KWLoc,
6134 SourceLocation ModulePrivateLoc,
6135 TemplateIdAnnotation &TemplateId,
6136 AttributeList *Attr,
6137 MultiTemplateParamsArg TemplateParameterLists,
6138 SkipBodyInfo *SkipBody = nullptr);
6140 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6141 TemplateDecl *PrimaryTemplate,
6142 unsigned NumExplicitArgs,
6143 ArrayRef<TemplateArgument> Args);
6144 void CheckTemplatePartialSpecialization(
6145 ClassTemplatePartialSpecializationDecl *Partial);
6146 void CheckTemplatePartialSpecialization(
6147 VarTemplatePartialSpecializationDecl *Partial);
6149 Decl *ActOnTemplateDeclarator(Scope *S,
6150 MultiTemplateParamsArg TemplateParameterLists,
6154 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6155 TemplateSpecializationKind NewTSK,
6156 NamedDecl *PrevDecl,
6157 TemplateSpecializationKind PrevTSK,
6158 SourceLocation PrevPtOfInstantiation,
6161 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6162 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6163 LookupResult &Previous);
6165 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6166 TemplateArgumentListInfo *ExplicitTemplateArgs,
6167 LookupResult &Previous);
6168 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6169 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6172 ActOnExplicitInstantiation(Scope *S,
6173 SourceLocation ExternLoc,
6174 SourceLocation TemplateLoc,
6176 SourceLocation KWLoc,
6177 const CXXScopeSpec &SS,
6178 TemplateTy Template,
6179 SourceLocation TemplateNameLoc,
6180 SourceLocation LAngleLoc,
6181 ASTTemplateArgsPtr TemplateArgs,
6182 SourceLocation RAngleLoc,
6183 AttributeList *Attr);
6186 ActOnExplicitInstantiation(Scope *S,
6187 SourceLocation ExternLoc,
6188 SourceLocation TemplateLoc,
6190 SourceLocation KWLoc,
6192 IdentifierInfo *Name,
6193 SourceLocation NameLoc,
6194 AttributeList *Attr);
6196 DeclResult ActOnExplicitInstantiation(Scope *S,
6197 SourceLocation ExternLoc,
6198 SourceLocation TemplateLoc,
6202 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6203 SourceLocation TemplateLoc,
6204 SourceLocation RAngleLoc,
6206 SmallVectorImpl<TemplateArgument>
6208 bool &HasDefaultArg);
6210 /// \brief Specifies the context in which a particular template
6211 /// argument is being checked.
6212 enum CheckTemplateArgumentKind {
6213 /// \brief The template argument was specified in the code or was
6214 /// instantiated with some deduced template arguments.
6217 /// \brief The template argument was deduced via template argument
6221 /// \brief The template argument was deduced from an array bound
6222 /// via template argument deduction.
6223 CTAK_DeducedFromArrayBound
6226 bool CheckTemplateArgument(NamedDecl *Param,
6227 TemplateArgumentLoc &Arg,
6228 NamedDecl *Template,
6229 SourceLocation TemplateLoc,
6230 SourceLocation RAngleLoc,
6231 unsigned ArgumentPackIndex,
6232 SmallVectorImpl<TemplateArgument> &Converted,
6233 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6235 /// \brief Check that the given template arguments can be be provided to
6236 /// the given template, converting the arguments along the way.
6238 /// \param Template The template to which the template arguments are being
6241 /// \param TemplateLoc The location of the template name in the source.
6243 /// \param TemplateArgs The list of template arguments. If the template is
6244 /// a template template parameter, this function may extend the set of
6245 /// template arguments to also include substituted, defaulted template
6248 /// \param PartialTemplateArgs True if the list of template arguments is
6249 /// intentionally partial, e.g., because we're checking just the initial
6250 /// set of template arguments.
6252 /// \param Converted Will receive the converted, canonicalized template
6255 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6256 /// contain the converted forms of the template arguments as written.
6257 /// Otherwise, \p TemplateArgs will not be modified.
6259 /// \returns true if an error occurred, false otherwise.
6260 bool CheckTemplateArgumentList(TemplateDecl *Template,
6261 SourceLocation TemplateLoc,
6262 TemplateArgumentListInfo &TemplateArgs,
6263 bool PartialTemplateArgs,
6264 SmallVectorImpl<TemplateArgument> &Converted,
6265 bool UpdateArgsWithConversions = true);
6267 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6268 TemplateArgumentLoc &Arg,
6269 SmallVectorImpl<TemplateArgument> &Converted);
6271 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6272 TypeSourceInfo *Arg);
6273 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6274 QualType InstantiatedParamType, Expr *Arg,
6275 TemplateArgument &Converted,
6276 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6277 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6278 TemplateArgumentLoc &Arg,
6279 unsigned ArgumentPackIndex);
6282 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6284 SourceLocation Loc);
6286 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6287 SourceLocation Loc);
6289 /// \brief Enumeration describing how template parameter lists are compared
6291 enum TemplateParameterListEqualKind {
6292 /// \brief We are matching the template parameter lists of two templates
6293 /// that might be redeclarations.
6296 /// template<typename T> struct X;
6297 /// template<typename T> struct X;
6301 /// \brief We are matching the template parameter lists of two template
6302 /// template parameters as part of matching the template parameter lists
6303 /// of two templates that might be redeclarations.
6306 /// template<template<int I> class TT> struct X;
6307 /// template<template<int Value> class Other> struct X;
6309 TPL_TemplateTemplateParmMatch,
6311 /// \brief We are matching the template parameter lists of a template
6312 /// template argument against the template parameter lists of a template
6313 /// template parameter.
6316 /// template<template<int Value> class Metafun> struct X;
6317 /// template<int Value> struct integer_c;
6318 /// X<integer_c> xic;
6320 TPL_TemplateTemplateArgumentMatch
6323 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6324 TemplateParameterList *Old,
6326 TemplateParameterListEqualKind Kind,
6327 SourceLocation TemplateArgLoc
6328 = SourceLocation());
6330 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6332 /// \brief Called when the parser has parsed a C++ typename
6333 /// specifier, e.g., "typename T::type".
6335 /// \param S The scope in which this typename type occurs.
6336 /// \param TypenameLoc the location of the 'typename' keyword
6337 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6338 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6339 /// \param IdLoc the location of the identifier.
6341 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6342 const CXXScopeSpec &SS, const IdentifierInfo &II,
6343 SourceLocation IdLoc);
6345 /// \brief Called when the parser has parsed a C++ typename
6346 /// specifier that ends in a template-id, e.g.,
6347 /// "typename MetaFun::template apply<T1, T2>".
6349 /// \param S The scope in which this typename type occurs.
6350 /// \param TypenameLoc the location of the 'typename' keyword
6351 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6352 /// \param TemplateLoc the location of the 'template' keyword, if any.
6353 /// \param TemplateName The template name.
6354 /// \param TemplateII The identifier used to name the template.
6355 /// \param TemplateIILoc The location of the template name.
6356 /// \param LAngleLoc The location of the opening angle bracket ('<').
6357 /// \param TemplateArgs The template arguments.
6358 /// \param RAngleLoc The location of the closing angle bracket ('>').
6360 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6361 const CXXScopeSpec &SS,
6362 SourceLocation TemplateLoc,
6363 TemplateTy TemplateName,
6364 IdentifierInfo *TemplateII,
6365 SourceLocation TemplateIILoc,
6366 SourceLocation LAngleLoc,
6367 ASTTemplateArgsPtr TemplateArgs,
6368 SourceLocation RAngleLoc);
6370 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6371 SourceLocation KeywordLoc,
6372 NestedNameSpecifierLoc QualifierLoc,
6373 const IdentifierInfo &II,
6374 SourceLocation IILoc);
6376 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6378 DeclarationName Name);
6379 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6381 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6382 bool RebuildTemplateParamsInCurrentInstantiation(
6383 TemplateParameterList *Params);
6386 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6387 const TemplateArgumentList &Args);
6390 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6391 const TemplateArgument *Args,
6394 //===--------------------------------------------------------------------===//
6395 // C++ Variadic Templates (C++0x [temp.variadic])
6396 //===--------------------------------------------------------------------===//
6398 /// Determine whether an unexpanded parameter pack might be permitted in this
6399 /// location. Useful for error recovery.
6400 bool isUnexpandedParameterPackPermitted();
6402 /// \brief The context in which an unexpanded parameter pack is
6403 /// being diagnosed.
6405 /// Note that the values of this enumeration line up with the first
6406 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6407 enum UnexpandedParameterPackContext {
6408 /// \brief An arbitrary expression.
6409 UPPC_Expression = 0,
6411 /// \brief The base type of a class type.
6414 /// \brief The type of an arbitrary declaration.
6415 UPPC_DeclarationType,
6417 /// \brief The type of a data member.
6418 UPPC_DataMemberType,
6420 /// \brief The size of a bit-field.
6423 /// \brief The expression in a static assertion.
6424 UPPC_StaticAssertExpression,
6426 /// \brief The fixed underlying type of an enumeration.
6427 UPPC_FixedUnderlyingType,
6429 /// \brief The enumerator value.
6430 UPPC_EnumeratorValue,
6432 /// \brief A using declaration.
6433 UPPC_UsingDeclaration,
6435 /// \brief A friend declaration.
6436 UPPC_FriendDeclaration,
6438 /// \brief A declaration qualifier.
6439 UPPC_DeclarationQualifier,
6441 /// \brief An initializer.
6444 /// \brief A default argument.
6445 UPPC_DefaultArgument,
6447 /// \brief The type of a non-type template parameter.
6448 UPPC_NonTypeTemplateParameterType,
6450 /// \brief The type of an exception.
6453 /// \brief Partial specialization.
6454 UPPC_PartialSpecialization,
6456 /// \brief Microsoft __if_exists.
6459 /// \brief Microsoft __if_not_exists.
6462 /// \brief Lambda expression.
6465 /// \brief Block expression,
6469 /// \brief Diagnose unexpanded parameter packs.
6471 /// \param Loc The location at which we should emit the diagnostic.
6473 /// \param UPPC The context in which we are diagnosing unexpanded
6474 /// parameter packs.
6476 /// \param Unexpanded the set of unexpanded parameter packs.
6478 /// \returns true if an error occurred, false otherwise.
6479 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6480 UnexpandedParameterPackContext UPPC,
6481 ArrayRef<UnexpandedParameterPack> Unexpanded);
6483 /// \brief If the given type contains an unexpanded parameter pack,
6484 /// diagnose the error.
6486 /// \param Loc The source location where a diagnostc should be emitted.
6488 /// \param T The type that is being checked for unexpanded parameter
6491 /// \returns true if an error occurred, false otherwise.
6492 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6493 UnexpandedParameterPackContext UPPC);
6495 /// \brief If the given expression contains an unexpanded parameter
6496 /// pack, diagnose the error.
6498 /// \param E The expression that is being checked for unexpanded
6499 /// parameter packs.
6501 /// \returns true if an error occurred, false otherwise.
6502 bool DiagnoseUnexpandedParameterPack(Expr *E,
6503 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6505 /// \brief If the given nested-name-specifier contains an unexpanded
6506 /// parameter pack, diagnose the error.
6508 /// \param SS The nested-name-specifier that is being checked for
6509 /// unexpanded parameter packs.
6511 /// \returns true if an error occurred, false otherwise.
6512 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6513 UnexpandedParameterPackContext UPPC);
6515 /// \brief If the given name contains an unexpanded parameter pack,
6516 /// diagnose the error.
6518 /// \param NameInfo The name (with source location information) that
6519 /// is being checked for unexpanded parameter packs.
6521 /// \returns true if an error occurred, false otherwise.
6522 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6523 UnexpandedParameterPackContext UPPC);
6525 /// \brief If the given template name contains an unexpanded parameter pack,
6526 /// diagnose the error.
6528 /// \param Loc The location of the template name.
6530 /// \param Template The template name that is being checked for unexpanded
6531 /// parameter packs.
6533 /// \returns true if an error occurred, false otherwise.
6534 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6535 TemplateName Template,
6536 UnexpandedParameterPackContext UPPC);
6538 /// \brief If the given template argument contains an unexpanded parameter
6539 /// pack, diagnose the error.
6541 /// \param Arg The template argument that is being checked for unexpanded
6542 /// parameter packs.
6544 /// \returns true if an error occurred, false otherwise.
6545 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6546 UnexpandedParameterPackContext UPPC);
6548 /// \brief Collect the set of unexpanded parameter packs within the given
6549 /// template argument.
6551 /// \param Arg The template argument that will be traversed to find
6552 /// unexpanded parameter packs.
6553 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6554 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6556 /// \brief Collect the set of unexpanded parameter packs within the given
6557 /// template argument.
6559 /// \param Arg The template argument that will be traversed to find
6560 /// unexpanded parameter packs.
6561 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6562 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6564 /// \brief Collect the set of unexpanded parameter packs within the given
6567 /// \param T The type that will be traversed to find
6568 /// unexpanded parameter packs.
6569 void collectUnexpandedParameterPacks(QualType T,
6570 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6572 /// \brief Collect the set of unexpanded parameter packs within the given
6575 /// \param TL The type that will be traversed to find
6576 /// unexpanded parameter packs.
6577 void collectUnexpandedParameterPacks(TypeLoc TL,
6578 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6580 /// \brief Collect the set of unexpanded parameter packs within the given
6581 /// nested-name-specifier.
6583 /// \param NNS The nested-name-specifier that will be traversed to find
6584 /// unexpanded parameter packs.
6585 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6586 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6588 /// \brief Collect the set of unexpanded parameter packs within the given
6591 /// \param NameInfo The name that will be traversed to find
6592 /// unexpanded parameter packs.
6593 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6594 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6596 /// \brief Invoked when parsing a template argument followed by an
6597 /// ellipsis, which creates a pack expansion.
6599 /// \param Arg The template argument preceding the ellipsis, which
6600 /// may already be invalid.
6602 /// \param EllipsisLoc The location of the ellipsis.
6603 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6604 SourceLocation EllipsisLoc);
6606 /// \brief Invoked when parsing a type followed by an ellipsis, which
6607 /// creates a pack expansion.
6609 /// \param Type The type preceding the ellipsis, which will become
6610 /// the pattern of the pack expansion.
6612 /// \param EllipsisLoc The location of the ellipsis.
6613 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6615 /// \brief Construct a pack expansion type from the pattern of the pack
6617 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6618 SourceLocation EllipsisLoc,
6619 Optional<unsigned> NumExpansions);
6621 /// \brief Construct a pack expansion type from the pattern of the pack
6623 QualType CheckPackExpansion(QualType Pattern,
6624 SourceRange PatternRange,
6625 SourceLocation EllipsisLoc,
6626 Optional<unsigned> NumExpansions);
6628 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6629 /// creates a pack expansion.
6631 /// \param Pattern The expression preceding the ellipsis, which will become
6632 /// the pattern of the pack expansion.
6634 /// \param EllipsisLoc The location of the ellipsis.
6635 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6637 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6638 /// creates a pack expansion.
6640 /// \param Pattern The expression preceding the ellipsis, which will become
6641 /// the pattern of the pack expansion.
6643 /// \param EllipsisLoc The location of the ellipsis.
6644 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6645 Optional<unsigned> NumExpansions);
6647 /// \brief Determine whether we could expand a pack expansion with the
6648 /// given set of parameter packs into separate arguments by repeatedly
6649 /// transforming the pattern.
6651 /// \param EllipsisLoc The location of the ellipsis that identifies the
6654 /// \param PatternRange The source range that covers the entire pattern of
6655 /// the pack expansion.
6657 /// \param Unexpanded The set of unexpanded parameter packs within the
6660 /// \param ShouldExpand Will be set to \c true if the transformer should
6661 /// expand the corresponding pack expansions into separate arguments. When
6662 /// set, \c NumExpansions must also be set.
6664 /// \param RetainExpansion Whether the caller should add an unexpanded
6665 /// pack expansion after all of the expanded arguments. This is used
6666 /// when extending explicitly-specified template argument packs per
6667 /// C++0x [temp.arg.explicit]p9.
6669 /// \param NumExpansions The number of separate arguments that will be in
6670 /// the expanded form of the corresponding pack expansion. This is both an
6671 /// input and an output parameter, which can be set by the caller if the
6672 /// number of expansions is known a priori (e.g., due to a prior substitution)
6673 /// and will be set by the callee when the number of expansions is known.
6674 /// The callee must set this value when \c ShouldExpand is \c true; it may
6675 /// set this value in other cases.
6677 /// \returns true if an error occurred (e.g., because the parameter packs
6678 /// are to be instantiated with arguments of different lengths), false
6679 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6681 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6682 SourceRange PatternRange,
6683 ArrayRef<UnexpandedParameterPack> Unexpanded,
6684 const MultiLevelTemplateArgumentList &TemplateArgs,
6686 bool &RetainExpansion,
6687 Optional<unsigned> &NumExpansions);
6689 /// \brief Determine the number of arguments in the given pack expansion
6692 /// This routine assumes that the number of arguments in the expansion is
6693 /// consistent across all of the unexpanded parameter packs in its pattern.
6695 /// Returns an empty Optional if the type can't be expanded.
6696 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6697 const MultiLevelTemplateArgumentList &TemplateArgs);
6699 /// \brief Determine whether the given declarator contains any unexpanded
6700 /// parameter packs.
6702 /// This routine is used by the parser to disambiguate function declarators
6703 /// with an ellipsis prior to the ')', e.g.,
6709 /// To determine whether we have an (unnamed) function parameter pack or
6710 /// a variadic function.
6712 /// \returns true if the declarator contains any unexpanded parameter packs,
6713 /// false otherwise.
6714 bool containsUnexpandedParameterPacks(Declarator &D);
6716 /// \brief Returns the pattern of the pack expansion for a template argument.
6718 /// \param OrigLoc The template argument to expand.
6720 /// \param Ellipsis Will be set to the location of the ellipsis.
6722 /// \param NumExpansions Will be set to the number of expansions that will
6723 /// be generated from this pack expansion, if known a priori.
6724 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6725 TemplateArgumentLoc OrigLoc,
6726 SourceLocation &Ellipsis,
6727 Optional<unsigned> &NumExpansions) const;
6729 /// Given a template argument that contains an unexpanded parameter pack, but
6730 /// which has already been substituted, attempt to determine the number of
6731 /// elements that will be produced once this argument is fully-expanded.
6733 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6734 /// avoid actually expanding the pack where possible.
6735 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6737 //===--------------------------------------------------------------------===//
6738 // C++ Template Argument Deduction (C++ [temp.deduct])
6739 //===--------------------------------------------------------------------===//
6741 /// Adjust the type \p ArgFunctionType to match the calling convention,
6742 /// noreturn, and optionally the exception specification of \p FunctionType.
6743 /// Deduction often wants to ignore these properties when matching function
6745 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6746 bool AdjustExceptionSpec = false);
6748 /// \brief Describes the result of template argument deduction.
6750 /// The TemplateDeductionResult enumeration describes the result of
6751 /// template argument deduction, as returned from
6752 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6753 /// structure provides additional information about the results of
6754 /// template argument deduction, e.g., the deduced template argument
6755 /// list (if successful) or the specific template parameters or
6756 /// deduced arguments that were involved in the failure.
6757 enum TemplateDeductionResult {
6758 /// \brief Template argument deduction was successful.
6760 /// \brief The declaration was invalid; do nothing.
6762 /// \brief Template argument deduction exceeded the maximum template
6763 /// instantiation depth (which has already been diagnosed).
6764 TDK_InstantiationDepth,
6765 /// \brief Template argument deduction did not deduce a value
6766 /// for every template parameter.
6768 /// \brief Template argument deduction produced inconsistent
6769 /// deduced values for the given template parameter.
6771 /// \brief Template argument deduction failed due to inconsistent
6772 /// cv-qualifiers on a template parameter type that would
6773 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6774 /// but were given a non-const "X".
6776 /// \brief Substitution of the deduced template argument values
6777 /// resulted in an error.
6778 TDK_SubstitutionFailure,
6779 /// \brief After substituting deduced template arguments, a dependent
6780 /// parameter type did not match the corresponding argument.
6781 TDK_DeducedMismatch,
6782 /// \brief After substituting deduced template arguments, an element of
6783 /// a dependent parameter type did not match the corresponding element
6784 /// of the corresponding argument (when deducing from an initializer list).
6785 TDK_DeducedMismatchNested,
6786 /// \brief A non-depnedent component of the parameter did not match the
6787 /// corresponding component of the argument.
6788 TDK_NonDeducedMismatch,
6789 /// \brief When performing template argument deduction for a function
6790 /// template, there were too many call arguments.
6791 TDK_TooManyArguments,
6792 /// \brief When performing template argument deduction for a function
6793 /// template, there were too few call arguments.
6794 TDK_TooFewArguments,
6795 /// \brief The explicitly-specified template arguments were not valid
6796 /// template arguments for the given template.
6797 TDK_InvalidExplicitArguments,
6798 /// \brief Checking non-dependent argument conversions failed.
6799 TDK_NonDependentConversionFailure,
6800 /// \brief Deduction failed; that's all we know.
6801 TDK_MiscellaneousDeductionFailure,
6802 /// \brief CUDA Target attributes do not match.
6803 TDK_CUDATargetMismatch
6806 TemplateDeductionResult
6807 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6808 const TemplateArgumentList &TemplateArgs,
6809 sema::TemplateDeductionInfo &Info);
6811 TemplateDeductionResult
6812 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6813 const TemplateArgumentList &TemplateArgs,
6814 sema::TemplateDeductionInfo &Info);
6816 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6817 FunctionTemplateDecl *FunctionTemplate,
6818 TemplateArgumentListInfo &ExplicitTemplateArgs,
6819 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6820 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6821 sema::TemplateDeductionInfo &Info);
6823 /// brief A function argument from which we performed template argument
6824 // deduction for a call.
6825 struct OriginalCallArg {
6826 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6827 unsigned ArgIdx, QualType OriginalArgType)
6828 : OriginalParamType(OriginalParamType),
6829 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6830 OriginalArgType(OriginalArgType) {}
6832 QualType OriginalParamType;
6833 bool DecomposedParam;
6835 QualType OriginalArgType;
6838 TemplateDeductionResult FinishTemplateArgumentDeduction(
6839 FunctionTemplateDecl *FunctionTemplate,
6840 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6841 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6842 sema::TemplateDeductionInfo &Info,
6843 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6844 bool PartialOverloading = false,
6845 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6847 TemplateDeductionResult DeduceTemplateArguments(
6848 FunctionTemplateDecl *FunctionTemplate,
6849 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6850 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6851 bool PartialOverloading,
6852 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6854 TemplateDeductionResult
6855 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6856 TemplateArgumentListInfo *ExplicitTemplateArgs,
6857 QualType ArgFunctionType,
6858 FunctionDecl *&Specialization,
6859 sema::TemplateDeductionInfo &Info,
6860 bool IsAddressOfFunction = false);
6862 TemplateDeductionResult
6863 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6865 CXXConversionDecl *&Specialization,
6866 sema::TemplateDeductionInfo &Info);
6868 TemplateDeductionResult
6869 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6870 TemplateArgumentListInfo *ExplicitTemplateArgs,
6871 FunctionDecl *&Specialization,
6872 sema::TemplateDeductionInfo &Info,
6873 bool IsAddressOfFunction = false);
6875 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6876 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6877 /// \brief Substitute Replacement for auto in TypeWithAuto
6878 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6879 QualType Replacement);
6880 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6881 /// \p Replacement. This does not retain any \c auto type sugar.
6882 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6884 /// \brief Result type of DeduceAutoType.
6885 enum DeduceAutoResult {
6888 DAR_FailedAlreadyDiagnosed
6892 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6893 Optional<unsigned> DependentDeductionDepth = None);
6895 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6896 Optional<unsigned> DependentDeductionDepth = None);
6897 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6898 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6899 bool Diagnose = true);
6901 /// \brief Declare implicit deduction guides for a class template if we've
6902 /// not already done so.
6903 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6904 SourceLocation Loc);
6906 QualType DeduceTemplateSpecializationFromInitializer(
6907 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6908 const InitializationKind &Kind, MultiExprArg Init);
6910 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6911 QualType Type, TypeSourceInfo *TSI,
6912 SourceRange Range, bool DirectInit,
6915 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6917 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6918 SourceLocation ReturnLoc,
6919 Expr *&RetExpr, AutoType *AT);
6921 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6922 FunctionTemplateDecl *FT2,
6924 TemplatePartialOrderingContext TPOC,
6925 unsigned NumCallArguments1,
6926 unsigned NumCallArguments2);
6927 UnresolvedSetIterator
6928 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6929 TemplateSpecCandidateSet &FailedCandidates,
6931 const PartialDiagnostic &NoneDiag,
6932 const PartialDiagnostic &AmbigDiag,
6933 const PartialDiagnostic &CandidateDiag,
6934 bool Complain = true, QualType TargetType = QualType());
6936 ClassTemplatePartialSpecializationDecl *
6937 getMoreSpecializedPartialSpecialization(
6938 ClassTemplatePartialSpecializationDecl *PS1,
6939 ClassTemplatePartialSpecializationDecl *PS2,
6940 SourceLocation Loc);
6942 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6943 sema::TemplateDeductionInfo &Info);
6945 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6946 VarTemplatePartialSpecializationDecl *PS1,
6947 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6949 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6950 sema::TemplateDeductionInfo &Info);
6952 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6953 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6955 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6958 llvm::SmallBitVector &Used);
6959 void MarkDeducedTemplateParameters(
6960 const FunctionTemplateDecl *FunctionTemplate,
6961 llvm::SmallBitVector &Deduced) {
6962 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6964 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6965 const FunctionTemplateDecl *FunctionTemplate,
6966 llvm::SmallBitVector &Deduced);
6968 //===--------------------------------------------------------------------===//
6969 // C++ Template Instantiation
6972 MultiLevelTemplateArgumentList
6973 getTemplateInstantiationArgs(NamedDecl *D,
6974 const TemplateArgumentList *Innermost = nullptr,
6975 bool RelativeToPrimary = false,
6976 const FunctionDecl *Pattern = nullptr);
6978 /// A context in which code is being synthesized (where a source location
6979 /// alone is not sufficient to identify the context). This covers template
6980 /// instantiation and various forms of implicitly-generated functions.
6981 struct CodeSynthesisContext {
6982 /// \brief The kind of template instantiation we are performing
6983 enum SynthesisKind {
6984 /// We are instantiating a template declaration. The entity is
6985 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6986 TemplateInstantiation,
6988 /// We are instantiating a default argument for a template
6989 /// parameter. The Entity is the template parameter whose argument is
6990 /// being instantiated, the Template is the template, and the
6991 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6993 DefaultTemplateArgumentInstantiation,
6995 /// We are instantiating a default argument for a function.
6996 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6997 /// provides the template arguments as specified.
6998 DefaultFunctionArgumentInstantiation,
7000 /// We are substituting explicit template arguments provided for
7001 /// a function template. The entity is a FunctionTemplateDecl.
7002 ExplicitTemplateArgumentSubstitution,
7004 /// We are substituting template argument determined as part of
7005 /// template argument deduction for either a class template
7006 /// partial specialization or a function template. The
7007 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7009 DeducedTemplateArgumentSubstitution,
7011 /// We are substituting prior template arguments into a new
7012 /// template parameter. The template parameter itself is either a
7013 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7014 PriorTemplateArgumentSubstitution,
7016 /// We are checking the validity of a default template argument that
7017 /// has been used when naming a template-id.
7018 DefaultTemplateArgumentChecking,
7020 /// We are instantiating the exception specification for a function
7021 /// template which was deferred until it was needed.
7022 ExceptionSpecInstantiation,
7024 /// We are declaring an implicit special member function.
7025 DeclaringSpecialMember,
7027 /// We are defining a synthesized function (such as a defaulted special
7029 DefiningSynthesizedFunction,
7032 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7033 bool SavedInNonInstantiationSFINAEContext;
7035 /// \brief The point of instantiation or synthesis within the source code.
7036 SourceLocation PointOfInstantiation;
7038 /// \brief The entity that is being synthesized.
7041 /// \brief The template (or partial specialization) in which we are
7042 /// performing the instantiation, for substitutions of prior template
7044 NamedDecl *Template;
7046 /// \brief The list of template arguments we are substituting, if they
7047 /// are not part of the entity.
7048 const TemplateArgument *TemplateArgs;
7050 // FIXME: Wrap this union around more members, or perhaps store the
7051 // kind-specific members in the RAII object owning the context.
7053 /// \brief The number of template arguments in TemplateArgs.
7054 unsigned NumTemplateArgs;
7056 /// \brief The special member being declared or defined.
7057 CXXSpecialMember SpecialMember;
7060 ArrayRef<TemplateArgument> template_arguments() const {
7061 assert(Kind != DeclaringSpecialMember);
7062 return {TemplateArgs, NumTemplateArgs};
7065 /// \brief The template deduction info object associated with the
7066 /// substitution or checking of explicit or deduced template arguments.
7067 sema::TemplateDeductionInfo *DeductionInfo;
7069 /// \brief The source range that covers the construct that cause
7070 /// the instantiation, e.g., the template-id that causes a class
7071 /// template instantiation.
7072 SourceRange InstantiationRange;
7074 CodeSynthesisContext()
7075 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7076 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7078 /// \brief Determines whether this template is an actual instantiation
7079 /// that should be counted toward the maximum instantiation depth.
7080 bool isInstantiationRecord() const;
7083 /// \brief List of active code synthesis contexts.
7085 /// This vector is treated as a stack. As synthesis of one entity requires
7086 /// synthesis of another, additional contexts are pushed onto the stack.
7087 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7089 /// Specializations whose definitions are currently being instantiated.
7090 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7092 /// Non-dependent types used in templates that have already been instantiated
7093 /// by some template instantiation.
7094 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7096 /// \brief Extra modules inspected when performing a lookup during a template
7097 /// instantiation. Computed lazily.
7098 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7100 /// \brief Cache of additional modules that should be used for name lookup
7101 /// within the current template instantiation. Computed lazily; use
7102 /// getLookupModules() to get a complete set.
7103 llvm::DenseSet<Module*> LookupModulesCache;
7105 /// \brief Get the set of additional modules that should be checked during
7106 /// name lookup. A module and its imports become visible when instanting a
7107 /// template defined within it.
7108 llvm::DenseSet<Module*> &getLookupModules();
7110 /// \brief Map from the most recent declaration of a namespace to the most
7111 /// recent visible declaration of that namespace.
7112 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7114 /// \brief Whether we are in a SFINAE context that is not associated with
7115 /// template instantiation.
7117 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7118 /// of a template instantiation or template argument deduction.
7119 bool InNonInstantiationSFINAEContext;
7121 /// \brief The number of \p CodeSynthesisContexts that are not template
7122 /// instantiations and, therefore, should not be counted as part of the
7123 /// instantiation depth.
7125 /// When the instantiation depth reaches the user-configurable limit
7126 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7127 // FIXME: Should we have a similar limit for other forms of synthesis?
7128 unsigned NonInstantiationEntries;
7130 /// \brief The depth of the context stack at the point when the most recent
7131 /// error or warning was produced.
7133 /// This value is used to suppress printing of redundant context stacks
7134 /// when there are multiple errors or warnings in the same instantiation.
7135 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7136 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7138 /// \brief The current index into pack expansion arguments that will be
7139 /// used for substitution of parameter packs.
7141 /// The pack expansion index will be -1 to indicate that parameter packs
7142 /// should be instantiated as themselves. Otherwise, the index specifies
7143 /// which argument within the parameter pack will be used for substitution.
7144 int ArgumentPackSubstitutionIndex;
7146 /// \brief RAII object used to change the argument pack substitution index
7147 /// within a \c Sema object.
7149 /// See \c ArgumentPackSubstitutionIndex for more information.
7150 class ArgumentPackSubstitutionIndexRAII {
7152 int OldSubstitutionIndex;
7155 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7156 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7157 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7160 ~ArgumentPackSubstitutionIndexRAII() {
7161 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7165 friend class ArgumentPackSubstitutionRAII;
7167 /// \brief For each declaration that involved template argument deduction, the
7168 /// set of diagnostics that were suppressed during that template argument
7171 /// FIXME: Serialize this structure to the AST file.
7172 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7173 SuppressedDiagnosticsMap;
7174 SuppressedDiagnosticsMap SuppressedDiagnostics;
7176 /// \brief A stack object to be created when performing template
7179 /// Construction of an object of type \c InstantiatingTemplate
7180 /// pushes the current instantiation onto the stack of active
7181 /// instantiations. If the size of this stack exceeds the maximum
7182 /// number of recursive template instantiations, construction
7183 /// produces an error and evaluates true.
7185 /// Destruction of this object will pop the named instantiation off
7187 struct InstantiatingTemplate {
7188 /// \brief Note that we are instantiating a class template,
7189 /// function template, variable template, alias template,
7190 /// or a member thereof.
7191 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7193 SourceRange InstantiationRange = SourceRange());
7195 struct ExceptionSpecification {};
7196 /// \brief Note that we are instantiating an exception specification
7197 /// of a function template.
7198 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7199 FunctionDecl *Entity, ExceptionSpecification,
7200 SourceRange InstantiationRange = SourceRange());
7202 /// \brief Note that we are instantiating a default argument in a
7204 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7205 TemplateParameter Param, TemplateDecl *Template,
7206 ArrayRef<TemplateArgument> TemplateArgs,
7207 SourceRange InstantiationRange = SourceRange());
7209 /// \brief Note that we are substituting either explicitly-specified or
7210 /// deduced template arguments during function template argument deduction.
7211 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7212 FunctionTemplateDecl *FunctionTemplate,
7213 ArrayRef<TemplateArgument> TemplateArgs,
7214 CodeSynthesisContext::SynthesisKind Kind,
7215 sema::TemplateDeductionInfo &DeductionInfo,
7216 SourceRange InstantiationRange = SourceRange());
7218 /// \brief Note that we are instantiating as part of template
7219 /// argument deduction for a class template declaration.
7220 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7221 TemplateDecl *Template,
7222 ArrayRef<TemplateArgument> TemplateArgs,
7223 sema::TemplateDeductionInfo &DeductionInfo,
7224 SourceRange InstantiationRange = SourceRange());
7226 /// \brief Note that we are instantiating as part of template
7227 /// argument deduction for a class template partial
7229 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7230 ClassTemplatePartialSpecializationDecl *PartialSpec,
7231 ArrayRef<TemplateArgument> TemplateArgs,
7232 sema::TemplateDeductionInfo &DeductionInfo,
7233 SourceRange InstantiationRange = SourceRange());
7235 /// \brief Note that we are instantiating as part of template
7236 /// argument deduction for a variable template partial
7238 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7239 VarTemplatePartialSpecializationDecl *PartialSpec,
7240 ArrayRef<TemplateArgument> TemplateArgs,
7241 sema::TemplateDeductionInfo &DeductionInfo,
7242 SourceRange InstantiationRange = SourceRange());
7244 /// \brief Note that we are instantiating a default argument for a function
7246 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7248 ArrayRef<TemplateArgument> TemplateArgs,
7249 SourceRange InstantiationRange = SourceRange());
7251 /// \brief Note that we are substituting prior template arguments into a
7252 /// non-type parameter.
7253 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7254 NamedDecl *Template,
7255 NonTypeTemplateParmDecl *Param,
7256 ArrayRef<TemplateArgument> TemplateArgs,
7257 SourceRange InstantiationRange);
7259 /// \brief Note that we are substituting prior template arguments into a
7260 /// template template parameter.
7261 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7262 NamedDecl *Template,
7263 TemplateTemplateParmDecl *Param,
7264 ArrayRef<TemplateArgument> TemplateArgs,
7265 SourceRange InstantiationRange);
7267 /// \brief Note that we are checking the default template argument
7268 /// against the template parameter for a given template-id.
7269 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7270 TemplateDecl *Template,
7272 ArrayRef<TemplateArgument> TemplateArgs,
7273 SourceRange InstantiationRange);
7276 /// \brief Note that we have finished instantiating this template.
7279 ~InstantiatingTemplate() { Clear(); }
7281 /// \brief Determines whether we have exceeded the maximum
7282 /// recursive template instantiations.
7283 bool isInvalid() const { return Invalid; }
7285 /// \brief Determine whether we are already instantiating this
7286 /// specialization in some surrounding active instantiation.
7287 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7292 bool AlreadyInstantiating;
7293 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7294 SourceRange InstantiationRange);
7296 InstantiatingTemplate(
7297 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7298 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7299 Decl *Entity, NamedDecl *Template = nullptr,
7300 ArrayRef<TemplateArgument> TemplateArgs = None,
7301 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7303 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7305 InstantiatingTemplate&
7306 operator=(const InstantiatingTemplate&) = delete;
7309 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7310 void popCodeSynthesisContext();
7312 /// Determine whether we are currently performing template instantiation.
7313 bool inTemplateInstantiation() const {
7314 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7317 void PrintContextStack() {
7318 if (!CodeSynthesisContexts.empty() &&
7319 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7320 PrintInstantiationStack();
7321 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7323 if (PragmaAttributeCurrentTargetDecl)
7324 PrintPragmaAttributeInstantiationPoint();
7326 void PrintInstantiationStack();
7328 void PrintPragmaAttributeInstantiationPoint();
7330 /// \brief Determines whether we are currently in a context where
7331 /// template argument substitution failures are not considered
7334 /// \returns An empty \c Optional if we're not in a SFINAE context.
7335 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7336 /// template-deduction context object, which can be used to capture
7337 /// diagnostics that will be suppressed.
7338 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7340 /// \brief Determines whether we are currently in a context that
7341 /// is not evaluated as per C++ [expr] p5.
7342 bool isUnevaluatedContext() const {
7343 assert(!ExprEvalContexts.empty() &&
7344 "Must be in an expression evaluation context");
7345 return ExprEvalContexts.back().isUnevaluated();
7348 /// \brief RAII class used to determine whether SFINAE has
7349 /// trapped any errors that occur during template argument
7353 unsigned PrevSFINAEErrors;
7354 bool PrevInNonInstantiationSFINAEContext;
7355 bool PrevAccessCheckingSFINAE;
7358 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7359 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7360 PrevInNonInstantiationSFINAEContext(
7361 SemaRef.InNonInstantiationSFINAEContext),
7362 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7364 if (!SemaRef.isSFINAEContext())
7365 SemaRef.InNonInstantiationSFINAEContext = true;
7366 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7370 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7371 SemaRef.InNonInstantiationSFINAEContext
7372 = PrevInNonInstantiationSFINAEContext;
7373 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7376 /// \brief Determine whether any SFINAE errors have been trapped.
7377 bool hasErrorOccurred() const {
7378 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7382 /// \brief RAII class used to indicate that we are performing provisional
7383 /// semantic analysis to determine the validity of a construct, so
7384 /// typo-correction and diagnostics in the immediate context (not within
7385 /// implicitly-instantiated templates) should be suppressed.
7386 class TentativeAnalysisScope {
7388 // FIXME: Using a SFINAETrap for this is a hack.
7390 bool PrevDisableTypoCorrection;
7392 explicit TentativeAnalysisScope(Sema &SemaRef)
7393 : SemaRef(SemaRef), Trap(SemaRef, true),
7394 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7395 SemaRef.DisableTypoCorrection = true;
7397 ~TentativeAnalysisScope() {
7398 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7402 /// \brief The current instantiation scope used to store local
7404 LocalInstantiationScope *CurrentInstantiationScope;
7406 /// \brief Tracks whether we are in a context where typo correction is
7408 bool DisableTypoCorrection;
7410 /// \brief The number of typos corrected by CorrectTypo.
7411 unsigned TyposCorrected;
7413 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7414 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7416 /// \brief A cache containing identifiers for which typo correction failed and
7417 /// their locations, so that repeated attempts to correct an identifier in a
7418 /// given location are ignored if typo correction already failed for it.
7419 IdentifierSourceLocations TypoCorrectionFailures;
7421 /// \brief Worker object for performing CFG-based warnings.
7422 sema::AnalysisBasedWarnings AnalysisWarnings;
7423 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7425 /// \brief An entity for which implicit template instantiation is required.
7427 /// The source location associated with the declaration is the first place in
7428 /// the source code where the declaration was "used". It is not necessarily
7429 /// the point of instantiation (which will be either before or after the
7430 /// namespace-scope declaration that triggered this implicit instantiation),
7431 /// However, it is the location that diagnostics should generally refer to,
7432 /// because users will need to know what code triggered the instantiation.
7433 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7435 /// \brief The queue of implicit template instantiations that are required
7436 /// but have not yet been performed.
7437 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7439 class GlobalEagerInstantiationScope {
7441 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7442 : S(S), Enabled(Enabled) {
7443 if (!Enabled) return;
7445 SavedPendingInstantiations.swap(S.PendingInstantiations);
7446 SavedVTableUses.swap(S.VTableUses);
7451 S.DefineUsedVTables();
7452 S.PerformPendingInstantiations();
7456 ~GlobalEagerInstantiationScope() {
7457 if (!Enabled) return;
7459 // Restore the set of pending vtables.
7460 assert(S.VTableUses.empty() &&
7461 "VTableUses should be empty before it is discarded.");
7462 S.VTableUses.swap(SavedVTableUses);
7464 // Restore the set of pending implicit instantiations.
7465 assert(S.PendingInstantiations.empty() &&
7466 "PendingInstantiations should be empty before it is discarded.");
7467 S.PendingInstantiations.swap(SavedPendingInstantiations);
7472 SmallVector<VTableUse, 16> SavedVTableUses;
7473 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7477 /// \brief The queue of implicit template instantiations that are required
7478 /// and must be performed within the current local scope.
7480 /// This queue is only used for member functions of local classes in
7481 /// templates, which must be instantiated in the same scope as their
7482 /// enclosing function, so that they can reference function-local
7483 /// types, static variables, enumerators, etc.
7484 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7486 class LocalEagerInstantiationScope {
7488 LocalEagerInstantiationScope(Sema &S) : S(S) {
7489 SavedPendingLocalImplicitInstantiations.swap(
7490 S.PendingLocalImplicitInstantiations);
7493 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7495 ~LocalEagerInstantiationScope() {
7496 assert(S.PendingLocalImplicitInstantiations.empty() &&
7497 "there shouldn't be any pending local implicit instantiations");
7498 SavedPendingLocalImplicitInstantiations.swap(
7499 S.PendingLocalImplicitInstantiations);
7504 std::deque<PendingImplicitInstantiation>
7505 SavedPendingLocalImplicitInstantiations;
7508 /// A helper class for building up ExtParameterInfos.
7509 class ExtParameterInfoBuilder {
7510 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7511 bool HasInteresting = false;
7514 /// Set the ExtParameterInfo for the parameter at the given index,
7516 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7517 assert(Infos.size() <= index);
7518 Infos.resize(index);
7519 Infos.push_back(info);
7521 if (!HasInteresting)
7522 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7525 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7526 /// ExtParameterInfo array we've built up.
7527 const FunctionProtoType::ExtParameterInfo *
7528 getPointerOrNull(unsigned numParams) {
7529 if (!HasInteresting) return nullptr;
7530 Infos.resize(numParams);
7531 return Infos.data();
7535 void PerformPendingInstantiations(bool LocalOnly = false);
7537 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7538 const MultiLevelTemplateArgumentList &TemplateArgs,
7539 SourceLocation Loc, DeclarationName Entity,
7540 bool AllowDeducedTST = false);
7542 QualType SubstType(QualType T,
7543 const MultiLevelTemplateArgumentList &TemplateArgs,
7544 SourceLocation Loc, DeclarationName Entity);
7546 TypeSourceInfo *SubstType(TypeLoc TL,
7547 const MultiLevelTemplateArgumentList &TemplateArgs,
7548 SourceLocation Loc, DeclarationName Entity);
7550 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7551 const MultiLevelTemplateArgumentList &TemplateArgs,
7553 DeclarationName Entity,
7554 CXXRecordDecl *ThisContext,
7555 unsigned ThisTypeQuals);
7556 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7557 const MultiLevelTemplateArgumentList &Args);
7558 bool SubstExceptionSpec(SourceLocation Loc,
7559 FunctionProtoType::ExceptionSpecInfo &ESI,
7560 SmallVectorImpl<QualType> &ExceptionStorage,
7561 const MultiLevelTemplateArgumentList &Args);
7562 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7563 const MultiLevelTemplateArgumentList &TemplateArgs,
7564 int indexAdjustment,
7565 Optional<unsigned> NumExpansions,
7566 bool ExpectParameterPack);
7567 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7568 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7569 const MultiLevelTemplateArgumentList &TemplateArgs,
7570 SmallVectorImpl<QualType> &ParamTypes,
7571 SmallVectorImpl<ParmVarDecl *> *OutParams,
7572 ExtParameterInfoBuilder &ParamInfos);
7573 ExprResult SubstExpr(Expr *E,
7574 const MultiLevelTemplateArgumentList &TemplateArgs);
7576 /// \brief Substitute the given template arguments into a list of
7577 /// expressions, expanding pack expansions if required.
7579 /// \param Exprs The list of expressions to substitute into.
7581 /// \param IsCall Whether this is some form of call, in which case
7582 /// default arguments will be dropped.
7584 /// \param TemplateArgs The set of template arguments to substitute.
7586 /// \param Outputs Will receive all of the substituted arguments.
7588 /// \returns true if an error occurred, false otherwise.
7589 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7590 const MultiLevelTemplateArgumentList &TemplateArgs,
7591 SmallVectorImpl<Expr *> &Outputs);
7593 StmtResult SubstStmt(Stmt *S,
7594 const MultiLevelTemplateArgumentList &TemplateArgs);
7596 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7597 const MultiLevelTemplateArgumentList &TemplateArgs);
7599 ExprResult SubstInitializer(Expr *E,
7600 const MultiLevelTemplateArgumentList &TemplateArgs,
7601 bool CXXDirectInit);
7604 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7605 CXXRecordDecl *Pattern,
7606 const MultiLevelTemplateArgumentList &TemplateArgs);
7609 InstantiateClass(SourceLocation PointOfInstantiation,
7610 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7611 const MultiLevelTemplateArgumentList &TemplateArgs,
7612 TemplateSpecializationKind TSK,
7613 bool Complain = true);
7615 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7616 EnumDecl *Instantiation, EnumDecl *Pattern,
7617 const MultiLevelTemplateArgumentList &TemplateArgs,
7618 TemplateSpecializationKind TSK);
7620 bool InstantiateInClassInitializer(
7621 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7622 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7624 struct LateInstantiatedAttribute {
7625 const Attr *TmplAttr;
7626 LocalInstantiationScope *Scope;
7629 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7631 : TmplAttr(A), Scope(S), NewDecl(D)
7634 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7636 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7637 const Decl *Pattern, Decl *Inst,
7638 LateInstantiatedAttrVec *LateAttrs = nullptr,
7639 LocalInstantiationScope *OuterMostScope = nullptr);
7642 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7643 const Decl *Pattern, Decl *Inst,
7644 LateInstantiatedAttrVec *LateAttrs = nullptr,
7645 LocalInstantiationScope *OuterMostScope = nullptr);
7647 bool usesPartialOrExplicitSpecialization(
7648 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7651 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7652 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7653 TemplateSpecializationKind TSK,
7654 bool Complain = true);
7656 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7657 CXXRecordDecl *Instantiation,
7658 const MultiLevelTemplateArgumentList &TemplateArgs,
7659 TemplateSpecializationKind TSK);
7661 void InstantiateClassTemplateSpecializationMembers(
7662 SourceLocation PointOfInstantiation,
7663 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7664 TemplateSpecializationKind TSK);
7666 NestedNameSpecifierLoc
7667 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7668 const MultiLevelTemplateArgumentList &TemplateArgs);
7671 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7672 const MultiLevelTemplateArgumentList &TemplateArgs);
7674 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7676 const MultiLevelTemplateArgumentList &TemplateArgs);
7677 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7678 TemplateArgumentListInfo &Result,
7679 const MultiLevelTemplateArgumentList &TemplateArgs);
7681 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7682 FunctionDecl *Function);
7683 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7684 FunctionDecl *Function,
7685 bool Recursive = false,
7686 bool DefinitionRequired = false,
7687 bool AtEndOfTU = false);
7688 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7689 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7690 const TemplateArgumentList &TemplateArgList,
7691 const TemplateArgumentListInfo &TemplateArgsInfo,
7692 SmallVectorImpl<TemplateArgument> &Converted,
7693 SourceLocation PointOfInstantiation, void *InsertPos,
7694 LateInstantiatedAttrVec *LateAttrs = nullptr,
7695 LocalInstantiationScope *StartingScope = nullptr);
7696 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7697 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7698 const MultiLevelTemplateArgumentList &TemplateArgs);
7700 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7701 const MultiLevelTemplateArgumentList &TemplateArgs,
7702 LateInstantiatedAttrVec *LateAttrs,
7704 LocalInstantiationScope *StartingScope,
7705 bool InstantiatingVarTemplate = false);
7706 void InstantiateVariableInitializer(
7707 VarDecl *Var, VarDecl *OldVar,
7708 const MultiLevelTemplateArgumentList &TemplateArgs);
7709 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7710 VarDecl *Var, bool Recursive = false,
7711 bool DefinitionRequired = false,
7712 bool AtEndOfTU = false);
7713 void InstantiateStaticDataMemberDefinition(
7714 SourceLocation PointOfInstantiation,
7716 bool Recursive = false,
7717 bool DefinitionRequired = false);
7719 void InstantiateMemInitializers(CXXConstructorDecl *New,
7720 const CXXConstructorDecl *Tmpl,
7721 const MultiLevelTemplateArgumentList &TemplateArgs);
7723 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7724 const MultiLevelTemplateArgumentList &TemplateArgs,
7725 bool FindingInstantiatedContext = false);
7726 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7727 const MultiLevelTemplateArgumentList &TemplateArgs);
7729 // Objective-C declarations.
7730 enum ObjCContainerKind {
7737 OCK_CategoryImplementation
7739 ObjCContainerKind getObjCContainerKind() const;
7741 DeclResult actOnObjCTypeParam(Scope *S,
7742 ObjCTypeParamVariance variance,
7743 SourceLocation varianceLoc,
7745 IdentifierInfo *paramName,
7746 SourceLocation paramLoc,
7747 SourceLocation colonLoc,
7748 ParsedType typeBound);
7750 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7751 ArrayRef<Decl *> typeParams,
7752 SourceLocation rAngleLoc);
7753 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7755 Decl *ActOnStartClassInterface(Scope *S,
7756 SourceLocation AtInterfaceLoc,
7757 IdentifierInfo *ClassName,
7758 SourceLocation ClassLoc,
7759 ObjCTypeParamList *typeParamList,
7760 IdentifierInfo *SuperName,
7761 SourceLocation SuperLoc,
7762 ArrayRef<ParsedType> SuperTypeArgs,
7763 SourceRange SuperTypeArgsRange,
7764 Decl * const *ProtoRefs,
7765 unsigned NumProtoRefs,
7766 const SourceLocation *ProtoLocs,
7767 SourceLocation EndProtoLoc,
7768 AttributeList *AttrList);
7770 void ActOnSuperClassOfClassInterface(Scope *S,
7771 SourceLocation AtInterfaceLoc,
7772 ObjCInterfaceDecl *IDecl,
7773 IdentifierInfo *ClassName,
7774 SourceLocation ClassLoc,
7775 IdentifierInfo *SuperName,
7776 SourceLocation SuperLoc,
7777 ArrayRef<ParsedType> SuperTypeArgs,
7778 SourceRange SuperTypeArgsRange);
7780 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7781 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7782 IdentifierInfo *SuperName,
7783 SourceLocation SuperLoc);
7785 Decl *ActOnCompatibilityAlias(
7786 SourceLocation AtCompatibilityAliasLoc,
7787 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7788 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7790 bool CheckForwardProtocolDeclarationForCircularDependency(
7791 IdentifierInfo *PName,
7792 SourceLocation &PLoc, SourceLocation PrevLoc,
7793 const ObjCList<ObjCProtocolDecl> &PList);
7795 Decl *ActOnStartProtocolInterface(
7796 SourceLocation AtProtoInterfaceLoc,
7797 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7798 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7799 const SourceLocation *ProtoLocs,
7800 SourceLocation EndProtoLoc,
7801 AttributeList *AttrList);
7803 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7804 IdentifierInfo *ClassName,
7805 SourceLocation ClassLoc,
7806 ObjCTypeParamList *typeParamList,
7807 IdentifierInfo *CategoryName,
7808 SourceLocation CategoryLoc,
7809 Decl * const *ProtoRefs,
7810 unsigned NumProtoRefs,
7811 const SourceLocation *ProtoLocs,
7812 SourceLocation EndProtoLoc,
7813 AttributeList *AttrList);
7815 Decl *ActOnStartClassImplementation(
7816 SourceLocation AtClassImplLoc,
7817 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7818 IdentifierInfo *SuperClassname,
7819 SourceLocation SuperClassLoc);
7821 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7822 IdentifierInfo *ClassName,
7823 SourceLocation ClassLoc,
7824 IdentifierInfo *CatName,
7825 SourceLocation CatLoc);
7827 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7828 ArrayRef<Decl *> Decls);
7830 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7831 IdentifierInfo **IdentList,
7832 SourceLocation *IdentLocs,
7833 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7836 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7837 ArrayRef<IdentifierLocPair> IdentList,
7838 AttributeList *attrList);
7840 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7841 ArrayRef<IdentifierLocPair> ProtocolId,
7842 SmallVectorImpl<Decl *> &Protocols);
7844 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7845 SourceLocation ProtocolLoc,
7846 IdentifierInfo *TypeArgId,
7847 SourceLocation TypeArgLoc,
7848 bool SelectProtocolFirst = false);
7850 /// Given a list of identifiers (and their locations), resolve the
7851 /// names to either Objective-C protocol qualifiers or type
7852 /// arguments, as appropriate.
7853 void actOnObjCTypeArgsOrProtocolQualifiers(
7855 ParsedType baseType,
7856 SourceLocation lAngleLoc,
7857 ArrayRef<IdentifierInfo *> identifiers,
7858 ArrayRef<SourceLocation> identifierLocs,
7859 SourceLocation rAngleLoc,
7860 SourceLocation &typeArgsLAngleLoc,
7861 SmallVectorImpl<ParsedType> &typeArgs,
7862 SourceLocation &typeArgsRAngleLoc,
7863 SourceLocation &protocolLAngleLoc,
7864 SmallVectorImpl<Decl *> &protocols,
7865 SourceLocation &protocolRAngleLoc,
7866 bool warnOnIncompleteProtocols);
7868 /// Build a an Objective-C protocol-qualified 'id' type where no
7869 /// base type was specified.
7870 TypeResult actOnObjCProtocolQualifierType(
7871 SourceLocation lAngleLoc,
7872 ArrayRef<Decl *> protocols,
7873 ArrayRef<SourceLocation> protocolLocs,
7874 SourceLocation rAngleLoc);
7876 /// Build a specialized and/or protocol-qualified Objective-C type.
7877 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7880 ParsedType BaseType,
7881 SourceLocation TypeArgsLAngleLoc,
7882 ArrayRef<ParsedType> TypeArgs,
7883 SourceLocation TypeArgsRAngleLoc,
7884 SourceLocation ProtocolLAngleLoc,
7885 ArrayRef<Decl *> Protocols,
7886 ArrayRef<SourceLocation> ProtocolLocs,
7887 SourceLocation ProtocolRAngleLoc);
7889 /// Build an Objective-C type parameter type.
7890 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7891 SourceLocation ProtocolLAngleLoc,
7892 ArrayRef<ObjCProtocolDecl *> Protocols,
7893 ArrayRef<SourceLocation> ProtocolLocs,
7894 SourceLocation ProtocolRAngleLoc,
7895 bool FailOnError = false);
7897 /// Build an Objective-C object pointer type.
7898 QualType BuildObjCObjectType(QualType BaseType,
7900 SourceLocation TypeArgsLAngleLoc,
7901 ArrayRef<TypeSourceInfo *> TypeArgs,
7902 SourceLocation TypeArgsRAngleLoc,
7903 SourceLocation ProtocolLAngleLoc,
7904 ArrayRef<ObjCProtocolDecl *> Protocols,
7905 ArrayRef<SourceLocation> ProtocolLocs,
7906 SourceLocation ProtocolRAngleLoc,
7907 bool FailOnError = false);
7909 /// Check the application of the Objective-C '__kindof' qualifier to
7911 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7913 /// Ensure attributes are consistent with type.
7914 /// \param [in, out] Attributes The attributes to check; they will
7915 /// be modified to be consistent with \p PropertyTy.
7916 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7918 unsigned &Attributes,
7919 bool propertyInPrimaryClass);
7921 /// Process the specified property declaration and create decls for the
7922 /// setters and getters as needed.
7923 /// \param property The property declaration being processed
7924 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7927 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7928 ObjCPropertyDecl *SuperProperty,
7929 const IdentifierInfo *Name,
7930 bool OverridingProtocolProperty);
7932 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7933 ObjCInterfaceDecl *ID);
7935 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7936 ArrayRef<Decl *> allMethods = None,
7937 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7939 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7940 SourceLocation LParenLoc,
7941 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7942 Selector GetterSel, Selector SetterSel,
7943 tok::ObjCKeywordKind MethodImplKind,
7944 DeclContext *lexicalDC = nullptr);
7946 Decl *ActOnPropertyImplDecl(Scope *S,
7947 SourceLocation AtLoc,
7948 SourceLocation PropertyLoc,
7950 IdentifierInfo *PropertyId,
7951 IdentifierInfo *PropertyIvar,
7952 SourceLocation PropertyIvarLoc,
7953 ObjCPropertyQueryKind QueryKind);
7955 enum ObjCSpecialMethodKind {
7961 OSMK_NonRetainingInit
7964 struct ObjCArgInfo {
7965 IdentifierInfo *Name;
7966 SourceLocation NameLoc;
7967 // The Type is null if no type was specified, and the DeclSpec is invalid
7970 ObjCDeclSpec DeclSpec;
7972 /// ArgAttrs - Attribute list for this argument.
7973 AttributeList *ArgAttrs;
7976 Decl *ActOnMethodDeclaration(
7978 SourceLocation BeginLoc, // location of the + or -.
7979 SourceLocation EndLoc, // location of the ; or {.
7980 tok::TokenKind MethodType,
7981 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7982 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7983 // optional arguments. The number of types/arguments is obtained
7984 // from the Sel.getNumArgs().
7985 ObjCArgInfo *ArgInfo,
7986 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7987 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7988 bool isVariadic, bool MethodDefinition);
7990 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7991 const ObjCObjectPointerType *OPT,
7993 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7996 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7997 bool inferObjCARCLifetime(ValueDecl *decl);
8000 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8002 SourceLocation OpLoc,
8003 DeclarationName MemberName,
8004 SourceLocation MemberLoc,
8005 SourceLocation SuperLoc, QualType SuperType,
8009 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8010 IdentifierInfo &propertyName,
8011 SourceLocation receiverNameLoc,
8012 SourceLocation propertyNameLoc);
8014 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8016 /// \brief Describes the kind of message expression indicated by a message
8017 /// send that starts with an identifier.
8018 enum ObjCMessageKind {
8019 /// \brief The message is sent to 'super'.
8021 /// \brief The message is an instance message.
8022 ObjCInstanceMessage,
8023 /// \brief The message is a class message, and the identifier is a type
8028 ObjCMessageKind getObjCMessageKind(Scope *S,
8029 IdentifierInfo *Name,
8030 SourceLocation NameLoc,
8032 bool HasTrailingDot,
8033 ParsedType &ReceiverType);
8035 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8037 SourceLocation LBracLoc,
8038 ArrayRef<SourceLocation> SelectorLocs,
8039 SourceLocation RBracLoc,
8042 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8043 QualType ReceiverType,
8044 SourceLocation SuperLoc,
8046 ObjCMethodDecl *Method,
8047 SourceLocation LBracLoc,
8048 ArrayRef<SourceLocation> SelectorLocs,
8049 SourceLocation RBracLoc,
8051 bool isImplicit = false);
8053 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8054 bool isSuperReceiver,
8057 ObjCMethodDecl *Method,
8060 ExprResult ActOnClassMessage(Scope *S,
8061 ParsedType Receiver,
8063 SourceLocation LBracLoc,
8064 ArrayRef<SourceLocation> SelectorLocs,
8065 SourceLocation RBracLoc,
8068 ExprResult BuildInstanceMessage(Expr *Receiver,
8069 QualType ReceiverType,
8070 SourceLocation SuperLoc,
8072 ObjCMethodDecl *Method,
8073 SourceLocation LBracLoc,
8074 ArrayRef<SourceLocation> SelectorLocs,
8075 SourceLocation RBracLoc,
8077 bool isImplicit = false);
8079 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8080 QualType ReceiverType,
8083 ObjCMethodDecl *Method,
8086 ExprResult ActOnInstanceMessage(Scope *S,
8089 SourceLocation LBracLoc,
8090 ArrayRef<SourceLocation> SelectorLocs,
8091 SourceLocation RBracLoc,
8094 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8095 ObjCBridgeCastKind Kind,
8096 SourceLocation BridgeKeywordLoc,
8097 TypeSourceInfo *TSInfo,
8100 ExprResult ActOnObjCBridgedCast(Scope *S,
8101 SourceLocation LParenLoc,
8102 ObjCBridgeCastKind Kind,
8103 SourceLocation BridgeKeywordLoc,
8105 SourceLocation RParenLoc,
8108 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8110 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8112 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8115 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8116 QualType DestType, QualType SrcType,
8117 ObjCInterfaceDecl *&RelatedClass,
8118 ObjCMethodDecl *&ClassMethod,
8119 ObjCMethodDecl *&InstanceMethod,
8120 TypedefNameDecl *&TDNDecl,
8121 bool CfToNs, bool Diagnose = true);
8123 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8124 QualType DestType, QualType SrcType,
8125 Expr *&SrcExpr, bool Diagnose = true);
8127 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8128 bool Diagnose = true);
8130 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8132 /// \brief Check whether the given new method is a valid override of the
8133 /// given overridden method, and set any properties that should be inherited.
8134 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8135 const ObjCMethodDecl *Overridden);
8137 /// \brief Describes the compatibility of a result type with its method.
8138 enum ResultTypeCompatibilityKind {
8144 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8145 ObjCInterfaceDecl *CurrentClass,
8146 ResultTypeCompatibilityKind RTC);
8148 enum PragmaOptionsAlignKind {
8149 POAK_Native, // #pragma options align=native
8150 POAK_Natural, // #pragma options align=natural
8151 POAK_Packed, // #pragma options align=packed
8152 POAK_Power, // #pragma options align=power
8153 POAK_Mac68k, // #pragma options align=mac68k
8154 POAK_Reset // #pragma options align=reset
8157 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8158 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8159 PragmaClangSectionAction Action,
8160 PragmaClangSectionKind SecKind, StringRef SecName);
8162 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8163 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8164 SourceLocation PragmaLoc);
8166 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8167 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8168 StringRef SlotLabel, Expr *Alignment);
8170 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8171 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8173 /// ActOnPragmaMSComment - Called on well formed
8174 /// \#pragma comment(kind, "arg").
8175 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8178 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8179 /// pointers_to_members(representation method[, general purpose
8180 /// representation]).
8181 void ActOnPragmaMSPointersToMembers(
8182 LangOptions::PragmaMSPointersToMembersKind Kind,
8183 SourceLocation PragmaLoc);
8185 /// \brief Called on well formed \#pragma vtordisp().
8186 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8187 SourceLocation PragmaLoc,
8188 MSVtorDispAttr::Mode Value);
8190 enum PragmaSectionKind {
8197 bool UnifySection(StringRef SectionName,
8199 DeclaratorDecl *TheDecl);
8200 bool UnifySection(StringRef SectionName,
8202 SourceLocation PragmaSectionLocation);
8204 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8205 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8206 PragmaMsStackAction Action,
8207 llvm::StringRef StackSlotLabel,
8208 StringLiteral *SegmentName,
8209 llvm::StringRef PragmaName);
8211 /// \brief Called on well formed \#pragma section().
8212 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8213 int SectionFlags, StringLiteral *SegmentName);
8215 /// \brief Called on well-formed \#pragma init_seg().
8216 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8217 StringLiteral *SegmentName);
8219 /// \brief Called on #pragma clang __debug dump II
8220 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8222 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8223 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8226 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8227 void ActOnPragmaUnused(const Token &Identifier,
8229 SourceLocation PragmaLoc);
8231 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8232 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8233 SourceLocation PragmaLoc);
8235 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8236 SourceLocation Loc);
8237 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8239 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8240 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8241 SourceLocation PragmaLoc,
8242 SourceLocation WeakNameLoc);
8244 /// ActOnPragmaRedefineExtname - Called on well formed
8245 /// \#pragma redefine_extname oldname newname.
8246 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8247 IdentifierInfo* AliasName,
8248 SourceLocation PragmaLoc,
8249 SourceLocation WeakNameLoc,
8250 SourceLocation AliasNameLoc);
8252 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8253 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8254 IdentifierInfo* AliasName,
8255 SourceLocation PragmaLoc,
8256 SourceLocation WeakNameLoc,
8257 SourceLocation AliasNameLoc);
8259 /// ActOnPragmaFPContract - Called on well formed
8260 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8261 /// \#pragma clang fp contract
8262 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8264 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8265 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8266 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8268 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8269 void AddMsStructLayoutForRecord(RecordDecl *RD);
8271 /// FreePackedContext - Deallocate and null out PackContext.
8272 void FreePackedContext();
8274 /// PushNamespaceVisibilityAttr - Note that we've entered a
8275 /// namespace with a visibility attribute.
8276 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8277 SourceLocation Loc);
8279 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8280 /// add an appropriate visibility attribute.
8281 void AddPushedVisibilityAttribute(Decl *RD);
8283 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8284 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8285 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8287 /// FreeVisContext - Deallocate and null out VisContext.
8288 void FreeVisContext();
8290 /// AddCFAuditedAttribute - Check whether we're currently within
8291 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8292 /// the appropriate attribute.
8293 void AddCFAuditedAttribute(Decl *D);
8295 /// \brief Called on well-formed '\#pragma clang attribute push'.
8296 void ActOnPragmaAttributePush(AttributeList &Attribute,
8297 SourceLocation PragmaLoc,
8298 attr::ParsedSubjectMatchRuleSet Rules);
8300 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8301 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8303 /// \brief Adds the attributes that have been specified using the
8304 /// '\#pragma clang attribute push' directives to the given declaration.
8305 void AddPragmaAttributes(Scope *S, Decl *D);
8307 void DiagnoseUnterminatedPragmaAttribute();
8309 /// \brief Called on well formed \#pragma clang optimize.
8310 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8312 /// \brief Get the location for the currently active "\#pragma clang optimize
8313 /// off". If this location is invalid, then the state of the pragma is "on".
8314 SourceLocation getOptimizeOffPragmaLocation() const {
8315 return OptimizeOffPragmaLocation;
8318 /// \brief Only called on function definitions; if there is a pragma in scope
8319 /// with the effect of a range-based optnone, consider marking the function
8320 /// with attribute optnone.
8321 void AddRangeBasedOptnone(FunctionDecl *FD);
8323 /// \brief Adds the 'optnone' attribute to the function declaration if there
8324 /// are no conflicts; Loc represents the location causing the 'optnone'
8325 /// attribute to be added (usually because of a pragma).
8326 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8328 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8329 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8330 unsigned SpellingListIndex, bool IsPackExpansion);
8331 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8332 unsigned SpellingListIndex, bool IsPackExpansion);
8334 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8336 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8337 unsigned SpellingListIndex);
8339 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8341 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8342 unsigned SpellingListIndex);
8344 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8346 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8347 unsigned SpellingListIndex);
8349 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8351 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8352 Expr *MinBlocks, unsigned SpellingListIndex);
8354 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8355 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8356 unsigned SpellingListIndex, bool InInstantiation = false);
8358 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8359 ParameterABI ABI, unsigned SpellingListIndex);
8361 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8362 unsigned SpellingListIndex, bool isNSConsumed,
8363 bool isTemplateInstantiation);
8365 //===--------------------------------------------------------------------===//
8366 // C++ Coroutines TS
8368 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8370 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8371 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8372 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8374 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8375 bool IsImplicit = false);
8376 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8377 UnresolvedLookupExpr* Lookup);
8378 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8379 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8380 bool IsImplicit = false);
8381 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8382 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8383 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8385 //===--------------------------------------------------------------------===//
8386 // OpenCL extensions.
8389 std::string CurrOpenCLExtension;
8390 /// Extensions required by an OpenCL type.
8391 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8392 /// Extensions required by an OpenCL declaration.
8393 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8395 llvm::StringRef getCurrentOpenCLExtension() const {
8396 return CurrOpenCLExtension;
8398 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8399 CurrOpenCLExtension = Ext;
8402 /// \brief Set OpenCL extensions for a type which can only be used when these
8403 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8404 /// \param Exts A space separated list of OpenCL extensions.
8405 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8407 /// \brief Set OpenCL extensions for a declaration which can only be
8408 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8410 /// \param Exts A space separated list of OpenCL extensions.
8411 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8413 /// \brief Set current OpenCL extensions for a type which can only be used
8414 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8415 /// empty, do nothing.
8416 void setCurrentOpenCLExtensionForType(QualType T);
8418 /// \brief Set current OpenCL extensions for a declaration which
8419 /// can only be used when these OpenCL extensions are enabled. If current
8420 /// OpenCL extension is empty, do nothing.
8421 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8423 bool isOpenCLDisabledDecl(Decl *FD);
8425 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8426 /// is disabled due to required OpenCL extensions being disabled. If so,
8427 /// emit diagnostics.
8428 /// \return true if type is disabled.
8429 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8431 /// \brief Check if declaration \p D used by expression \p E
8432 /// is disabled due to required OpenCL extensions being disabled. If so,
8433 /// emit diagnostics.
8434 /// \return true if type is disabled.
8435 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8437 //===--------------------------------------------------------------------===//
8438 // OpenMP directives and clauses.
8441 void *VarDataSharingAttributesStack;
8442 /// Set to true inside '#pragma omp declare target' region.
8443 bool IsInOpenMPDeclareTargetContext = false;
8444 /// \brief Initialization of data-sharing attributes stack.
8445 void InitDataSharingAttributesStack();
8446 void DestroyDataSharingAttributesStack();
8448 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8449 bool StrictlyPositive = true);
8450 /// Returns OpenMP nesting level for current directive.
8451 unsigned getOpenMPNestingLevel() const;
8453 /// Push new OpenMP function region for non-capturing function.
8454 void pushOpenMPFunctionRegion();
8456 /// Pop OpenMP function region for non-capturing function.
8457 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8459 /// Checks if a type or a declaration is disabled due to the owning extension
8460 /// being disabled, and emits diagnostic messages if it is disabled.
8461 /// \param D type or declaration to be checked.
8462 /// \param DiagLoc source location for the diagnostic message.
8463 /// \param DiagInfo information to be emitted for the diagnostic message.
8464 /// \param SrcRange source range of the declaration.
8465 /// \param Map maps type or declaration to the extensions.
8466 /// \param Selector selects diagnostic message: 0 for type and 1 for
8468 /// \return true if the type or declaration is disabled.
8469 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8470 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8471 MapT &Map, unsigned Selector = 0,
8472 SourceRange SrcRange = SourceRange());
8475 /// \brief Return true if the provided declaration \a VD should be captured by
8477 /// \param Level Relative level of nested OpenMP construct for that the check
8479 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8481 /// \brief Check if the specified variable is used in one of the private
8482 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8484 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8485 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8486 ExprObjectKind OK, SourceLocation Loc);
8488 /// \brief Check if the specified variable is used in 'private' clause.
8489 /// \param Level Relative level of nested OpenMP construct for that the check
8491 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8493 /// \brief Check if the specified variable is captured by 'target' directive.
8494 /// \param Level Relative level of nested OpenMP construct for that the check
8496 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8498 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8500 /// \brief Called on start of new data sharing attribute block.
8501 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8502 const DeclarationNameInfo &DirName, Scope *CurScope,
8503 SourceLocation Loc);
8504 /// \brief Start analysis of clauses.
8505 void StartOpenMPClause(OpenMPClauseKind K);
8506 /// \brief End analysis of clauses.
8507 void EndOpenMPClause();
8508 /// \brief Called on end of data sharing attribute block.
8509 void EndOpenMPDSABlock(Stmt *CurDirective);
8511 /// \brief Check if the current region is an OpenMP loop region and if it is,
8512 /// mark loop control variable, used in \p Init for loop initialization, as
8513 /// private by default.
8514 /// \param Init First part of the for loop.
8515 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8517 // OpenMP directives and clauses.
8518 /// \brief Called on correct id-expression from the '#pragma omp
8520 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8521 CXXScopeSpec &ScopeSpec,
8522 const DeclarationNameInfo &Id);
8523 /// \brief Called on well-formed '#pragma omp threadprivate'.
8524 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8526 ArrayRef<Expr *> VarList);
8527 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8528 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8530 ArrayRef<Expr *> VarList);
8531 /// \brief Check if the specified type is allowed to be used in 'omp declare
8532 /// reduction' construct.
8533 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8534 TypeResult ParsedType);
8535 /// \brief Called on start of '#pragma omp declare reduction'.
8536 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8537 Scope *S, DeclContext *DC, DeclarationName Name,
8538 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8539 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8540 /// \brief Initialize declare reduction construct initializer.
8541 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8542 /// \brief Finish current declare reduction construct initializer.
8543 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8544 /// \brief Initialize declare reduction construct initializer.
8545 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8546 /// \brief Finish current declare reduction construct initializer.
8547 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8548 /// \brief Called at the end of '#pragma omp declare reduction'.
8549 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8550 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8552 /// Called on the start of target region i.e. '#pragma omp declare target'.
8553 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8554 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8555 void ActOnFinishOpenMPDeclareTargetDirective();
8556 /// Called on correct id-expression from the '#pragma omp declare target'.
8557 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8558 const DeclarationNameInfo &Id,
8559 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8560 NamedDeclSetType &SameDirectiveDecls);
8561 /// Check declaration inside target region.
8562 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8563 /// Return true inside OpenMP target region.
8564 bool isInOpenMPDeclareTargetContext() const {
8565 return IsInOpenMPDeclareTargetContext;
8568 /// Return the number of captured regions created for an OpenMP directive.
8569 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8571 /// \brief Initialization of captured region for OpenMP region.
8572 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8573 /// \brief End of OpenMP region.
8575 /// \param S Statement associated with the current OpenMP region.
8576 /// \param Clauses List of clauses for the current OpenMP region.
8578 /// \returns Statement for finished OpenMP region.
8579 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8580 StmtResult ActOnOpenMPExecutableDirective(
8581 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8582 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8583 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8584 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8585 /// of the associated statement.
8586 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8588 SourceLocation StartLoc,
8589 SourceLocation EndLoc);
8590 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8591 /// of the associated statement.
8592 StmtResult ActOnOpenMPSimdDirective(
8593 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8594 SourceLocation EndLoc,
8595 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8596 /// \brief Called on well-formed '\#pragma omp for' after parsing
8597 /// of the associated statement.
8598 StmtResult ActOnOpenMPForDirective(
8599 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8600 SourceLocation EndLoc,
8601 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8602 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8603 /// of the associated statement.
8604 StmtResult ActOnOpenMPForSimdDirective(
8605 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8606 SourceLocation EndLoc,
8607 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8608 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8609 /// of the associated statement.
8610 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8611 Stmt *AStmt, SourceLocation StartLoc,
8612 SourceLocation EndLoc);
8613 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8614 /// associated statement.
8615 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8616 SourceLocation EndLoc);
8617 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8618 /// associated statement.
8619 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8620 Stmt *AStmt, SourceLocation StartLoc,
8621 SourceLocation EndLoc);
8622 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8623 /// associated statement.
8624 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8625 SourceLocation EndLoc);
8626 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8627 /// associated statement.
8628 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8629 ArrayRef<OMPClause *> Clauses,
8630 Stmt *AStmt, SourceLocation StartLoc,
8631 SourceLocation EndLoc);
8632 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8633 /// of the associated statement.
8634 StmtResult ActOnOpenMPParallelForDirective(
8635 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8636 SourceLocation EndLoc,
8637 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8638 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8639 /// parsing of the associated statement.
8640 StmtResult ActOnOpenMPParallelForSimdDirective(
8641 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8642 SourceLocation EndLoc,
8643 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8644 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8645 /// parsing of the associated statement.
8646 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8648 SourceLocation StartLoc,
8649 SourceLocation EndLoc);
8650 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8651 /// associated statement.
8652 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8653 Stmt *AStmt, SourceLocation StartLoc,
8654 SourceLocation EndLoc);
8655 /// \brief Called on well-formed '\#pragma omp taskyield'.
8656 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8657 SourceLocation EndLoc);
8658 /// \brief Called on well-formed '\#pragma omp barrier'.
8659 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8660 SourceLocation EndLoc);
8661 /// \brief Called on well-formed '\#pragma omp taskwait'.
8662 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8663 SourceLocation EndLoc);
8664 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8665 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8666 SourceLocation EndLoc);
8667 /// \brief Called on well-formed '\#pragma omp flush'.
8668 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8669 SourceLocation StartLoc,
8670 SourceLocation EndLoc);
8671 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8672 /// associated statement.
8673 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8674 Stmt *AStmt, SourceLocation StartLoc,
8675 SourceLocation EndLoc);
8676 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8677 /// associated statement.
8678 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8679 Stmt *AStmt, SourceLocation StartLoc,
8680 SourceLocation EndLoc);
8681 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8682 /// associated statement.
8683 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8684 Stmt *AStmt, SourceLocation StartLoc,
8685 SourceLocation EndLoc);
8686 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8687 /// the associated statement.
8688 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8689 Stmt *AStmt, SourceLocation StartLoc,
8690 SourceLocation EndLoc);
8691 /// \brief Called on well-formed '\#pragma omp target enter data' after
8692 /// parsing of the associated statement.
8693 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8694 SourceLocation StartLoc,
8695 SourceLocation EndLoc);
8696 /// \brief Called on well-formed '\#pragma omp target exit data' after
8697 /// parsing of the associated statement.
8698 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8699 SourceLocation StartLoc,
8700 SourceLocation EndLoc);
8701 /// \brief Called on well-formed '\#pragma omp target parallel' after
8702 /// parsing of the associated statement.
8703 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8705 SourceLocation StartLoc,
8706 SourceLocation EndLoc);
8707 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8708 /// parsing of the associated statement.
8709 StmtResult ActOnOpenMPTargetParallelForDirective(
8710 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8711 SourceLocation EndLoc,
8712 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8713 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8714 /// associated statement.
8715 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8716 Stmt *AStmt, SourceLocation StartLoc,
8717 SourceLocation EndLoc);
8718 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8720 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8721 SourceLocation EndLoc,
8722 OpenMPDirectiveKind CancelRegion);
8723 /// \brief Called on well-formed '\#pragma omp cancel'.
8724 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8725 SourceLocation StartLoc,
8726 SourceLocation EndLoc,
8727 OpenMPDirectiveKind CancelRegion);
8728 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8729 /// associated statement.
8730 StmtResult ActOnOpenMPTaskLoopDirective(
8731 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8732 SourceLocation EndLoc,
8733 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8734 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8735 /// the associated statement.
8736 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8737 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8738 SourceLocation EndLoc,
8739 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8740 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8741 /// of the associated statement.
8742 StmtResult ActOnOpenMPDistributeDirective(
8743 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8744 SourceLocation EndLoc,
8745 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8746 /// \brief Called on well-formed '\#pragma omp target update'.
8747 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8748 SourceLocation StartLoc,
8749 SourceLocation EndLoc);
8750 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8751 /// parsing of the associated statement.
8752 StmtResult ActOnOpenMPDistributeParallelForDirective(
8753 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8754 SourceLocation EndLoc,
8755 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8756 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8757 /// after parsing of the associated statement.
8758 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8759 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8760 SourceLocation EndLoc,
8761 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8762 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8763 /// parsing of the associated statement.
8764 StmtResult ActOnOpenMPDistributeSimdDirective(
8765 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8766 SourceLocation EndLoc,
8767 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8768 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8769 /// parsing of the associated statement.
8770 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8771 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8772 SourceLocation EndLoc,
8773 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8774 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8775 /// the associated statement.
8776 StmtResult ActOnOpenMPTargetSimdDirective(
8777 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8778 SourceLocation EndLoc,
8779 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8780 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8781 /// the associated statement.
8782 StmtResult ActOnOpenMPTeamsDistributeDirective(
8783 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8784 SourceLocation EndLoc,
8785 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8786 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8787 /// of the associated statement.
8788 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8789 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8790 SourceLocation EndLoc,
8791 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8792 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8793 /// after parsing of the associated statement.
8794 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8795 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8796 SourceLocation EndLoc,
8797 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8798 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8799 /// after parsing of the associated statement.
8800 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8801 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8802 SourceLocation EndLoc,
8803 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8804 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8805 /// associated statement.
8806 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8808 SourceLocation StartLoc,
8809 SourceLocation EndLoc);
8810 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8811 /// of the associated statement.
8812 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8814 SourceLocation EndLoc,
8815 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8816 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8817 /// after parsing of the associated statement.
8818 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8820 SourceLocation EndLoc,
8821 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8822 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8823 /// simd' after parsing of the associated statement.
8824 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8825 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8826 SourceLocation EndLoc,
8827 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8828 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8829 /// parsing of the associated statement.
8830 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8831 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8832 SourceLocation EndLoc,
8833 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8835 /// Checks correctness of linear modifiers.
8836 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8837 SourceLocation LinLoc);
8838 /// Checks that the specified declaration matches requirements for the linear
8840 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8841 OpenMPLinearClauseKind LinKind, QualType Type);
8843 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8844 /// the associated method/function.
8845 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8846 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8847 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8848 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8849 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8851 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8853 SourceLocation StartLoc,
8854 SourceLocation LParenLoc,
8855 SourceLocation EndLoc);
8856 /// \brief Called on well-formed 'if' clause.
8857 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8858 Expr *Condition, SourceLocation StartLoc,
8859 SourceLocation LParenLoc,
8860 SourceLocation NameModifierLoc,
8861 SourceLocation ColonLoc,
8862 SourceLocation EndLoc);
8863 /// \brief Called on well-formed 'final' clause.
8864 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8865 SourceLocation LParenLoc,
8866 SourceLocation EndLoc);
8867 /// \brief Called on well-formed 'num_threads' clause.
8868 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8869 SourceLocation StartLoc,
8870 SourceLocation LParenLoc,
8871 SourceLocation EndLoc);
8872 /// \brief Called on well-formed 'safelen' clause.
8873 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8874 SourceLocation StartLoc,
8875 SourceLocation LParenLoc,
8876 SourceLocation EndLoc);
8877 /// \brief Called on well-formed 'simdlen' clause.
8878 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8879 SourceLocation LParenLoc,
8880 SourceLocation EndLoc);
8881 /// \brief Called on well-formed 'collapse' clause.
8882 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8883 SourceLocation StartLoc,
8884 SourceLocation LParenLoc,
8885 SourceLocation EndLoc);
8886 /// \brief Called on well-formed 'ordered' clause.
8888 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8889 SourceLocation LParenLoc = SourceLocation(),
8890 Expr *NumForLoops = nullptr);
8891 /// \brief Called on well-formed 'grainsize' clause.
8892 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8893 SourceLocation LParenLoc,
8894 SourceLocation EndLoc);
8895 /// \brief Called on well-formed 'num_tasks' clause.
8896 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8897 SourceLocation LParenLoc,
8898 SourceLocation EndLoc);
8899 /// \brief Called on well-formed 'hint' clause.
8900 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8901 SourceLocation LParenLoc,
8902 SourceLocation EndLoc);
8904 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8906 SourceLocation ArgumentLoc,
8907 SourceLocation StartLoc,
8908 SourceLocation LParenLoc,
8909 SourceLocation EndLoc);
8910 /// \brief Called on well-formed 'default' clause.
8911 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8912 SourceLocation KindLoc,
8913 SourceLocation StartLoc,
8914 SourceLocation LParenLoc,
8915 SourceLocation EndLoc);
8916 /// \brief Called on well-formed 'proc_bind' clause.
8917 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8918 SourceLocation KindLoc,
8919 SourceLocation StartLoc,
8920 SourceLocation LParenLoc,
8921 SourceLocation EndLoc);
8923 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8924 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8925 SourceLocation StartLoc, SourceLocation LParenLoc,
8926 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8927 SourceLocation EndLoc);
8928 /// \brief Called on well-formed 'schedule' clause.
8929 OMPClause *ActOnOpenMPScheduleClause(
8930 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8931 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8932 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8933 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8935 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8936 SourceLocation EndLoc);
8937 /// \brief Called on well-formed 'nowait' clause.
8938 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8939 SourceLocation EndLoc);
8940 /// \brief Called on well-formed 'untied' clause.
8941 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8942 SourceLocation EndLoc);
8943 /// \brief Called on well-formed 'mergeable' clause.
8944 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8945 SourceLocation EndLoc);
8946 /// \brief Called on well-formed 'read' clause.
8947 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8948 SourceLocation EndLoc);
8949 /// \brief Called on well-formed 'write' clause.
8950 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8951 SourceLocation EndLoc);
8952 /// \brief Called on well-formed 'update' clause.
8953 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8954 SourceLocation EndLoc);
8955 /// \brief Called on well-formed 'capture' clause.
8956 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8957 SourceLocation EndLoc);
8958 /// \brief Called on well-formed 'seq_cst' clause.
8959 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8960 SourceLocation EndLoc);
8961 /// \brief Called on well-formed 'threads' clause.
8962 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8963 SourceLocation EndLoc);
8964 /// \brief Called on well-formed 'simd' clause.
8965 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8966 SourceLocation EndLoc);
8967 /// \brief Called on well-formed 'nogroup' clause.
8968 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8969 SourceLocation EndLoc);
8971 OMPClause *ActOnOpenMPVarListClause(
8972 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8973 SourceLocation StartLoc, SourceLocation LParenLoc,
8974 SourceLocation ColonLoc, SourceLocation EndLoc,
8975 CXXScopeSpec &ReductionIdScopeSpec,
8976 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8977 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8978 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8979 SourceLocation DepLinMapLoc);
8980 /// \brief Called on well-formed 'private' clause.
8981 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8982 SourceLocation StartLoc,
8983 SourceLocation LParenLoc,
8984 SourceLocation EndLoc);
8985 /// \brief Called on well-formed 'firstprivate' clause.
8986 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8987 SourceLocation StartLoc,
8988 SourceLocation LParenLoc,
8989 SourceLocation EndLoc);
8990 /// \brief Called on well-formed 'lastprivate' clause.
8991 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8992 SourceLocation StartLoc,
8993 SourceLocation LParenLoc,
8994 SourceLocation EndLoc);
8995 /// \brief Called on well-formed 'shared' clause.
8996 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8997 SourceLocation StartLoc,
8998 SourceLocation LParenLoc,
8999 SourceLocation EndLoc);
9000 /// \brief Called on well-formed 'reduction' clause.
9001 OMPClause *ActOnOpenMPReductionClause(
9002 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9003 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9004 CXXScopeSpec &ReductionIdScopeSpec,
9005 const DeclarationNameInfo &ReductionId,
9006 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9007 /// \brief Called on well-formed 'linear' clause.
9009 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9010 SourceLocation StartLoc, SourceLocation LParenLoc,
9011 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9012 SourceLocation ColonLoc, SourceLocation EndLoc);
9013 /// \brief Called on well-formed 'aligned' clause.
9014 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9016 SourceLocation StartLoc,
9017 SourceLocation LParenLoc,
9018 SourceLocation ColonLoc,
9019 SourceLocation EndLoc);
9020 /// \brief Called on well-formed 'copyin' clause.
9021 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9022 SourceLocation StartLoc,
9023 SourceLocation LParenLoc,
9024 SourceLocation EndLoc);
9025 /// \brief Called on well-formed 'copyprivate' clause.
9026 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9027 SourceLocation StartLoc,
9028 SourceLocation LParenLoc,
9029 SourceLocation EndLoc);
9030 /// \brief Called on well-formed 'flush' pseudo clause.
9031 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9032 SourceLocation StartLoc,
9033 SourceLocation LParenLoc,
9034 SourceLocation EndLoc);
9035 /// \brief Called on well-formed 'depend' clause.
9037 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9038 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9039 SourceLocation StartLoc, SourceLocation LParenLoc,
9040 SourceLocation EndLoc);
9041 /// \brief Called on well-formed 'device' clause.
9042 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9043 SourceLocation LParenLoc,
9044 SourceLocation EndLoc);
9045 /// \brief Called on well-formed 'map' clause.
9047 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9048 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9049 SourceLocation MapLoc, SourceLocation ColonLoc,
9050 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9051 SourceLocation LParenLoc, SourceLocation EndLoc);
9052 /// \brief Called on well-formed 'num_teams' clause.
9053 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9054 SourceLocation LParenLoc,
9055 SourceLocation EndLoc);
9056 /// \brief Called on well-formed 'thread_limit' clause.
9057 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9058 SourceLocation StartLoc,
9059 SourceLocation LParenLoc,
9060 SourceLocation EndLoc);
9061 /// \brief Called on well-formed 'priority' clause.
9062 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9063 SourceLocation LParenLoc,
9064 SourceLocation EndLoc);
9065 /// \brief Called on well-formed 'dist_schedule' clause.
9066 OMPClause *ActOnOpenMPDistScheduleClause(
9067 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9068 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9069 SourceLocation CommaLoc, SourceLocation EndLoc);
9070 /// \brief Called on well-formed 'defaultmap' clause.
9071 OMPClause *ActOnOpenMPDefaultmapClause(
9072 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9073 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9074 SourceLocation KindLoc, SourceLocation EndLoc);
9075 /// \brief Called on well-formed 'to' clause.
9076 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9077 SourceLocation StartLoc,
9078 SourceLocation LParenLoc,
9079 SourceLocation EndLoc);
9080 /// \brief Called on well-formed 'from' clause.
9081 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9082 SourceLocation StartLoc,
9083 SourceLocation LParenLoc,
9084 SourceLocation EndLoc);
9085 /// Called on well-formed 'use_device_ptr' clause.
9086 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9087 SourceLocation StartLoc,
9088 SourceLocation LParenLoc,
9089 SourceLocation EndLoc);
9090 /// Called on well-formed 'is_device_ptr' clause.
9091 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9092 SourceLocation StartLoc,
9093 SourceLocation LParenLoc,
9094 SourceLocation EndLoc);
9096 /// \brief The kind of conversion being performed.
9097 enum CheckedConversionKind {
9098 /// \brief An implicit conversion.
9099 CCK_ImplicitConversion,
9100 /// \brief A C-style cast.
9102 /// \brief A functional-style cast.
9104 /// \brief A cast other than a C-style cast.
9108 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9109 /// cast. If there is already an implicit cast, merge into the existing one.
9110 /// If isLvalue, the result of the cast is an lvalue.
9111 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9112 ExprValueKind VK = VK_RValue,
9113 const CXXCastPath *BasePath = nullptr,
9114 CheckedConversionKind CCK
9115 = CCK_ImplicitConversion);
9117 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9118 /// to the conversion from scalar type ScalarTy to the Boolean type.
9119 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9121 /// IgnoredValueConversions - Given that an expression's result is
9122 /// syntactically ignored, perform any conversions that are
9124 ExprResult IgnoredValueConversions(Expr *E);
9126 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9127 // functions and arrays to their respective pointers (C99 6.3.2.1).
9128 ExprResult UsualUnaryConversions(Expr *E);
9130 /// CallExprUnaryConversions - a special case of an unary conversion
9131 /// performed on a function designator of a call expression.
9132 ExprResult CallExprUnaryConversions(Expr *E);
9134 // DefaultFunctionArrayConversion - converts functions and arrays
9135 // to their respective pointers (C99 6.3.2.1).
9136 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9138 // DefaultFunctionArrayLvalueConversion - converts functions and
9139 // arrays to their respective pointers and performs the
9140 // lvalue-to-rvalue conversion.
9141 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9142 bool Diagnose = true);
9144 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9145 // the operand. This is DefaultFunctionArrayLvalueConversion,
9146 // except that it assumes the operand isn't of function or array
9148 ExprResult DefaultLvalueConversion(Expr *E);
9150 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9151 // do not have a prototype. Integer promotions are performed on each
9152 // argument, and arguments that have type float are promoted to double.
9153 ExprResult DefaultArgumentPromotion(Expr *E);
9155 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9156 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9157 /// we don't have xvalues there.
9158 ExprResult TemporaryMaterializationConversion(Expr *E);
9160 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9161 enum VariadicCallType {
9165 VariadicConstructor,
9166 VariadicDoesNotApply
9169 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9170 const FunctionProtoType *Proto,
9173 // Used for determining in which context a type is allowed to be passed to a
9183 // Determines which VarArgKind fits an expression.
9184 VarArgKind isValidVarArgType(const QualType &Ty);
9186 /// Check to see if the given expression is a valid argument to a variadic
9187 /// function, issuing a diagnostic if not.
9188 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9190 /// Check to see if a given expression could have '.c_str()' called on it.
9191 bool hasCStrMethod(const Expr *E);
9193 /// GatherArgumentsForCall - Collector argument expressions for various
9194 /// form of call prototypes.
9195 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9196 const FunctionProtoType *Proto,
9197 unsigned FirstParam, ArrayRef<Expr *> Args,
9198 SmallVectorImpl<Expr *> &AllArgs,
9199 VariadicCallType CallType = VariadicDoesNotApply,
9200 bool AllowExplicit = false,
9201 bool IsListInitialization = false);
9203 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9204 // will create a runtime trap if the resulting type is not a POD type.
9205 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9206 FunctionDecl *FDecl);
9208 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9209 // operands and then handles various conversions that are common to binary
9210 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9211 // routine returns the first non-arithmetic type found. The client is
9212 // responsible for emitting appropriate error diagnostics.
9213 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9214 bool IsCompAssign = false);
9216 /// AssignConvertType - All of the 'assignment' semantic checks return this
9217 /// enum to indicate whether the assignment was allowed. These checks are
9218 /// done for simple assignments, as well as initialization, return from
9219 /// function, argument passing, etc. The query is phrased in terms of a
9220 /// source and destination type.
9221 enum AssignConvertType {
9222 /// Compatible - the types are compatible according to the standard.
9225 /// PointerToInt - The assignment converts a pointer to an int, which we
9226 /// accept as an extension.
9229 /// IntToPointer - The assignment converts an int to a pointer, which we
9230 /// accept as an extension.
9233 /// FunctionVoidPointer - The assignment is between a function pointer and
9234 /// void*, which the standard doesn't allow, but we accept as an extension.
9235 FunctionVoidPointer,
9237 /// IncompatiblePointer - The assignment is between two pointers types that
9238 /// are not compatible, but we accept them as an extension.
9239 IncompatiblePointer,
9241 /// IncompatiblePointerSign - The assignment is between two pointers types
9242 /// which point to integers which have a different sign, but are otherwise
9243 /// identical. This is a subset of the above, but broken out because it's by
9244 /// far the most common case of incompatible pointers.
9245 IncompatiblePointerSign,
9247 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9248 /// c/v/r qualifiers, which we accept as an extension.
9249 CompatiblePointerDiscardsQualifiers,
9251 /// IncompatiblePointerDiscardsQualifiers - The assignment
9252 /// discards qualifiers that we don't permit to be discarded,
9253 /// like address spaces.
9254 IncompatiblePointerDiscardsQualifiers,
9256 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9257 /// nested pointer types, and the qualifiers other than the first two
9258 /// levels differ e.g. char ** -> const char **, but we accept them as an
9260 IncompatibleNestedPointerQualifiers,
9262 /// IncompatibleVectors - The assignment is between two vector types that
9263 /// have the same size, which we accept as an extension.
9264 IncompatibleVectors,
9266 /// IntToBlockPointer - The assignment converts an int to a block
9267 /// pointer. We disallow this.
9270 /// IncompatibleBlockPointer - The assignment is between two block
9271 /// pointers types that are not compatible.
9272 IncompatibleBlockPointer,
9274 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9275 /// id type and something else (that is incompatible with it). For example,
9276 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9277 IncompatibleObjCQualifiedId,
9279 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9280 /// object with __weak qualifier.
9281 IncompatibleObjCWeakRef,
9283 /// Incompatible - We reject this conversion outright, it is invalid to
9284 /// represent it in the AST.
9288 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9289 /// assignment conversion type specified by ConvTy. This returns true if the
9290 /// conversion was invalid or false if the conversion was accepted.
9291 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9293 QualType DstType, QualType SrcType,
9294 Expr *SrcExpr, AssignmentAction Action,
9295 bool *Complained = nullptr);
9297 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9298 /// enum. If AllowMask is true, then we also allow the complement of a valid
9299 /// value, to be used as a mask.
9300 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9301 bool AllowMask) const;
9303 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9304 /// integer not in the range of enum values.
9305 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9308 /// CheckAssignmentConstraints - Perform type checking for assignment,
9309 /// argument passing, variable initialization, and function return values.
9311 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9315 /// Check assignment constraints and optionally prepare for a conversion of
9316 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9318 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9321 bool ConvertRHS = true);
9323 /// Check assignment constraints for an assignment of RHS to LHSType.
9325 /// \param LHSType The destination type for the assignment.
9326 /// \param RHS The source expression for the assignment.
9327 /// \param Diagnose If \c true, diagnostics may be produced when checking
9328 /// for assignability. If a diagnostic is produced, \p RHS will be
9329 /// set to ExprError(). Note that this function may still return
9330 /// without producing a diagnostic, even for an invalid assignment.
9331 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9332 /// in an audited Core Foundation API and does not need to be checked
9333 /// for ARC retain issues.
9334 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9335 /// conversions necessary to perform the assignment. If \c false,
9336 /// \p Diagnose must also be \c false.
9337 AssignConvertType CheckSingleAssignmentConstraints(
9338 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9339 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9341 // \brief If the lhs type is a transparent union, check whether we
9342 // can initialize the transparent union with the given expression.
9343 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9346 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9348 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9350 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9351 AssignmentAction Action,
9352 bool AllowExplicit = false);
9353 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9354 AssignmentAction Action,
9356 ImplicitConversionSequence& ICS);
9357 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9358 const ImplicitConversionSequence& ICS,
9359 AssignmentAction Action,
9360 CheckedConversionKind CCK
9361 = CCK_ImplicitConversion);
9362 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9363 const StandardConversionSequence& SCS,
9364 AssignmentAction Action,
9365 CheckedConversionKind CCK);
9367 /// the following "Check" methods will return a valid/converted QualType
9368 /// or a null QualType (indicating an error diagnostic was issued).
9370 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9371 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9373 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9375 QualType CheckPointerToMemberOperands( // C++ 5.5
9376 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9377 SourceLocation OpLoc, bool isIndirect);
9378 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9379 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9381 QualType CheckRemainderOperands( // C99 6.5.5
9382 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9383 bool IsCompAssign = false);
9384 QualType CheckAdditionOperands( // C99 6.5.6
9385 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9386 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9387 QualType CheckSubtractionOperands( // C99 6.5.6
9388 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9389 QualType* CompLHSTy = nullptr);
9390 QualType CheckShiftOperands( // C99 6.5.7
9391 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9392 BinaryOperatorKind Opc, bool IsCompAssign = false);
9393 QualType CheckCompareOperands( // C99 6.5.8/9
9394 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9395 BinaryOperatorKind Opc, bool isRelational);
9396 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9397 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9398 BinaryOperatorKind Opc);
9399 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9400 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9401 BinaryOperatorKind Opc);
9402 // CheckAssignmentOperands is used for both simple and compound assignment.
9403 // For simple assignment, pass both expressions and a null converted type.
9404 // For compound assignment, pass both expressions and the converted type.
9405 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9406 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9408 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9409 UnaryOperatorKind Opcode, Expr *Op);
9410 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9411 BinaryOperatorKind Opcode,
9412 Expr *LHS, Expr *RHS);
9413 ExprResult checkPseudoObjectRValue(Expr *E);
9414 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9416 QualType CheckConditionalOperands( // C99 6.5.15
9417 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9418 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9419 QualType CXXCheckConditionalOperands( // C++ 5.16
9420 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9421 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9422 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9423 bool ConvertArgs = true);
9424 QualType FindCompositePointerType(SourceLocation Loc,
9425 ExprResult &E1, ExprResult &E2,
9426 bool ConvertArgs = true) {
9427 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9428 QualType Composite =
9429 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9435 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9436 SourceLocation QuestionLoc);
9438 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9439 SourceLocation QuestionLoc);
9441 void DiagnoseAlwaysNonNullPointer(Expr *E,
9442 Expr::NullPointerConstantKind NullType,
9443 bool IsEqual, SourceRange Range);
9445 /// type checking for vector binary operators.
9446 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9447 SourceLocation Loc, bool IsCompAssign,
9448 bool AllowBothBool, bool AllowBoolConversion);
9449 QualType GetSignedVectorType(QualType V);
9450 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9451 SourceLocation Loc, bool isRelational);
9452 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9453 SourceLocation Loc);
9455 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9456 bool isLaxVectorConversion(QualType srcType, QualType destType);
9458 /// type checking declaration initializers (C99 6.7.8)
9459 bool CheckForConstantInitializer(Expr *e, QualType t);
9461 // type checking C++ declaration initializers (C++ [dcl.init]).
9463 /// ReferenceCompareResult - Expresses the result of comparing two
9464 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9465 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9466 enum ReferenceCompareResult {
9467 /// Ref_Incompatible - The two types are incompatible, so direct
9468 /// reference binding is not possible.
9469 Ref_Incompatible = 0,
9470 /// Ref_Related - The two types are reference-related, which means
9471 /// that their unqualified forms (T1 and T2) are either the same
9472 /// or T1 is a base class of T2.
9474 /// Ref_Compatible - The two types are reference-compatible.
9478 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9479 QualType T1, QualType T2,
9480 bool &DerivedToBase,
9481 bool &ObjCConversion,
9482 bool &ObjCLifetimeConversion);
9484 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9485 Expr *CastExpr, CastKind &CastKind,
9486 ExprValueKind &VK, CXXCastPath &Path);
9488 /// \brief Force an expression with unknown-type to an expression of the
9490 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9492 /// \brief Type-check an expression that's being passed to an
9493 /// __unknown_anytype parameter.
9494 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9495 Expr *result, QualType ¶mType);
9497 // CheckVectorCast - check type constraints for vectors.
9498 // Since vectors are an extension, there are no C standard reference for this.
9499 // We allow casting between vectors and integer datatypes of the same size.
9500 // returns true if the cast is invalid
9501 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9504 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9505 /// implicit casts if necessary.
9506 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9508 // CheckExtVectorCast - check type constraints for extended vectors.
9509 // Since vectors are an extension, there are no C standard reference for this.
9510 // We allow casting between vectors and integer datatypes of the same size,
9511 // or vectors and the element type of that vector.
9512 // returns the cast expr
9513 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9516 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9517 SourceLocation LParenLoc,
9519 SourceLocation RParenLoc);
9521 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9523 /// \brief Checks for invalid conversions and casts between
9524 /// retainable pointers and other pointer kinds for ARC and Weak.
9525 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9526 QualType castType, Expr *&op,
9527 CheckedConversionKind CCK,
9528 bool Diagnose = true,
9529 bool DiagnoseCFAudited = false,
9530 BinaryOperatorKind Opc = BO_PtrMemD
9533 Expr *stripARCUnbridgedCast(Expr *e);
9534 void diagnoseARCUnbridgedCast(Expr *e);
9536 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9539 /// checkRetainCycles - Check whether an Objective-C message send
9540 /// might create an obvious retain cycle.
9541 void checkRetainCycles(ObjCMessageExpr *msg);
9542 void checkRetainCycles(Expr *receiver, Expr *argument);
9543 void checkRetainCycles(VarDecl *Var, Expr *Init);
9545 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9546 /// to weak/__unsafe_unretained type.
9547 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9549 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9550 /// to weak/__unsafe_unretained expression.
9551 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9553 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9554 /// \param Method - May be null.
9555 /// \param [out] ReturnType - The return type of the send.
9556 /// \return true iff there were any incompatible types.
9557 bool CheckMessageArgumentTypes(QualType ReceiverType,
9558 MultiExprArg Args, Selector Sel,
9559 ArrayRef<SourceLocation> SelectorLocs,
9560 ObjCMethodDecl *Method, bool isClassMessage,
9561 bool isSuperMessage,
9562 SourceLocation lbrac, SourceLocation rbrac,
9563 SourceRange RecRange,
9564 QualType &ReturnType, ExprValueKind &VK);
9566 /// \brief Determine the result of a message send expression based on
9567 /// the type of the receiver, the method expected to receive the message,
9568 /// and the form of the message send.
9569 QualType getMessageSendResultType(QualType ReceiverType,
9570 ObjCMethodDecl *Method,
9571 bool isClassMessage, bool isSuperMessage);
9573 /// \brief If the given expression involves a message send to a method
9574 /// with a related result type, emit a note describing what happened.
9575 void EmitRelatedResultTypeNote(const Expr *E);
9577 /// \brief Given that we had incompatible pointer types in a return
9578 /// statement, check whether we're in a method with a related result
9579 /// type, and if so, emit a note describing what happened.
9580 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9582 class ConditionResult {
9584 FullExprArg Condition;
9590 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9592 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9593 HasKnownValue(IsConstexpr && Condition.get() &&
9594 !Condition.get()->isValueDependent()),
9595 KnownValue(HasKnownValue &&
9596 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9597 explicit ConditionResult(bool Invalid)
9598 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9599 HasKnownValue(false), KnownValue(false) {}
9602 ConditionResult() : ConditionResult(false) {}
9603 bool isInvalid() const { return Invalid; }
9604 std::pair<VarDecl *, Expr *> get() const {
9605 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9608 llvm::Optional<bool> getKnownValue() const {
9614 static ConditionResult ConditionError() { return ConditionResult(true); }
9616 enum class ConditionKind {
9617 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9618 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9619 Switch ///< An integral condition for a 'switch' statement.
9622 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9623 Expr *SubExpr, ConditionKind CK);
9625 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9626 SourceLocation StmtLoc,
9629 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9631 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9632 SourceLocation StmtLoc,
9634 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9636 /// CheckBooleanCondition - Diagnose problems involving the use of
9637 /// the given expression as a boolean condition (e.g. in an if
9638 /// statement). Also performs the standard function and array
9639 /// decays, possibly changing the input variable.
9641 /// \param Loc - A location associated with the condition, e.g. the
9643 /// \return true iff there were any errors
9644 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9645 bool IsConstexpr = false);
9647 /// DiagnoseAssignmentAsCondition - Given that an expression is
9648 /// being used as a boolean condition, warn if it's an assignment.
9649 void DiagnoseAssignmentAsCondition(Expr *E);
9651 /// \brief Redundant parentheses over an equality comparison can indicate
9652 /// that the user intended an assignment used as condition.
9653 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9655 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9656 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9658 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9659 /// the specified width and sign. If an overflow occurs, detect it and emit
9660 /// the specified diagnostic.
9661 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9662 unsigned NewWidth, bool NewSign,
9663 SourceLocation Loc, unsigned DiagID);
9665 /// Checks that the Objective-C declaration is declared in the global scope.
9666 /// Emits an error and marks the declaration as invalid if it's not declared
9667 /// in the global scope.
9668 bool CheckObjCDeclScope(Decl *D);
9670 /// \brief Abstract base class used for diagnosing integer constant
9671 /// expression violations.
9672 class VerifyICEDiagnoser {
9676 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9678 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9679 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9680 virtual ~VerifyICEDiagnoser() { }
9683 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9684 /// and reports the appropriate diagnostics. Returns false on success.
9685 /// Can optionally return the value of the expression.
9686 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9687 VerifyICEDiagnoser &Diagnoser,
9688 bool AllowFold = true);
9689 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9691 bool AllowFold = true);
9692 ExprResult VerifyIntegerConstantExpression(Expr *E,
9693 llvm::APSInt *Result = nullptr);
9695 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9696 /// the correct width, and that the field type is valid.
9697 /// Returns false on success.
9698 /// Can optionally return whether the bit-field is of width 0
9699 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9700 QualType FieldTy, bool IsMsStruct,
9701 Expr *BitWidth, bool *ZeroWidth = nullptr);
9704 unsigned ForceCUDAHostDeviceDepth = 0;
9707 /// Increments our count of the number of times we've seen a pragma forcing
9708 /// functions to be __host__ __device__. So long as this count is greater
9709 /// than zero, all functions encountered will be __host__ __device__.
9710 void PushForceCUDAHostDevice();
9712 /// Decrements our count of the number of times we've seen a pragma forcing
9713 /// functions to be __host__ __device__. Returns false if the count is 0
9714 /// before incrementing, so you can emit an error.
9715 bool PopForceCUDAHostDevice();
9717 /// Diagnostics that are emitted only if we discover that the given function
9718 /// must be codegen'ed. Because handling these correctly adds overhead to
9719 /// compilation, this is currently only enabled for CUDA compilations.
9720 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9721 std::vector<PartialDiagnosticAt>>
9724 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9725 /// key in a hashtable, both the FD and location are hashed.
9726 struct FunctionDeclAndLoc {
9727 CanonicalDeclPtr<FunctionDecl> FD;
9731 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9732 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9733 /// same deferred diag twice.
9734 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9736 /// An inverse call graph, mapping known-emitted functions to one of their
9737 /// known-emitted callers (plus the location of the call).
9739 /// Functions that we can tell a priori must be emitted aren't added to this
9741 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9742 /* Caller = */ FunctionDeclAndLoc>
9743 CUDAKnownEmittedFns;
9745 /// A partial call graph maintained during CUDA compilation to support
9746 /// deferred diagnostics.
9748 /// Functions are only added here if, at the time they're considered, they are
9749 /// not known-emitted. As soon as we discover that a function is
9750 /// known-emitted, we remove it and everything it transitively calls from this
9751 /// set and add those functions to CUDAKnownEmittedFns.
9752 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9753 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9757 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9759 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9760 /// which are not allowed to appear inside __device__ functions and are
9761 /// allowed to appear in __host__ __device__ functions only if the host+device
9762 /// function is never codegen'ed.
9764 /// To handle this, we use the notion of "deferred diagnostics", where we
9765 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9767 /// This class lets you emit either a regular diagnostic, a deferred
9768 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9769 /// its constructor, thus simplifying the process of creating these "maybe
9770 /// deferred" diagnostics.
9771 class CUDADiagBuilder {
9774 /// Emit no diagnostics.
9776 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9778 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9779 /// emit a call stack showing how this function can be reached by an a
9780 /// priori known-emitted function.
9781 K_ImmediateWithCallStack,
9782 /// Create a deferred diagnostic, which is emitted only if the function
9783 /// it's attached to is codegen'ed. Also emit a call stack as with
9784 /// K_ImmediateWithCallStack.
9788 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9789 FunctionDecl *Fn, Sema &S);
9792 /// Convertible to bool: True if we immediately emitted an error, false if
9793 /// we didn't emit an error or we created a deferred error.
9797 /// if (CUDADiagBuilder(...) << foo << bar)
9798 /// return ExprError();
9800 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9801 /// want to use these instead of creating a CUDADiagBuilder yourself.
9802 operator bool() const { return ImmediateDiag.hasValue(); }
9804 template <typename T>
9805 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9807 if (Diag.ImmediateDiag.hasValue())
9808 *Diag.ImmediateDiag << Value;
9809 else if (Diag.PartialDiag.hasValue())
9810 *Diag.PartialDiag << Value;
9821 // Invariant: At most one of these Optionals has a value.
9822 // FIXME: Switch these to a Variant once that exists.
9823 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9824 llvm::Optional<PartialDiagnostic> PartialDiag;
9827 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9828 /// is "used as device code".
9830 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9831 /// - If CurContext is a __device__ or __global__ function, emits the
9832 /// diagnostics immediately.
9833 /// - If CurContext is a __host__ __device__ function and we are compiling for
9834 /// the device, creates a diagnostic which is emitted if and when we realize
9835 /// that the function will be codegen'ed.
9839 /// // Variable-length arrays are not allowed in CUDA device code.
9840 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9841 /// return ExprError();
9842 /// // Otherwise, continue parsing as normal.
9843 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9845 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9846 /// is "used as host code".
9848 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9849 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9851 enum CUDAFunctionTarget {
9859 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9862 /// Use this rather than examining the function's attributes yourself -- you
9863 /// will get it wrong. Returns CFT_Host if D is null.
9864 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9865 bool IgnoreImplicitHDAttr = false);
9866 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9868 /// Gets the CUDA target for the current context.
9869 CUDAFunctionTarget CurrentCUDATarget() {
9870 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9873 // CUDA function call preference. Must be ordered numerically from
9875 enum CUDAFunctionPreference {
9876 CFP_Never, // Invalid caller/callee combination.
9877 CFP_WrongSide, // Calls from host-device to host or device
9878 // function that do not match current compilation
9880 CFP_HostDevice, // Any calls to host/device functions.
9881 CFP_SameSide, // Calls from host-device to host or device
9882 // function matching current compilation mode.
9883 CFP_Native, // host-to-host or device-to-device calls.
9886 /// Identifies relative preference of a given Caller/Callee
9887 /// combination, based on their host/device attributes.
9888 /// \param Caller function which needs address of \p Callee.
9889 /// nullptr in case of global context.
9890 /// \param Callee target function
9892 /// \returns preference value for particular Caller/Callee combination.
9893 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9894 const FunctionDecl *Callee);
9896 /// Determines whether Caller may invoke Callee, based on their CUDA
9897 /// host/device attributes. Returns false if the call is not allowed.
9899 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9900 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9901 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9902 const FunctionDecl *Callee) {
9903 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9906 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9907 /// depending on FD and the current compilation settings.
9908 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9909 const LookupResult &Previous);
9912 /// Check whether we're allowed to call Callee from the current context.
9914 /// - If the call is never allowed in a semantically-correct program
9915 /// (CFP_Never), emits an error and returns false.
9917 /// - If the call is allowed in semantically-correct programs, but only if
9918 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9919 /// be emitted if and when the caller is codegen'ed, and returns true.
9921 /// Will only create deferred diagnostics for a given SourceLocation once,
9922 /// so you can safely call this multiple times without generating duplicate
9923 /// deferred errors.
9925 /// - Otherwise, returns true without emitting any diagnostics.
9926 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9928 /// Set __device__ or __host__ __device__ attributes on the given lambda
9929 /// operator() method.
9931 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9932 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9933 /// functions become __host__ __device__ themselves.
9934 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9936 /// Finds a function in \p Matches with highest calling priority
9937 /// from \p Caller context and erases all functions with lower
9938 /// calling priority.
9939 void EraseUnwantedCUDAMatches(
9940 const FunctionDecl *Caller,
9941 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9943 /// Given a implicit special member, infer its CUDA target from the
9944 /// calls it needs to make to underlying base/field special members.
9945 /// \param ClassDecl the class for which the member is being created.
9946 /// \param CSM the kind of special member.
9947 /// \param MemberDecl the special member itself.
9948 /// \param ConstRHS true if this is a copy operation with a const object on
9950 /// \param Diagnose true if this call should emit diagnostics.
9951 /// \return true if there was an error inferring.
9952 /// The result of this call is implicit CUDA target attribute(s) attached to
9953 /// the member declaration.
9954 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9955 CXXSpecialMember CSM,
9956 CXXMethodDecl *MemberDecl,
9960 /// \return true if \p CD can be considered empty according to CUDA
9961 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9962 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9963 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9965 /// Check whether NewFD is a valid overload for CUDA. Emits
9966 /// diagnostics and invalidates NewFD if not.
9967 void checkCUDATargetOverload(FunctionDecl *NewFD,
9968 const LookupResult &Previous);
9969 /// Copies target attributes from the template TD to the function FD.
9970 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9972 /// \name Code completion
9974 /// \brief Describes the context in which code completion occurs.
9975 enum ParserCompletionContext {
9976 /// \brief Code completion occurs at top-level or namespace context.
9978 /// \brief Code completion occurs within a class, struct, or union.
9980 /// \brief Code completion occurs within an Objective-C interface, protocol,
9983 /// \brief Code completion occurs within an Objective-C implementation or
9984 /// category implementation
9985 PCC_ObjCImplementation,
9986 /// \brief Code completion occurs within the list of instance variables
9987 /// in an Objective-C interface, protocol, category, or implementation.
9988 PCC_ObjCInstanceVariableList,
9989 /// \brief Code completion occurs following one or more template
9992 /// \brief Code completion occurs following one or more template
9993 /// headers within a class.
9995 /// \brief Code completion occurs within an expression.
9997 /// \brief Code completion occurs within a statement, which may
9998 /// also be an expression or a declaration.
10000 /// \brief Code completion occurs at the beginning of the
10001 /// initialization statement (or expression) in a for loop.
10003 /// \brief Code completion occurs within the condition of an if,
10004 /// while, switch, or for statement.
10006 /// \brief Code completion occurs within the body of a function on a
10007 /// recovery path, where we do not have a specific handle on our position
10008 /// in the grammar.
10009 PCC_RecoveryInFunction,
10010 /// \brief Code completion occurs where only a type is permitted.
10012 /// \brief Code completion occurs in a parenthesized expression, which
10013 /// might also be a type cast.
10014 PCC_ParenthesizedExpression,
10015 /// \brief Code completion occurs within a sequence of declaration
10016 /// specifiers within a function, method, or block.
10017 PCC_LocalDeclarationSpecifiers
10020 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10021 void CodeCompleteOrdinaryName(Scope *S,
10022 ParserCompletionContext CompletionContext);
10023 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10024 bool AllowNonIdentifiers,
10025 bool AllowNestedNameSpecifiers);
10027 struct CodeCompleteExpressionData;
10028 void CodeCompleteExpression(Scope *S,
10029 const CodeCompleteExpressionData &Data);
10030 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10031 SourceLocation OpLoc, bool IsArrow,
10032 bool IsBaseExprStatement);
10033 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10034 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10035 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10036 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10037 const VirtSpecifiers *VS = nullptr);
10038 void CodeCompleteBracketDeclarator(Scope *S);
10039 void CodeCompleteCase(Scope *S);
10040 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10041 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10042 ArrayRef<Expr *> Args);
10043 void CodeCompleteInitializer(Scope *S, Decl *D);
10044 void CodeCompleteReturn(Scope *S);
10045 void CodeCompleteAfterIf(Scope *S);
10046 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10048 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10049 bool EnteringContext);
10050 void CodeCompleteUsing(Scope *S);
10051 void CodeCompleteUsingDirective(Scope *S);
10052 void CodeCompleteNamespaceDecl(Scope *S);
10053 void CodeCompleteNamespaceAliasDecl(Scope *S);
10054 void CodeCompleteOperatorName(Scope *S);
10055 void CodeCompleteConstructorInitializer(
10057 ArrayRef<CXXCtorInitializer *> Initializers);
10059 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10060 bool AfterAmpersand);
10062 void CodeCompleteObjCAtDirective(Scope *S);
10063 void CodeCompleteObjCAtVisibility(Scope *S);
10064 void CodeCompleteObjCAtStatement(Scope *S);
10065 void CodeCompleteObjCAtExpression(Scope *S);
10066 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10067 void CodeCompleteObjCPropertyGetter(Scope *S);
10068 void CodeCompleteObjCPropertySetter(Scope *S);
10069 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10071 void CodeCompleteObjCMessageReceiver(Scope *S);
10072 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10073 ArrayRef<IdentifierInfo *> SelIdents,
10074 bool AtArgumentExpression);
10075 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10076 ArrayRef<IdentifierInfo *> SelIdents,
10077 bool AtArgumentExpression,
10078 bool IsSuper = false);
10079 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10080 ArrayRef<IdentifierInfo *> SelIdents,
10081 bool AtArgumentExpression,
10082 ObjCInterfaceDecl *Super = nullptr);
10083 void CodeCompleteObjCForCollection(Scope *S,
10084 DeclGroupPtrTy IterationVar);
10085 void CodeCompleteObjCSelector(Scope *S,
10086 ArrayRef<IdentifierInfo *> SelIdents);
10087 void CodeCompleteObjCProtocolReferences(
10088 ArrayRef<IdentifierLocPair> Protocols);
10089 void CodeCompleteObjCProtocolDecl(Scope *S);
10090 void CodeCompleteObjCInterfaceDecl(Scope *S);
10091 void CodeCompleteObjCSuperclass(Scope *S,
10092 IdentifierInfo *ClassName,
10093 SourceLocation ClassNameLoc);
10094 void CodeCompleteObjCImplementationDecl(Scope *S);
10095 void CodeCompleteObjCInterfaceCategory(Scope *S,
10096 IdentifierInfo *ClassName,
10097 SourceLocation ClassNameLoc);
10098 void CodeCompleteObjCImplementationCategory(Scope *S,
10099 IdentifierInfo *ClassName,
10100 SourceLocation ClassNameLoc);
10101 void CodeCompleteObjCPropertyDefinition(Scope *S);
10102 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10103 IdentifierInfo *PropertyName);
10104 void CodeCompleteObjCMethodDecl(Scope *S,
10105 bool IsInstanceMethod,
10106 ParsedType ReturnType);
10107 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10108 bool IsInstanceMethod,
10109 bool AtParameterName,
10110 ParsedType ReturnType,
10111 ArrayRef<IdentifierInfo *> SelIdents);
10112 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10113 SourceLocation ClassNameLoc,
10114 bool IsBaseExprStatement);
10115 void CodeCompletePreprocessorDirective(bool InConditional);
10116 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10117 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10118 void CodeCompletePreprocessorExpression();
10119 void CodeCompletePreprocessorMacroArgument(Scope *S,
10120 IdentifierInfo *Macro,
10121 MacroInfo *MacroInfo,
10122 unsigned Argument);
10123 void CodeCompleteNaturalLanguage();
10124 void CodeCompleteAvailabilityPlatformName();
10125 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10126 CodeCompletionTUInfo &CCTUInfo,
10127 SmallVectorImpl<CodeCompletionResult> &Results);
10130 //===--------------------------------------------------------------------===//
10131 // Extra semantic analysis beyond the C type system
10134 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10135 unsigned ByteNo) const;
10138 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10139 const ArraySubscriptExpr *ASE=nullptr,
10140 bool AllowOnePastEnd=true, bool IndexNegated=false);
10141 void CheckArrayAccess(const Expr *E);
10142 // Used to grab the relevant information from a FormatAttr and a
10143 // FunctionDeclaration.
10144 struct FormatStringInfo {
10145 unsigned FormatIdx;
10146 unsigned FirstDataArg;
10150 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10151 FormatStringInfo *FSI);
10152 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10153 const FunctionProtoType *Proto);
10154 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10155 ArrayRef<const Expr *> Args);
10156 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10157 const FunctionProtoType *Proto);
10158 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10159 void CheckConstructorCall(FunctionDecl *FDecl,
10160 ArrayRef<const Expr *> Args,
10161 const FunctionProtoType *Proto,
10162 SourceLocation Loc);
10164 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10165 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10166 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10167 VariadicCallType CallType);
10169 bool CheckObjCString(Expr *Arg);
10170 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10172 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10173 unsigned BuiltinID, CallExpr *TheCall);
10175 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10176 unsigned MaxWidth);
10177 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10178 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10180 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10181 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10182 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10183 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10184 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10185 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10186 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10188 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10189 bool SemaBuiltinVAStartARM(CallExpr *Call);
10190 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10191 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10192 bool SemaBuiltinVSX(CallExpr *TheCall);
10193 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10196 // Used by C++ template instantiation.
10197 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10198 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10199 SourceLocation BuiltinLoc,
10200 SourceLocation RParenLoc);
10203 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10204 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10205 bool SemaBuiltinAssume(CallExpr *TheCall);
10206 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10207 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10208 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10209 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10210 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10211 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10212 AtomicExpr::AtomicOp Op);
10213 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10214 llvm::APSInt &Result);
10215 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10216 int Low, int High);
10217 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10218 unsigned Multiple);
10219 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10220 int ArgNum, unsigned ExpectedFieldNum,
10223 enum FormatStringType {
10230 FST_FreeBSDKPrintf,
10235 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10237 bool FormatStringHasSArg(const StringLiteral *FExpr);
10239 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10242 bool CheckFormatArguments(const FormatAttr *Format,
10243 ArrayRef<const Expr *> Args,
10245 VariadicCallType CallType,
10246 SourceLocation Loc, SourceRange Range,
10247 llvm::SmallBitVector &CheckedVarArgs);
10248 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10249 bool HasVAListArg, unsigned format_idx,
10250 unsigned firstDataArg, FormatStringType Type,
10251 VariadicCallType CallType,
10252 SourceLocation Loc, SourceRange range,
10253 llvm::SmallBitVector &CheckedVarArgs);
10255 void CheckAbsoluteValueFunction(const CallExpr *Call,
10256 const FunctionDecl *FDecl);
10258 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10260 void CheckMemaccessArguments(const CallExpr *Call,
10262 IdentifierInfo *FnName);
10264 void CheckStrlcpycatArguments(const CallExpr *Call,
10265 IdentifierInfo *FnName);
10267 void CheckStrncatArguments(const CallExpr *Call,
10268 IdentifierInfo *FnName);
10270 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10271 SourceLocation ReturnLoc,
10272 bool isObjCMethod = false,
10273 const AttrVec *Attrs = nullptr,
10274 const FunctionDecl *FD = nullptr);
10276 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10277 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10278 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10279 void CheckForIntOverflow(Expr *E);
10280 void CheckUnsequencedOperations(Expr *E);
10282 /// \brief Perform semantic checks on a completed expression. This will either
10283 /// be a full-expression or a default argument expression.
10284 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10285 bool IsConstexpr = false);
10287 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10290 /// Check if there is a field shadowing.
10291 void CheckShadowInheritedFields(const SourceLocation &Loc,
10292 DeclarationName FieldName,
10293 const CXXRecordDecl *RD);
10295 /// \brief Check if the given expression contains 'break' or 'continue'
10296 /// statement that produces control flow different from GCC.
10297 void CheckBreakContinueBinding(Expr *E);
10299 /// \brief Check whether receiver is mutable ObjC container which
10300 /// attempts to add itself into the container
10301 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10303 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10304 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10305 bool DeleteWasArrayForm);
10307 /// \brief Register a magic integral constant to be used as a type tag.
10308 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10309 uint64_t MagicValue, QualType Type,
10310 bool LayoutCompatible, bool MustBeNull);
10312 struct TypeTagData {
10315 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10316 Type(Type), LayoutCompatible(LayoutCompatible),
10317 MustBeNull(MustBeNull)
10322 /// If true, \c Type should be compared with other expression's types for
10323 /// layout-compatibility.
10324 unsigned LayoutCompatible : 1;
10325 unsigned MustBeNull : 1;
10328 /// A pair of ArgumentKind identifier and magic value. This uniquely
10329 /// identifies the magic value.
10330 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10333 /// \brief A map from magic value to type information.
10334 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10335 TypeTagForDatatypeMagicValues;
10337 /// \brief Peform checks on a call of a function with argument_with_type_tag
10338 /// or pointer_with_type_tag attributes.
10339 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10340 const Expr * const *ExprArgs);
10342 /// \brief Check if we are taking the address of a packed field
10343 /// as this may be a problem if the pointer value is dereferenced.
10344 void CheckAddressOfPackedMember(Expr *rhs);
10346 /// \brief The parser's current scope.
10348 /// The parser maintains this state here.
10351 mutable IdentifierInfo *Ident_super;
10352 mutable IdentifierInfo *Ident___float128;
10354 /// Nullability type specifiers.
10355 IdentifierInfo *Ident__Nonnull = nullptr;
10356 IdentifierInfo *Ident__Nullable = nullptr;
10357 IdentifierInfo *Ident__Null_unspecified = nullptr;
10359 IdentifierInfo *Ident_NSError = nullptr;
10362 friend class Parser;
10363 friend class InitializationSequence;
10364 friend class ASTReader;
10365 friend class ASTDeclReader;
10366 friend class ASTWriter;
10369 /// Retrieve the keyword associated
10370 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10372 /// The struct behind the CFErrorRef pointer.
10373 RecordDecl *CFError = nullptr;
10375 /// Retrieve the identifier "NSError".
10376 IdentifierInfo *getNSErrorIdent();
10378 /// \brief Retrieve the parser's current scope.
10380 /// This routine must only be used when it is certain that semantic analysis
10381 /// and the parser are in precisely the same context, which is not the case
10382 /// when, e.g., we are performing any kind of template instantiation.
10383 /// Therefore, the only safe places to use this scope are in the parser
10384 /// itself and in routines directly invoked from the parser and *never* from
10385 /// template substitution or instantiation.
10386 Scope *getCurScope() const { return CurScope; }
10388 void incrementMSManglingNumber() const {
10389 return CurScope->incrementMSManglingNumber();
10392 IdentifierInfo *getSuperIdentifier() const;
10393 IdentifierInfo *getFloat128Identifier() const;
10395 Decl *getObjCDeclContext() const;
10397 DeclContext *getCurLexicalContext() const {
10398 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10401 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10403 /// \param D The declaration to check. Note that this may be altered to point
10404 /// to another declaration that \c D gets it's availability from. i.e., we
10405 /// walk the list of typedefs to find an availability attribute.
10407 /// \param Message If non-null, this will be populated with the message from
10408 /// the availability attribute that is selected.
10409 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10410 std::string *Message);
10412 const DeclContext *getCurObjCLexicalContext() const {
10413 const DeclContext *DC = getCurLexicalContext();
10414 // A category implicitly has the attribute of the interface.
10415 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10416 DC = CatD->getClassInterface();
10420 /// \brief To be used for checking whether the arguments being passed to
10421 /// function exceeds the number of parameters expected for it.
10422 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10423 bool PartialOverloading = false) {
10424 // We check whether we're just after a comma in code-completion.
10425 if (NumArgs > 0 && PartialOverloading)
10426 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10427 return NumArgs > NumParams;
10430 // Emitting members of dllexported classes is delayed until the class
10431 // (including field initializers) is fully parsed.
10432 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10435 /// \brief Helper class that collects misaligned member designations and
10436 /// their location info for delayed diagnostics.
10437 struct MisalignedMember {
10441 CharUnits Alignment;
10443 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10444 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10445 CharUnits Alignment)
10446 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10447 explicit MisalignedMember(Expr *E)
10448 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10450 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10452 /// \brief Small set of gathered accesses to potentially misaligned members
10453 /// due to the packed attribute.
10454 SmallVector<MisalignedMember, 4> MisalignedMembers;
10456 /// \brief Adds an expression to the set of gathered misaligned members.
10457 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10458 CharUnits Alignment);
10461 /// \brief Diagnoses the current set of gathered accesses. This typically
10462 /// happens at full expression level. The set is cleared after emitting the
10464 void DiagnoseMisalignedMembers();
10466 /// \brief This function checks if the expression is in the sef of potentially
10467 /// misaligned members and it is converted to some pointer type T with lower
10468 /// or equal alignment requirements. If so it removes it. This is used when
10469 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10471 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10473 /// \brief This function calls Action when it determines that E designates a
10474 /// misaligned member due to the packed attribute. This is used to emit
10475 /// local diagnostics like in reference binding.
10476 void RefersToMemberWithReducedAlignment(
10478 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10482 /// \brief RAII object that enters a new expression evaluation context.
10483 class EnterExpressionEvaluationContext {
10485 bool Entered = true;
10489 EnterExpressionEvaluationContext(Sema &Actions,
10490 Sema::ExpressionEvaluationContext NewContext,
10491 Decl *LambdaContextDecl = nullptr,
10492 bool IsDecltype = false,
10493 bool ShouldEnter = true)
10494 : Actions(Actions), Entered(ShouldEnter) {
10496 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10499 EnterExpressionEvaluationContext(Sema &Actions,
10500 Sema::ExpressionEvaluationContext NewContext,
10501 Sema::ReuseLambdaContextDecl_t,
10502 bool IsDecltype = false)
10503 : Actions(Actions) {
10504 Actions.PushExpressionEvaluationContext(NewContext,
10505 Sema::ReuseLambdaContextDecl,
10509 enum InitListTag { InitList };
10510 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10511 bool ShouldEnter = true)
10512 : Actions(Actions), Entered(false) {
10513 // In C++11 onwards, narrowing checks are performed on the contents of
10514 // braced-init-lists, even when they occur within unevaluated operands.
10515 // Therefore we still need to instantiate constexpr functions used in such
10517 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10518 Actions.getLangOpts().CPlusPlus11) {
10519 Actions.PushExpressionEvaluationContext(
10520 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10525 ~EnterExpressionEvaluationContext() {
10527 Actions.PopExpressionEvaluationContext();
10531 DeductionFailureInfo
10532 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10533 sema::TemplateDeductionInfo &Info);
10535 /// \brief Contains a late templated function.
10536 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10537 struct LateParsedTemplate {
10539 /// \brief The template function declaration to be late parsed.
10543 } // end namespace clang
10546 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10548 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10549 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10550 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10552 static FunctionDeclAndLoc getEmptyKey() {
10553 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10556 static FunctionDeclAndLoc getTombstoneKey() {
10557 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10560 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10561 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10562 FDL.Loc.getRawEncoding());
10565 static bool isEqual(const FunctionDeclAndLoc &LHS,
10566 const FunctionDeclAndLoc &RHS) {
10567 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10570 } // namespace llvm