1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Sema class, which performs semantic analysis and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Availability.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/LocInfoType.h"
26 #include "clang/AST/MangleNumberingContext.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/AST/TypeOrdering.h"
32 #include "clang/Basic/ExpressionTraits.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/OpenMPKinds.h"
36 #include "clang/Basic/PragmaKinds.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TemplateKinds.h"
39 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/ExternalSemaSource.h"
44 #include "clang/Sema/IdentifierResolver.h"
45 #include "clang/Sema/ObjCMethodList.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
48 #include "clang/Sema/ScopeInfo.h"
49 #include "clang/Sema/TypoCorrection.h"
50 #include "clang/Sema/Weak.h"
51 #include "llvm/ADT/ArrayRef.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class InlineAsmIdentifierInfo;
74 class ASTMutationListener;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
107 class DeclAccessPair;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
116 class EnumConstantDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
134 class LocalInstantiationScope;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class MultiLevelTemplateArgumentList;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
167 class StandardConversionSequence;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
175 class TemplateParameterList;
176 class TemplatePartialOrderingContext;
177 class TemplateTemplateParmDecl;
181 class TypedefNameDecl;
183 class TypoCorrectionConsumer;
185 class UnresolvedLookupExpr;
186 class UnresolvedMemberExpr;
187 class UnresolvedSetImpl;
188 class UnresolvedSetIterator;
190 class UsingShadowDecl;
193 class VarTemplateSpecializationDecl;
194 class VisibilityAttr;
195 class VisibleDeclConsumer;
196 class IndirectFieldDecl;
197 struct DeductionFailureInfo;
198 class TemplateSpecCandidateSet;
201 class AccessedEntity;
202 class BlockScopeInfo;
203 class CapturedRegionScopeInfo;
204 class CapturingScopeInfo;
205 class CompoundScopeInfo;
206 class DelayedDiagnostic;
207 class DelayedDiagnosticPool;
208 class FunctionScopeInfo;
209 class LambdaScopeInfo;
210 class PossiblyUnreachableDiag;
211 class TemplateDeductionInfo;
214 namespace threadSafety {
216 void threadSafetyCleanup(BeforeSet* Cache);
219 // FIXME: No way to easily map from TemplateTypeParmTypes to
220 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
221 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222 SourceLocation> UnexpandedParameterPack;
224 /// Describes whether we've seen any nullability information for the given
226 struct FileNullability {
227 /// The first pointer declarator (of any pointer kind) in the file that does
228 /// not have a corresponding nullability annotation.
229 SourceLocation PointerLoc;
231 /// Which kind of pointer declarator we saw.
234 /// Whether we saw any type nullability annotations in the given file.
235 bool SawTypeNullability = false;
238 /// A mapping from file IDs to a record of whether we've seen nullability
239 /// information in that file.
240 class FileNullabilityMap {
241 /// A mapping from file IDs to the nullability information for each file ID.
242 llvm::DenseMap<FileID, FileNullability> Map;
244 /// A single-element cache based on the file ID.
247 FileNullability Nullability;
251 FileNullability &operator[](FileID file) {
252 // Check the single-element cache.
253 if (file == Cache.File)
254 return Cache.Nullability;
256 // It's not in the single-element cache; flush the cache if we have one.
257 if (!Cache.File.isInvalid()) {
258 Map[Cache.File] = Cache.Nullability;
261 // Pull this entry into the cache.
263 Cache.Nullability = Map[file];
264 return Cache.Nullability;
268 /// Sema - This implements semantic analysis and AST building for C.
270 Sema(const Sema &) = delete;
271 void operator=(const Sema &) = delete;
273 ///\brief Source of additional semantic information.
274 ExternalSemaSource *ExternalSource;
276 ///\brief Whether Sema has generated a multiplexer and has to delete it.
277 bool isMultiplexExternalSource;
279 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
281 bool isVisibleSlow(const NamedDecl *D);
283 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
284 const NamedDecl *New) {
285 // We are about to link these. It is now safe to compute the linkage of
286 // the new decl. If the new decl has external linkage, we will
287 // link it with the hidden decl (which also has external linkage) and
288 // it will keep having external linkage. If it has internal linkage, we
289 // will not link it. Since it has no previous decls, it will remain
290 // with internal linkage.
291 return isVisible(Old) || New->isExternallyVisible();
293 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
296 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297 typedef OpaquePtr<TemplateName> TemplateTy;
298 typedef OpaquePtr<QualType> TypeTy;
300 OpenCLOptions OpenCLFeatures;
301 FPOptions FPFeatures;
303 const LangOptions &LangOpts;
306 ASTConsumer &Consumer;
307 DiagnosticsEngine &Diags;
308 SourceManager &SourceMgr;
310 /// \brief Flag indicating whether or not to collect detailed statistics.
313 /// \brief Code-completion consumer.
314 CodeCompleteConsumer *CodeCompleter;
316 /// CurContext - This is the current declaration context of parsing.
317 DeclContext *CurContext;
319 /// \brief Generally null except when we temporarily switch decl contexts,
320 /// like in \see ActOnObjCTemporaryExitContainerContext.
321 DeclContext *OriginalLexicalContext;
323 /// VAListTagName - The declaration name corresponding to __va_list_tag.
324 /// This is used as part of a hack to omit that class from ADL results.
325 DeclarationName VAListTagName;
327 bool MSStructPragmaOn; // True when \#pragma ms_struct on
329 /// \brief Controls member pointer representation format under the MS ABI.
330 LangOptions::PragmaMSPointersToMembersKind
331 MSPointerToMemberRepresentationMethod;
333 /// Stack of active SEH __finally scopes. Can be empty.
334 SmallVector<Scope*, 2> CurrentSEHFinally;
336 /// \brief Source location for newly created implicit MSInheritanceAttrs
337 SourceLocation ImplicitMSInheritanceAttrLoc;
339 enum PragmaMsStackAction {
340 PSK_Reset = 0x0, // #pragma ()
341 PSK_Set = 0x1, // #pragma (value)
342 PSK_Push = 0x2, // #pragma (push[, id])
343 PSK_Pop = 0x4, // #pragma (pop[, id])
344 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
345 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
346 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
349 template<typename ValueType>
352 llvm::StringRef StackSlotLabel;
354 SourceLocation PragmaLocation;
355 Slot(llvm::StringRef StackSlotLabel,
357 SourceLocation PragmaLocation)
358 : StackSlotLabel(StackSlotLabel), Value(Value),
359 PragmaLocation(PragmaLocation) {}
361 void Act(SourceLocation PragmaLocation,
362 PragmaMsStackAction Action,
363 llvm::StringRef StackSlotLabel,
366 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
367 // method body to restore the stacks on exit, so it works like this:
370 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
372 // #pragma <name>(pop, InternalPragmaSlot)
375 // It works even with #pragma vtordisp, although MSVC doesn't support
376 // #pragma vtordisp(push [, id], n)
379 // Push / pop a named sentinel slot.
380 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
381 assert((Action == PSK_Push || Action == PSK_Pop) &&
382 "Can only push / pop #pragma stack sentinels!");
383 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
387 explicit PragmaStack(const ValueType &Default)
388 : DefaultValue(Default), CurrentValue(Default) {}
390 SmallVector<Slot, 2> Stack;
391 ValueType DefaultValue; // Value used for PSK_Reset action.
392 ValueType CurrentValue;
393 SourceLocation CurrentPragmaLocation;
395 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
396 // we shouldn't do so if they're in a module).
398 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
399 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
401 /// 0: Suppress all vtordisps
402 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
404 /// 2: Always insert vtordisps to support RTTI on partially constructed
406 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
408 // Sentinel to represent when the stack is set to mac68k alignment.
409 static const unsigned kMac68kAlignmentSentinel = ~0U;
410 PragmaStack<unsigned> PackStack;
412 PragmaStack<StringLiteral *> DataSegStack;
413 PragmaStack<StringLiteral *> BSSSegStack;
414 PragmaStack<StringLiteral *> ConstSegStack;
415 PragmaStack<StringLiteral *> CodeSegStack;
417 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
418 // Actions should be performed only if we enter / exit a C++ method body.
419 class PragmaStackSentinelRAII {
421 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
422 ~PragmaStackSentinelRAII();
430 /// A mapping that describes the nullability we've seen in each header file.
431 FileNullabilityMap NullabilityMap;
433 /// Last section used with #pragma init_seg.
434 StringLiteral *CurInitSeg;
435 SourceLocation CurInitSegLoc;
437 /// VisContext - Manages the stack for \#pragma GCC visibility.
438 void *VisContext; // Really a "PragmaVisStack*"
440 /// \brief This represents the stack of attributes that were pushed by
441 /// \#pragma clang attribute.
442 struct PragmaAttributeEntry {
444 AttributeList *Attribute;
445 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
448 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
450 /// \brief The declaration that is currently receiving an attribute from the
451 /// #pragma attribute stack.
452 const Decl *PragmaAttributeCurrentTargetDecl;
454 /// \brief This represents the last location of a "#pragma clang optimize off"
455 /// directive if such a directive has not been closed by an "on" yet. If
456 /// optimizations are currently "on", this is set to an invalid location.
457 SourceLocation OptimizeOffPragmaLocation;
459 /// \brief Flag indicating if Sema is building a recovery call expression.
461 /// This flag is used to avoid building recovery call expressions
462 /// if Sema is already doing so, which would cause infinite recursions.
463 bool IsBuildingRecoveryCallExpr;
465 /// Used to control the generation of ExprWithCleanups.
468 /// ExprCleanupObjects - This is the stack of objects requiring
469 /// cleanup that are created by the current full expression. The
470 /// element type here is ExprWithCleanups::Object.
471 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
473 /// \brief Store a list of either DeclRefExprs or MemberExprs
474 /// that contain a reference to a variable (constant) that may or may not
475 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
476 /// and discarded value conversions have been applied to all subexpressions
477 /// of the enclosing full expression. This is cleared at the end of each
479 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
481 /// \brief Stack containing information about each of the nested
482 /// function, block, and method scopes that are currently active.
484 /// This array is never empty. Clients should ignore the first
485 /// element, which is used to cache a single FunctionScopeInfo
486 /// that's used to parse every top-level function.
487 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
489 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
490 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
493 /// ExtVectorDecls - This is a list all the extended vector types. This allows
494 /// us to associate a raw vector type with one of the ext_vector type names.
495 /// This is only necessary for issuing pretty diagnostics.
496 ExtVectorDeclsType ExtVectorDecls;
498 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
499 std::unique_ptr<CXXFieldCollector> FieldCollector;
501 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
503 /// \brief Set containing all declared private fields that are not used.
504 NamedDeclSetType UnusedPrivateFields;
506 /// \brief Set containing all typedefs that are likely unused.
507 llvm::SmallSetVector<const TypedefNameDecl *, 4>
508 UnusedLocalTypedefNameCandidates;
510 /// \brief Delete-expressions to be analyzed at the end of translation unit
512 /// This list contains class members, and locations of delete-expressions
513 /// that could not be proven as to whether they mismatch with new-expression
514 /// used in initializer of the field.
515 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
516 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
517 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
519 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
521 /// PureVirtualClassDiagSet - a set of class declarations which we have
522 /// emitted a list of pure virtual functions. Used to prevent emitting the
523 /// same list more than once.
524 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
526 /// ParsingInitForAutoVars - a set of declarations with auto types for which
527 /// we are currently parsing the initializer.
528 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
530 /// \brief Look for a locally scoped extern "C" declaration by the given name.
531 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
533 typedef LazyVector<VarDecl *, ExternalSemaSource,
534 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
535 TentativeDefinitionsType;
537 /// \brief All the tentative definitions encountered in the TU.
538 TentativeDefinitionsType TentativeDefinitions;
540 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
542 UnusedFileScopedDeclsType;
544 /// \brief The set of file scoped decls seen so far that have not been used
545 /// and must warn if not used. Only contains the first declaration.
546 UnusedFileScopedDeclsType UnusedFileScopedDecls;
548 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
549 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
550 DelegatingCtorDeclsType;
552 /// \brief All the delegating constructors seen so far in the file, used for
553 /// cycle detection at the end of the TU.
554 DelegatingCtorDeclsType DelegatingCtorDecls;
556 /// \brief All the overriding functions seen during a class definition
557 /// that had their exception spec checks delayed, plus the overridden
559 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
560 DelayedExceptionSpecChecks;
562 /// \brief All the members seen during a class definition which were both
563 /// explicitly defaulted and had explicitly-specified exception
564 /// specifications, along with the function type containing their
565 /// user-specified exception specification. Those exception specifications
566 /// were overridden with the default specifications, but we still need to
567 /// check whether they are compatible with the default specification, and
568 /// we can't do that until the nesting set of class definitions is complete.
569 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
570 DelayedDefaultedMemberExceptionSpecs;
572 typedef llvm::MapVector<const FunctionDecl *,
573 std::unique_ptr<LateParsedTemplate>>
574 LateParsedTemplateMapT;
575 LateParsedTemplateMapT LateParsedTemplateMap;
577 /// \brief Callback to the parser to parse templated functions when needed.
578 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
579 typedef void LateTemplateParserCleanupCB(void *P);
580 LateTemplateParserCB *LateTemplateParser;
581 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
584 void SetLateTemplateParser(LateTemplateParserCB *LTP,
585 LateTemplateParserCleanupCB *LTPCleanup,
587 LateTemplateParser = LTP;
588 LateTemplateParserCleanup = LTPCleanup;
592 class DelayedDiagnostics;
594 class DelayedDiagnosticsState {
595 sema::DelayedDiagnosticPool *SavedPool;
596 friend class Sema::DelayedDiagnostics;
598 typedef DelayedDiagnosticsState ParsingDeclState;
599 typedef DelayedDiagnosticsState ProcessingContextState;
601 /// A class which encapsulates the logic for delaying diagnostics
602 /// during parsing and other processing.
603 class DelayedDiagnostics {
604 /// \brief The current pool of diagnostics into which delayed
605 /// diagnostics should go.
606 sema::DelayedDiagnosticPool *CurPool;
609 DelayedDiagnostics() : CurPool(nullptr) {}
611 /// Adds a delayed diagnostic.
612 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
614 /// Determines whether diagnostics should be delayed.
615 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
617 /// Returns the current delayed-diagnostics pool.
618 sema::DelayedDiagnosticPool *getCurrentPool() const {
622 /// Enter a new scope. Access and deprecation diagnostics will be
623 /// collected in this pool.
624 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
625 DelayedDiagnosticsState state;
626 state.SavedPool = CurPool;
631 /// Leave a delayed-diagnostic state that was previously pushed.
632 /// Do not emit any of the diagnostics. This is performed as part
633 /// of the bookkeeping of popping a pool "properly".
634 void popWithoutEmitting(DelayedDiagnosticsState state) {
635 CurPool = state.SavedPool;
638 /// Enter a new scope where access and deprecation diagnostics are
640 DelayedDiagnosticsState pushUndelayed() {
641 DelayedDiagnosticsState state;
642 state.SavedPool = CurPool;
647 /// Undo a previous pushUndelayed().
648 void popUndelayed(DelayedDiagnosticsState state) {
649 assert(CurPool == nullptr);
650 CurPool = state.SavedPool;
652 } DelayedDiagnostics;
654 /// A RAII object to temporarily push a declaration context.
658 DeclContext *SavedContext;
659 ProcessingContextState SavedContextState;
660 QualType SavedCXXThisTypeOverride;
663 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
664 : S(S), SavedContext(S.CurContext),
665 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
666 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
668 assert(ContextToPush && "pushing null context");
669 S.CurContext = ContextToPush;
671 S.CXXThisTypeOverride = QualType();
675 if (!SavedContext) return;
676 S.CurContext = SavedContext;
677 S.DelayedDiagnostics.popUndelayed(SavedContextState);
678 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
679 SavedContext = nullptr;
687 /// \brief RAII object to handle the state changes required to synthesize
689 class SynthesizedFunctionScope {
691 Sema::ContextRAII SavedContext;
694 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
695 : S(S), SavedContext(S, DC)
697 S.PushFunctionScope();
698 S.PushExpressionEvaluationContext(
699 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
702 ~SynthesizedFunctionScope() {
703 S.PopExpressionEvaluationContext();
704 S.PopFunctionScopeInfo();
708 /// WeakUndeclaredIdentifiers - Identifiers contained in
709 /// \#pragma weak before declared. rare. may alias another
710 /// identifier, declared or undeclared
711 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
713 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
714 /// \#pragma redefine_extname before declared. Used in Solaris system headers
715 /// to define functions that occur in multiple standards to call the version
716 /// in the currently selected standard.
717 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
720 /// \brief Load weak undeclared identifiers from the external source.
721 void LoadExternalWeakUndeclaredIdentifiers();
723 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
724 /// \#pragma weak during processing of other Decls.
725 /// I couldn't figure out a clean way to generate these in-line, so
726 /// we store them here and handle separately -- which is a hack.
727 /// It would be best to refactor this.
728 SmallVector<Decl*,2> WeakTopLevelDecl;
730 IdentifierResolver IdResolver;
732 /// Translation Unit Scope - useful to Objective-C actions that need
733 /// to lookup file scope declarations in the "ordinary" C decl namespace.
734 /// For example, user-defined classes, built-in "id" type, etc.
737 /// \brief The C++ "std" namespace, where the standard library resides.
738 LazyDeclPtr StdNamespace;
740 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
741 /// standard library.
742 LazyDeclPtr StdBadAlloc;
744 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
745 /// standard library.
746 LazyDeclPtr StdAlignValT;
748 /// \brief The C++ "std::experimental" namespace, where the experimental parts
749 /// of the standard library resides.
750 NamespaceDecl *StdExperimentalNamespaceCache;
752 /// \brief The C++ "std::initializer_list" template, which is defined in
753 /// \<initializer_list>.
754 ClassTemplateDecl *StdInitializerList;
756 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
757 RecordDecl *CXXTypeInfoDecl;
759 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
760 RecordDecl *MSVCGuidDecl;
762 /// \brief Caches identifiers/selectors for NSFoundation APIs.
763 std::unique_ptr<NSAPI> NSAPIObj;
765 /// \brief The declaration of the Objective-C NSNumber class.
766 ObjCInterfaceDecl *NSNumberDecl;
768 /// \brief The declaration of the Objective-C NSValue class.
769 ObjCInterfaceDecl *NSValueDecl;
771 /// \brief Pointer to NSNumber type (NSNumber *).
772 QualType NSNumberPointer;
774 /// \brief Pointer to NSValue type (NSValue *).
775 QualType NSValuePointer;
777 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
778 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
780 /// \brief The declaration of the Objective-C NSString class.
781 ObjCInterfaceDecl *NSStringDecl;
783 /// \brief Pointer to NSString type (NSString *).
784 QualType NSStringPointer;
786 /// \brief The declaration of the stringWithUTF8String: method.
787 ObjCMethodDecl *StringWithUTF8StringMethod;
789 /// \brief The declaration of the valueWithBytes:objCType: method.
790 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
792 /// \brief The declaration of the Objective-C NSArray class.
793 ObjCInterfaceDecl *NSArrayDecl;
795 /// \brief The declaration of the arrayWithObjects:count: method.
796 ObjCMethodDecl *ArrayWithObjectsMethod;
798 /// \brief The declaration of the Objective-C NSDictionary class.
799 ObjCInterfaceDecl *NSDictionaryDecl;
801 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
802 ObjCMethodDecl *DictionaryWithObjectsMethod;
804 /// \brief id<NSCopying> type.
805 QualType QIDNSCopying;
807 /// \brief will hold 'respondsToSelector:'
808 Selector RespondsToSelectorSel;
810 /// A flag to remember whether the implicit forms of operator new and delete
811 /// have been declared.
812 bool GlobalNewDeleteDeclared;
814 /// A flag to indicate that we're in a context that permits abstract
815 /// references to fields. This is really a
816 bool AllowAbstractFieldReference;
818 /// \brief Describes how the expressions currently being parsed are
819 /// evaluated at run-time, if at all.
820 enum class ExpressionEvaluationContext {
821 /// \brief The current expression and its subexpressions occur within an
822 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
823 /// \c sizeof, where the type of the expression may be significant but
824 /// no code will be generated to evaluate the value of the expression at
828 /// \brief The current expression occurs within a braced-init-list within
829 /// an unevaluated operand. This is mostly like a regular unevaluated
830 /// context, except that we still instantiate constexpr functions that are
831 /// referenced here so that we can perform narrowing checks correctly.
834 /// \brief The current expression occurs within a discarded statement.
835 /// This behaves largely similarly to an unevaluated operand in preventing
836 /// definitions from being required, but not in other ways.
839 /// \brief The current expression occurs within an unevaluated
840 /// operand that unconditionally permits abstract references to
841 /// fields, such as a SIZE operator in MS-style inline assembly.
844 /// \brief The current context is "potentially evaluated" in C++11 terms,
845 /// but the expression is evaluated at compile-time (like the values of
846 /// cases in a switch statement).
849 /// \brief The current expression is potentially evaluated at run time,
850 /// which means that code may be generated to evaluate the value of the
851 /// expression at run time.
852 PotentiallyEvaluated,
854 /// \brief The current expression is potentially evaluated, but any
855 /// declarations referenced inside that expression are only used if
856 /// in fact the current expression is used.
858 /// This value is used when parsing default function arguments, for which
859 /// we would like to provide diagnostics (e.g., passing non-POD arguments
860 /// through varargs) but do not want to mark declarations as "referenced"
861 /// until the default argument is used.
862 PotentiallyEvaluatedIfUsed
865 /// \brief Data structure used to record current or nested
866 /// expression evaluation contexts.
867 struct ExpressionEvaluationContextRecord {
868 /// \brief The expression evaluation context.
869 ExpressionEvaluationContext Context;
871 /// \brief Whether the enclosing context needed a cleanup.
872 CleanupInfo ParentCleanup;
874 /// \brief Whether we are in a decltype expression.
877 /// \brief The number of active cleanup objects when we entered
878 /// this expression evaluation context.
879 unsigned NumCleanupObjects;
881 /// \brief The number of typos encountered during this expression evaluation
882 /// context (i.e. the number of TypoExprs created).
885 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
887 /// \brief The lambdas that are present within this context, if it
888 /// is indeed an unevaluated context.
889 SmallVector<LambdaExpr *, 2> Lambdas;
891 /// \brief The declaration that provides context for lambda expressions
892 /// and block literals if the normal declaration context does not
893 /// suffice, e.g., in a default function argument.
894 Decl *ManglingContextDecl;
896 /// \brief The context information used to mangle lambda expressions
897 /// and block literals within this context.
899 /// This mangling information is allocated lazily, since most contexts
900 /// do not have lambda expressions or block literals.
901 std::unique_ptr<MangleNumberingContext> MangleNumbering;
903 /// \brief If we are processing a decltype type, a set of call expressions
904 /// for which we have deferred checking the completeness of the return type.
905 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
907 /// \brief If we are processing a decltype type, a set of temporary binding
908 /// expressions for which we have deferred checking the destructor.
909 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
911 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
912 unsigned NumCleanupObjects,
913 CleanupInfo ParentCleanup,
914 Decl *ManglingContextDecl,
916 : Context(Context), ParentCleanup(ParentCleanup),
917 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
919 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
921 /// \brief Retrieve the mangling numbering context, used to consistently
922 /// number constructs like lambdas for mangling.
923 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
925 bool isUnevaluated() const {
926 return Context == ExpressionEvaluationContext::Unevaluated ||
927 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
928 Context == ExpressionEvaluationContext::UnevaluatedList;
930 bool isConstantEvaluated() const {
931 return Context == ExpressionEvaluationContext::ConstantEvaluated;
935 /// A stack of expression evaluation contexts.
936 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
938 /// \brief Compute the mangling number context for a lambda expression or
941 /// \param DC - The DeclContext containing the lambda expression or
943 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
944 /// associated with the context, if relevant.
945 MangleNumberingContext *getCurrentMangleNumberContext(
946 const DeclContext *DC,
947 Decl *&ManglingContextDecl);
950 /// SpecialMemberOverloadResult - The overloading result for a special member
953 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
954 /// integer are used to determine whether overload resolution succeeded.
955 class SpecialMemberOverloadResult {
964 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
967 SpecialMemberOverloadResult() : Pair() {}
968 SpecialMemberOverloadResult(CXXMethodDecl *MD)
969 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
971 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
972 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
974 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
975 void setKind(Kind K) { Pair.setInt(K); }
978 class SpecialMemberOverloadResultEntry
979 : public llvm::FastFoldingSetNode,
980 public SpecialMemberOverloadResult {
982 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
983 : FastFoldingSetNode(ID)
987 /// \brief A cache of special member function overload resolution results
989 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
991 /// \brief A cache of the flags available in enumerations with the flag_bits
993 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
995 /// \brief The kind of translation unit we are processing.
997 /// When we're processing a complete translation unit, Sema will perform
998 /// end-of-translation-unit semantic tasks (such as creating
999 /// initializers for tentative definitions in C) once parsing has
1000 /// completed. Modules and precompiled headers perform different kinds of
1002 TranslationUnitKind TUKind;
1004 llvm::BumpPtrAllocator BumpAlloc;
1006 /// \brief The number of SFINAE diagnostics that have been trapped.
1007 unsigned NumSFINAEErrors;
1009 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1010 UnparsedDefaultArgInstantiationsMap;
1012 /// \brief A mapping from parameters with unparsed default arguments to the
1013 /// set of instantiations of each parameter.
1015 /// This mapping is a temporary data structure used when parsing
1016 /// nested class templates or nested classes of class templates,
1017 /// where we might end up instantiating an inner class before the
1018 /// default arguments of its methods have been parsed.
1019 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1021 // Contains the locations of the beginning of unparsed default
1022 // argument locations.
1023 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1025 /// UndefinedInternals - all the used, undefined objects which require a
1026 /// definition in this translation unit.
1027 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1029 /// Obtain a sorted list of functions that are undefined but ODR-used.
1030 void getUndefinedButUsed(
1031 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1033 /// Retrieves list of suspicious delete-expressions that will be checked at
1034 /// the end of translation unit.
1035 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1036 getMismatchingDeleteExpressions() const;
1038 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1039 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1041 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1042 /// We need to maintain a list, since selectors can have differing signatures
1043 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1044 /// of selectors are "overloaded").
1045 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1046 /// methods inside categories with a particular selector.
1047 GlobalMethodPool MethodPool;
1049 /// Method selectors used in a \@selector expression. Used for implementation
1051 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1053 /// Kinds of C++ special members.
1054 enum CXXSpecialMember {
1055 CXXDefaultConstructor,
1064 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1066 /// The C++ special members which we are currently in the process of
1067 /// declaring. If this process recursively triggers the declaration of the
1068 /// same special member, we should act as if it is not yet declared.
1069 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1071 /// The function definitions which were renamed as part of typo-correction
1072 /// to match their respective declarations. We want to keep track of them
1073 /// to ensure that we don't emit a "redefinition" error if we encounter a
1074 /// correctly named definition after the renamed definition.
1075 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1077 void ReadMethodPool(Selector Sel);
1078 void updateOutOfDateSelector(Selector Sel);
1080 /// Private Helper predicate to check for 'self'.
1081 bool isSelfExpr(Expr *RExpr);
1082 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1084 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1085 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1086 /// should not be used elsewhere.
1087 void EmitCurrentDiagnostic(unsigned DiagID);
1089 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1091 class FPContractStateRAII {
1093 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1094 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1098 FPOptions OldFPFeaturesState;
1101 void addImplicitTypedef(StringRef Name, QualType T);
1104 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1105 TranslationUnitKind TUKind = TU_Complete,
1106 CodeCompleteConsumer *CompletionConsumer = nullptr);
1109 /// \brief Perform initialization that occurs after the parser has been
1110 /// initialized but before it parses anything.
1113 const LangOptions &getLangOpts() const { return LangOpts; }
1114 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1115 FPOptions &getFPOptions() { return FPFeatures; }
1117 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1118 SourceManager &getSourceManager() const { return SourceMgr; }
1119 Preprocessor &getPreprocessor() const { return PP; }
1120 ASTContext &getASTContext() const { return Context; }
1121 ASTConsumer &getASTConsumer() const { return Consumer; }
1122 ASTMutationListener *getASTMutationListener() const;
1123 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1125 ///\brief Registers an external source. If an external source already exists,
1126 /// creates a multiplex external source and appends to it.
1128 ///\param[in] E - A non-null external sema source.
1130 void addExternalSource(ExternalSemaSource *E);
1132 void PrintStats() const;
1134 /// \brief Helper class that creates diagnostics with optional
1135 /// template instantiation stacks.
1137 /// This class provides a wrapper around the basic DiagnosticBuilder
1138 /// class that emits diagnostics. SemaDiagnosticBuilder is
1139 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1140 /// does) and, if the diagnostic comes from inside a template
1141 /// instantiation, printing the template instantiation stack as
1143 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1148 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1149 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1151 // This is a cunning lie. DiagnosticBuilder actually performs move
1152 // construction in its copy constructor (but due to varied uses, it's not
1153 // possible to conveniently express this as actual move construction). So
1154 // the default copy ctor here is fine, because the base class disables the
1155 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1156 // in that case anwyay.
1157 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1159 ~SemaDiagnosticBuilder() {
1160 // If we aren't active, there is nothing to do.
1161 if (!isActive()) return;
1163 // Otherwise, we need to emit the diagnostic. First flush the underlying
1164 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1165 // won't emit the diagnostic in its own destructor.
1167 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1168 // do its own needless checks to see if the diagnostic needs to be
1169 // emitted. However, because we take care to ensure that the builder
1170 // objects never escape, a sufficiently smart compiler will be able to
1171 // eliminate that code.
1175 // Dispatch to Sema to emit the diagnostic.
1176 SemaRef.EmitCurrentDiagnostic(DiagID);
1179 /// Teach operator<< to produce an object of the correct type.
1180 template<typename T>
1181 friend const SemaDiagnosticBuilder &operator<<(
1182 const SemaDiagnosticBuilder &Diag, const T &Value) {
1183 const DiagnosticBuilder &BaseDiag = Diag;
1189 /// \brief Emit a diagnostic.
1190 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1191 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1192 return SemaDiagnosticBuilder(DB, *this, DiagID);
1195 /// \brief Emit a partial diagnostic.
1196 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1198 /// \brief Build a partial diagnostic.
1199 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1201 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1203 /// \brief Get a string to suggest for zero-initialization of a type.
1205 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1206 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1208 /// \brief Calls \c Lexer::getLocForEndOfToken()
1209 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1211 /// \brief Retrieve the module loader associated with the preprocessor.
1212 ModuleLoader &getModuleLoader() const;
1214 void emitAndClearUnusedLocalTypedefWarnings();
1216 void ActOnEndOfTranslationUnit();
1218 void CheckDelegatingCtorCycles();
1220 Scope *getScopeForContext(DeclContext *Ctx);
1222 void PushFunctionScope();
1223 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1224 sema::LambdaScopeInfo *PushLambdaScope();
1226 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1227 /// is during Parsing. Currently it is used to pass on the depth
1228 /// when parsing generic lambda 'auto' parameters.
1229 void RecordParsingTemplateParameterDepth(unsigned Depth);
1231 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1233 CapturedRegionKind K);
1235 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1236 const Decl *D = nullptr,
1237 const BlockExpr *blkExpr = nullptr);
1239 sema::FunctionScopeInfo *getCurFunction() const {
1240 return FunctionScopes.back();
1243 sema::FunctionScopeInfo *getEnclosingFunction() const {
1244 if (FunctionScopes.empty())
1247 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1248 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1250 return FunctionScopes[e];
1255 template <typename ExprT>
1256 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1257 if (!isUnevaluatedContext())
1258 getCurFunction()->recordUseOfWeak(E, IsRead);
1261 void PushCompoundScope();
1262 void PopCompoundScope();
1264 sema::CompoundScopeInfo &getCurCompoundScope() const;
1266 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1268 /// \brief Retrieve the current block, if any.
1269 sema::BlockScopeInfo *getCurBlock();
1271 /// Retrieve the current lambda scope info, if any.
1272 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1273 /// lambda scope info ignoring all inner capturing scopes that are not
1275 sema::LambdaScopeInfo *
1276 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1278 /// \brief Retrieve the current generic lambda info, if any.
1279 sema::LambdaScopeInfo *getCurGenericLambda();
1281 /// \brief Retrieve the current captured region, if any.
1282 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1284 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1285 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1287 void ActOnComment(SourceRange Comment);
1289 //===--------------------------------------------------------------------===//
1290 // Type Analysis / Processing: SemaType.cpp.
1293 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1294 const DeclSpec *DS = nullptr);
1295 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1296 const DeclSpec *DS = nullptr);
1297 QualType BuildPointerType(QualType T,
1298 SourceLocation Loc, DeclarationName Entity);
1299 QualType BuildReferenceType(QualType T, bool LValueRef,
1300 SourceLocation Loc, DeclarationName Entity);
1301 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1302 Expr *ArraySize, unsigned Quals,
1303 SourceRange Brackets, DeclarationName Entity);
1304 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1305 SourceLocation AttrLoc);
1307 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1309 /// \brief Build a function type.
1311 /// This routine checks the function type according to C++ rules and
1312 /// under the assumption that the result type and parameter types have
1313 /// just been instantiated from a template. It therefore duplicates
1314 /// some of the behavior of GetTypeForDeclarator, but in a much
1315 /// simpler form that is only suitable for this narrow use case.
1317 /// \param T The return type of the function.
1319 /// \param ParamTypes The parameter types of the function. This array
1320 /// will be modified to account for adjustments to the types of the
1321 /// function parameters.
1323 /// \param Loc The location of the entity whose type involves this
1324 /// function type or, if there is no such entity, the location of the
1325 /// type that will have function type.
1327 /// \param Entity The name of the entity that involves the function
1330 /// \param EPI Extra information about the function type. Usually this will
1331 /// be taken from an existing function with the same prototype.
1333 /// \returns A suitable function type, if there are no errors. The
1334 /// unqualified type will always be a FunctionProtoType.
1335 /// Otherwise, returns a NULL type.
1336 QualType BuildFunctionType(QualType T,
1337 MutableArrayRef<QualType> ParamTypes,
1338 SourceLocation Loc, DeclarationName Entity,
1339 const FunctionProtoType::ExtProtoInfo &EPI);
1341 QualType BuildMemberPointerType(QualType T, QualType Class,
1343 DeclarationName Entity);
1344 QualType BuildBlockPointerType(QualType T,
1345 SourceLocation Loc, DeclarationName Entity);
1346 QualType BuildParenType(QualType T);
1347 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1348 QualType BuildReadPipeType(QualType T,
1349 SourceLocation Loc);
1350 QualType BuildWritePipeType(QualType T,
1351 SourceLocation Loc);
1353 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1354 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1355 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1356 TypeSourceInfo *ReturnTypeInfo);
1358 /// \brief Package the given type and TSI into a ParsedType.
1359 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1360 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1361 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1362 static QualType GetTypeFromParser(ParsedType Ty,
1363 TypeSourceInfo **TInfo = nullptr);
1364 CanThrowResult canThrow(const Expr *E);
1365 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1366 const FunctionProtoType *FPT);
1367 void UpdateExceptionSpec(FunctionDecl *FD,
1368 const FunctionProtoType::ExceptionSpecInfo &ESI);
1369 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1370 bool CheckDistantExceptionSpec(QualType T);
1371 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1372 bool CheckEquivalentExceptionSpec(
1373 const FunctionProtoType *Old, SourceLocation OldLoc,
1374 const FunctionProtoType *New, SourceLocation NewLoc);
1375 bool CheckEquivalentExceptionSpec(
1376 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1377 const FunctionProtoType *Old, SourceLocation OldLoc,
1378 const FunctionProtoType *New, SourceLocation NewLoc);
1379 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1380 const PartialDiagnostic &NestedDiagID,
1381 const PartialDiagnostic &NoteID,
1382 const FunctionProtoType *Superset,
1383 SourceLocation SuperLoc,
1384 const FunctionProtoType *Subset,
1385 SourceLocation SubLoc);
1386 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1387 const PartialDiagnostic &NoteID,
1388 const FunctionProtoType *Target,
1389 SourceLocation TargetLoc,
1390 const FunctionProtoType *Source,
1391 SourceLocation SourceLoc);
1393 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1395 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1396 /// in an Objective-C message declaration. Return the appropriate type.
1397 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1399 /// \brief Abstract class used to diagnose incomplete types.
1400 struct TypeDiagnoser {
1403 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1404 virtual ~TypeDiagnoser() {}
1407 static int getPrintable(int I) { return I; }
1408 static unsigned getPrintable(unsigned I) { return I; }
1409 static bool getPrintable(bool B) { return B; }
1410 static const char * getPrintable(const char *S) { return S; }
1411 static StringRef getPrintable(StringRef S) { return S; }
1412 static const std::string &getPrintable(const std::string &S) { return S; }
1413 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1416 static DeclarationName getPrintable(DeclarationName N) { return N; }
1417 static QualType getPrintable(QualType T) { return T; }
1418 static SourceRange getPrintable(SourceRange R) { return R; }
1419 static SourceRange getPrintable(SourceLocation L) { return L; }
1420 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1421 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1423 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1425 std::tuple<const Ts &...> Args;
1427 template <std::size_t... Is>
1428 void emit(const SemaDiagnosticBuilder &DB,
1429 llvm::index_sequence<Is...>) const {
1430 // Apply all tuple elements to the builder in order.
1431 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1436 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1437 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1438 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1441 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1442 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1443 emit(DB, llvm::index_sequence_for<Ts...>());
1449 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1450 TypeDiagnoser *Diagnoser);
1452 struct ModuleScope {
1453 clang::Module *Module;
1454 VisibleModuleSet OuterVisibleModules;
1456 /// The modules we're currently parsing.
1457 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1459 VisibleModuleSet VisibleModules;
1461 Module *CachedFakeTopLevelModule;
1464 /// \brief Get the module owning an entity.
1465 Module *getOwningModule(Decl *Entity);
1467 /// \brief Make a merged definition of an existing hidden definition \p ND
1468 /// visible at the specified location.
1469 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1471 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1473 /// Determine whether a declaration is visible to name lookup.
1474 bool isVisible(const NamedDecl *D) {
1475 return !D->isHidden() || isVisibleSlow(D);
1478 /// Determine whether any declaration of an entity is visible.
1480 hasVisibleDeclaration(const NamedDecl *D,
1481 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1482 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1484 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1485 llvm::SmallVectorImpl<Module *> *Modules);
1487 bool hasVisibleMergedDefinition(NamedDecl *Def);
1489 /// Determine if \p D has a visible definition. If not, suggest a declaration
1490 /// that should be made visible to expose the definition.
1491 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1492 bool OnlyNeedComplete = false);
1493 bool hasVisibleDefinition(const NamedDecl *D) {
1495 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1498 /// Determine if the template parameter \p D has a visible default argument.
1500 hasVisibleDefaultArgument(const NamedDecl *D,
1501 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1503 /// Determine if there is a visible declaration of \p D that is a member
1504 /// specialization declaration (as opposed to an instantiated declaration).
1505 bool hasVisibleMemberSpecialization(
1506 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1508 /// Determine if \p A and \p B are equivalent internal linkage declarations
1509 /// from different modules, and thus an ambiguity error can be downgraded to
1510 /// an extension warning.
1511 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1512 const NamedDecl *B);
1513 void diagnoseEquivalentInternalLinkageDeclarations(
1514 SourceLocation Loc, const NamedDecl *D,
1515 ArrayRef<const NamedDecl *> Equiv);
1517 bool isCompleteType(SourceLocation Loc, QualType T) {
1518 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1520 bool RequireCompleteType(SourceLocation Loc, QualType T,
1521 TypeDiagnoser &Diagnoser);
1522 bool RequireCompleteType(SourceLocation Loc, QualType T,
1525 template <typename... Ts>
1526 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1527 const Ts &...Args) {
1528 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1529 return RequireCompleteType(Loc, T, Diagnoser);
1532 void completeExprArrayBound(Expr *E);
1533 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1534 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1536 template <typename... Ts>
1537 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1538 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1539 return RequireCompleteExprType(E, Diagnoser);
1542 bool RequireLiteralType(SourceLocation Loc, QualType T,
1543 TypeDiagnoser &Diagnoser);
1544 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1546 template <typename... Ts>
1547 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1548 const Ts &...Args) {
1549 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1550 return RequireLiteralType(Loc, T, Diagnoser);
1553 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1554 const CXXScopeSpec &SS, QualType T);
1556 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1557 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1558 /// context, such as when building a type for decltype(auto).
1559 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1560 bool AsUnevaluated = true);
1561 QualType BuildUnaryTransformType(QualType BaseType,
1562 UnaryTransformType::UTTKind UKind,
1563 SourceLocation Loc);
1565 //===--------------------------------------------------------------------===//
1566 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1569 struct SkipBodyInfo {
1570 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1572 NamedDecl *Previous;
1575 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1577 void DiagnoseUseOfUnimplementedSelectors();
1579 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1581 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1582 Scope *S, CXXScopeSpec *SS = nullptr,
1583 bool isClassName = false, bool HasTrailingDot = false,
1584 ParsedType ObjectType = nullptr,
1585 bool IsCtorOrDtorName = false,
1586 bool WantNontrivialTypeSourceInfo = false,
1587 bool IsClassTemplateDeductionContext = true,
1588 IdentifierInfo **CorrectedII = nullptr);
1589 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1590 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1591 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1592 SourceLocation IILoc,
1595 ParsedType &SuggestedType,
1596 bool AllowClassTemplates = false);
1598 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1599 /// type name has failed in a dependent context. In these situations, we
1600 /// automatically form a DependentTypeName that will retry lookup in a related
1601 /// scope during instantiation.
1602 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1603 SourceLocation NameLoc,
1604 bool IsTemplateTypeArg);
1606 /// \brief Describes the result of the name lookup and resolution performed
1607 /// by \c ClassifyName().
1608 enum NameClassificationKind {
1614 NC_NestedNameSpecifier,
1620 class NameClassification {
1621 NameClassificationKind Kind;
1623 TemplateName Template;
1625 const IdentifierInfo *Keyword;
1627 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1630 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1632 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1634 NameClassification(const IdentifierInfo *Keyword)
1635 : Kind(NC_Keyword), Keyword(Keyword) { }
1637 static NameClassification Error() {
1638 return NameClassification(NC_Error);
1641 static NameClassification Unknown() {
1642 return NameClassification(NC_Unknown);
1645 static NameClassification NestedNameSpecifier() {
1646 return NameClassification(NC_NestedNameSpecifier);
1649 static NameClassification TypeTemplate(TemplateName Name) {
1650 NameClassification Result(NC_TypeTemplate);
1651 Result.Template = Name;
1655 static NameClassification VarTemplate(TemplateName Name) {
1656 NameClassification Result(NC_VarTemplate);
1657 Result.Template = Name;
1661 static NameClassification FunctionTemplate(TemplateName Name) {
1662 NameClassification Result(NC_FunctionTemplate);
1663 Result.Template = Name;
1667 NameClassificationKind getKind() const { return Kind; }
1669 ParsedType getType() const {
1670 assert(Kind == NC_Type);
1674 ExprResult getExpression() const {
1675 assert(Kind == NC_Expression);
1679 TemplateName getTemplateName() const {
1680 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1681 Kind == NC_VarTemplate);
1685 TemplateNameKind getTemplateNameKind() const {
1687 case NC_TypeTemplate:
1688 return TNK_Type_template;
1689 case NC_FunctionTemplate:
1690 return TNK_Function_template;
1691 case NC_VarTemplate:
1692 return TNK_Var_template;
1694 llvm_unreachable("unsupported name classification.");
1699 /// \brief Perform name lookup on the given name, classifying it based on
1700 /// the results of name lookup and the following token.
1702 /// This routine is used by the parser to resolve identifiers and help direct
1703 /// parsing. When the identifier cannot be found, this routine will attempt
1704 /// to correct the typo and classify based on the resulting name.
1706 /// \param S The scope in which we're performing name lookup.
1708 /// \param SS The nested-name-specifier that precedes the name.
1710 /// \param Name The identifier. If typo correction finds an alternative name,
1711 /// this pointer parameter will be updated accordingly.
1713 /// \param NameLoc The location of the identifier.
1715 /// \param NextToken The token following the identifier. Used to help
1716 /// disambiguate the name.
1718 /// \param IsAddressOfOperand True if this name is the operand of a unary
1719 /// address of ('&') expression, assuming it is classified as an
1722 /// \param CCC The correction callback, if typo correction is desired.
1724 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1725 SourceLocation NameLoc, const Token &NextToken,
1726 bool IsAddressOfOperand,
1727 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1729 /// Describes the detailed kind of a template name. Used in diagnostics.
1730 enum class TemplateNameKindForDiagnostics {
1735 TemplateTemplateParam,
1738 TemplateNameKindForDiagnostics
1739 getTemplateNameKindForDiagnostics(TemplateName Name);
1741 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1743 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1744 MultiTemplateParamsArg TemplateParameterLists);
1745 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1746 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1747 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1748 DeclarationName Name,
1749 SourceLocation Loc);
1751 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1752 SourceLocation FallbackLoc,
1753 SourceLocation ConstQualLoc = SourceLocation(),
1754 SourceLocation VolatileQualLoc = SourceLocation(),
1755 SourceLocation RestrictQualLoc = SourceLocation(),
1756 SourceLocation AtomicQualLoc = SourceLocation(),
1757 SourceLocation UnalignedQualLoc = SourceLocation());
1759 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1760 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1761 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1762 const LookupResult &R);
1763 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1764 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1765 const LookupResult &R);
1766 void CheckShadow(Scope *S, VarDecl *D);
1768 /// Warn if 'E', which is an expression that is about to be modified, refers
1769 /// to a shadowing declaration.
1770 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1772 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1775 /// Map of current shadowing declarations to shadowed declarations. Warn if
1776 /// it looks like the user is trying to modify the shadowing declaration.
1777 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1780 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1781 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1782 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1783 TypedefNameDecl *NewTD);
1784 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1785 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1786 TypeSourceInfo *TInfo,
1787 LookupResult &Previous);
1788 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1789 LookupResult &Previous, bool &Redeclaration);
1790 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1791 TypeSourceInfo *TInfo,
1792 LookupResult &Previous,
1793 MultiTemplateParamsArg TemplateParamLists,
1795 ArrayRef<BindingDecl *> Bindings = None);
1797 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1798 MultiTemplateParamsArg TemplateParamLists);
1799 // Returns true if the variable declaration is a redeclaration
1800 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1801 void CheckVariableDeclarationType(VarDecl *NewVD);
1802 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1804 void CheckCompleteVariableDeclaration(VarDecl *VD);
1805 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1806 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1808 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1809 TypeSourceInfo *TInfo,
1810 LookupResult &Previous,
1811 MultiTemplateParamsArg TemplateParamLists,
1813 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1815 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1816 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1818 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1819 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1820 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1821 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1822 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1823 // Returns true if the function declaration is a redeclaration
1824 bool CheckFunctionDeclaration(Scope *S,
1825 FunctionDecl *NewFD, LookupResult &Previous,
1826 bool IsMemberSpecialization);
1827 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1828 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1829 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1830 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1831 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1834 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1835 SourceLocation NameLoc, IdentifierInfo *Name,
1836 QualType T, TypeSourceInfo *TSInfo,
1838 void ActOnParamDefaultArgument(Decl *param,
1839 SourceLocation EqualLoc,
1841 void ActOnParamUnparsedDefaultArgument(Decl *param,
1842 SourceLocation EqualLoc,
1843 SourceLocation ArgLoc);
1844 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1845 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1846 SourceLocation EqualLoc);
1848 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1849 void ActOnUninitializedDecl(Decl *dcl);
1850 void ActOnInitializerError(Decl *Dcl);
1852 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1853 void ActOnCXXForRangeDecl(Decl *D);
1854 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1855 IdentifierInfo *Ident,
1856 ParsedAttributes &Attrs,
1857 SourceLocation AttrEnd);
1858 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1859 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1860 void FinalizeDeclaration(Decl *D);
1861 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1862 ArrayRef<Decl *> Group);
1863 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1865 /// Should be called on all declarations that might have attached
1866 /// documentation comments.
1867 void ActOnDocumentableDecl(Decl *D);
1868 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1870 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1871 SourceLocation LocAfterDecls);
1872 void CheckForFunctionRedefinition(
1873 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1874 SkipBodyInfo *SkipBody = nullptr);
1875 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1876 MultiTemplateParamsArg TemplateParamLists,
1877 SkipBodyInfo *SkipBody = nullptr);
1878 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1879 SkipBodyInfo *SkipBody = nullptr);
1880 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1881 bool isObjCMethodDecl(Decl *D) {
1882 return D && isa<ObjCMethodDecl>(D);
1885 /// \brief Determine whether we can delay parsing the body of a function or
1886 /// function template until it is used, assuming we don't care about emitting
1887 /// code for that function.
1889 /// This will be \c false if we may need the body of the function in the
1890 /// middle of parsing an expression (where it's impractical to switch to
1891 /// parsing a different function), for instance, if it's constexpr in C++11
1892 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1893 bool canDelayFunctionBody(const Declarator &D);
1895 /// \brief Determine whether we can skip parsing the body of a function
1896 /// definition, assuming we don't care about analyzing its body or emitting
1897 /// code for that function.
1899 /// This will be \c false only if we may need the body of the function in
1900 /// order to parse the rest of the program (for instance, if it is
1901 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1902 bool canSkipFunctionBody(Decl *D);
1904 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1905 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1906 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1907 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1908 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1910 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1911 /// attribute for which parsing is delayed.
1912 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1914 /// \brief Diagnose any unused parameters in the given sequence of
1915 /// ParmVarDecl pointers.
1916 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1918 /// \brief Diagnose whether the size of parameters or return value of a
1919 /// function or obj-c method definition is pass-by-value and larger than a
1920 /// specified threshold.
1922 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1923 QualType ReturnTy, NamedDecl *D);
1925 void DiagnoseInvalidJumps(Stmt *Body);
1926 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1927 SourceLocation AsmLoc,
1928 SourceLocation RParenLoc);
1930 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1931 Decl *ActOnEmptyDeclaration(Scope *S,
1932 AttributeList *AttrList,
1933 SourceLocation SemiLoc);
1935 enum class ModuleDeclKind {
1936 Module, ///< 'module X;'
1937 Partition, ///< 'module partition X;'
1938 Implementation, ///< 'module implementation X;'
1941 /// The parser has processed a module-declaration that begins the definition
1942 /// of a module interface or implementation.
1943 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
1944 SourceLocation ModuleLoc, ModuleDeclKind MDK,
1947 /// \brief The parser has processed a module import declaration.
1949 /// \param AtLoc The location of the '@' symbol, if any.
1951 /// \param ImportLoc The location of the 'import' keyword.
1953 /// \param Path The module access path.
1954 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1957 /// \brief The parser has processed a module import translated from a
1958 /// #include or similar preprocessing directive.
1959 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1960 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1962 /// \brief The parsed has entered a submodule.
1963 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1964 /// \brief The parser has left a submodule.
1965 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1967 /// \brief Create an implicit import of the given module at the given
1968 /// source location, for error recovery, if possible.
1970 /// This routine is typically used when an entity found by name lookup
1971 /// is actually hidden within a module that we know about but the user
1972 /// has forgotten to import.
1973 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1976 /// Kinds of missing import. Note, the values of these enumerators correspond
1977 /// to %select values in diagnostics.
1978 enum class MissingImportKind {
1982 ExplicitSpecialization,
1983 PartialSpecialization
1986 /// \brief Diagnose that the specified declaration needs to be visible but
1987 /// isn't, and suggest a module import that would resolve the problem.
1988 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1989 MissingImportKind MIK, bool Recover = true);
1990 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1991 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1992 MissingImportKind MIK, bool Recover);
1994 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1995 SourceLocation LBraceLoc);
1996 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1997 SourceLocation RBraceLoc);
1999 /// \brief We've found a use of a templated declaration that would trigger an
2000 /// implicit instantiation. Check that any relevant explicit specializations
2001 /// and partial specializations are visible, and diagnose if not.
2002 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2004 /// \brief We've found a use of a template specialization that would select a
2005 /// partial specialization. Check that the partial specialization is visible,
2006 /// and diagnose if not.
2007 void checkPartialSpecializationVisibility(SourceLocation Loc,
2010 /// \brief Retrieve a suitable printing policy.
2011 PrintingPolicy getPrintingPolicy() const {
2012 return getPrintingPolicy(Context, PP);
2015 /// \brief Retrieve a suitable printing policy.
2016 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2017 const Preprocessor &PP);
2020 void ActOnPopScope(SourceLocation Loc, Scope *S);
2021 void ActOnTranslationUnitScope(Scope *S);
2023 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2024 RecordDecl *&AnonRecord);
2025 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2026 MultiTemplateParamsArg TemplateParams,
2027 bool IsExplicitInstantiation,
2028 RecordDecl *&AnonRecord);
2030 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2033 const PrintingPolicy &Policy);
2035 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2036 RecordDecl *Record);
2038 /// Common ways to introduce type names without a tag for use in diagnostics.
2039 /// Keep in sync with err_tag_reference_non_tag.
2048 NTK_TypeAliasTemplate,
2049 NTK_TemplateTemplateArgument,
2052 /// Given a non-tag type declaration, returns an enum useful for indicating
2053 /// what kind of non-tag type this is.
2054 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2056 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2057 TagTypeKind NewTag, bool isDefinition,
2058 SourceLocation NewTagLoc,
2059 const IdentifierInfo *Name);
2062 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2063 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2064 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2065 TUK_Friend // Friend declaration: 'friend struct foo;'
2068 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2069 SourceLocation KWLoc, CXXScopeSpec &SS,
2070 IdentifierInfo *Name, SourceLocation NameLoc,
2071 AttributeList *Attr, AccessSpecifier AS,
2072 SourceLocation ModulePrivateLoc,
2073 MultiTemplateParamsArg TemplateParameterLists,
2074 bool &OwnedDecl, bool &IsDependent,
2075 SourceLocation ScopedEnumKWLoc,
2076 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2077 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2079 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2080 unsigned TagSpec, SourceLocation TagLoc,
2082 IdentifierInfo *Name, SourceLocation NameLoc,
2083 AttributeList *Attr,
2084 MultiTemplateParamsArg TempParamLists);
2086 TypeResult ActOnDependentTag(Scope *S,
2089 const CXXScopeSpec &SS,
2090 IdentifierInfo *Name,
2091 SourceLocation TagLoc,
2092 SourceLocation NameLoc);
2094 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2095 IdentifierInfo *ClassName,
2096 SmallVectorImpl<Decl *> &Decls);
2097 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2098 Declarator &D, Expr *BitfieldWidth);
2100 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2101 Declarator &D, Expr *BitfieldWidth,
2102 InClassInitStyle InitStyle,
2103 AccessSpecifier AS);
2104 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2105 SourceLocation DeclStart,
2106 Declarator &D, Expr *BitfieldWidth,
2107 InClassInitStyle InitStyle,
2109 AttributeList *MSPropertyAttr);
2111 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2112 TypeSourceInfo *TInfo,
2113 RecordDecl *Record, SourceLocation Loc,
2114 bool Mutable, Expr *BitfieldWidth,
2115 InClassInitStyle InitStyle,
2116 SourceLocation TSSL,
2117 AccessSpecifier AS, NamedDecl *PrevDecl,
2118 Declarator *D = nullptr);
2120 bool CheckNontrivialField(FieldDecl *FD);
2121 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2122 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2123 bool Diagnose = false);
2124 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2125 void ActOnLastBitfield(SourceLocation DeclStart,
2126 SmallVectorImpl<Decl *> &AllIvarDecls);
2127 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2128 Declarator &D, Expr *BitfieldWidth,
2129 tok::ObjCKeywordKind visibility);
2131 // This is used for both record definitions and ObjC interface declarations.
2132 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2133 ArrayRef<Decl *> Fields,
2134 SourceLocation LBrac, SourceLocation RBrac,
2135 AttributeList *AttrList);
2137 /// ActOnTagStartDefinition - Invoked when we have entered the
2138 /// scope of a tag's definition (e.g., for an enumeration, class,
2139 /// struct, or union).
2140 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2142 typedef void *SkippedDefinitionContext;
2144 /// \brief Invoked when we enter a tag definition that we're skipping.
2145 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2147 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2149 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2150 /// C++ record definition's base-specifiers clause and are starting its
2151 /// member declarations.
2152 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2153 SourceLocation FinalLoc,
2154 bool IsFinalSpelledSealed,
2155 SourceLocation LBraceLoc);
2157 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2158 /// the definition of a tag (enumeration, class, struct, or union).
2159 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2160 SourceRange BraceRange);
2162 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2164 void ActOnObjCContainerFinishDefinition();
2166 /// \brief Invoked when we must temporarily exit the objective-c container
2167 /// scope for parsing/looking-up C constructs.
2169 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2170 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2171 void ActOnObjCReenterContainerContext(DeclContext *DC);
2173 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2174 /// error parsing the definition of a tag.
2175 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2177 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2178 EnumConstantDecl *LastEnumConst,
2179 SourceLocation IdLoc,
2182 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2183 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2184 QualType EnumUnderlyingTy,
2185 bool EnumUnderlyingIsImplicit,
2186 const EnumDecl *Prev);
2188 /// Determine whether the body of an anonymous enumeration should be skipped.
2189 /// \param II The name of the first enumerator.
2190 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2191 SourceLocation IILoc);
2193 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2194 SourceLocation IdLoc, IdentifierInfo *Id,
2195 AttributeList *Attrs,
2196 SourceLocation EqualLoc, Expr *Val);
2197 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2199 ArrayRef<Decl *> Elements,
2200 Scope *S, AttributeList *Attr);
2202 DeclContext *getContainingDC(DeclContext *DC);
2204 /// Set the current declaration context until it gets popped.
2205 void PushDeclContext(Scope *S, DeclContext *DC);
2206 void PopDeclContext();
2208 /// EnterDeclaratorContext - Used when we must lookup names in the context
2209 /// of a declarator's nested name specifier.
2210 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2211 void ExitDeclaratorContext(Scope *S);
2213 /// Push the parameters of D, which must be a function, into scope.
2214 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2215 void ActOnExitFunctionContext();
2217 DeclContext *getFunctionLevelDeclContext();
2219 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2220 /// to the function decl for the function being parsed. If we're currently
2221 /// in a 'block', this returns the containing context.
2222 FunctionDecl *getCurFunctionDecl();
2224 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2225 /// the method decl for the method being parsed. If we're currently
2226 /// in a 'block', this returns the containing context.
2227 ObjCMethodDecl *getCurMethodDecl();
2229 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2230 /// or C function we're in, otherwise return null. If we're currently
2231 /// in a 'block', this returns the containing context.
2232 NamedDecl *getCurFunctionOrMethodDecl();
2234 /// Add this decl to the scope shadowed decl chains.
2235 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2237 /// \brief Make the given externally-produced declaration visible at the
2238 /// top level scope.
2240 /// \param D The externally-produced declaration to push.
2242 /// \param Name The name of the externally-produced declaration.
2243 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2245 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2246 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2247 /// true if 'D' belongs to the given declaration context.
2249 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2250 /// enclosing namespace set of the context, rather than contained
2251 /// directly within it.
2252 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2253 bool AllowInlineNamespace = false);
2255 /// Finds the scope corresponding to the given decl context, if it
2256 /// happens to be an enclosing scope. Otherwise return NULL.
2257 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2259 /// Subroutines of ActOnDeclarator().
2260 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2261 TypeSourceInfo *TInfo);
2262 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2264 /// \brief Describes the kind of merge to perform for availability
2265 /// attributes (including "deprecated", "unavailable", and "availability").
2266 enum AvailabilityMergeKind {
2267 /// \brief Don't merge availability attributes at all.
2269 /// \brief Merge availability attributes for a redeclaration, which requires
2272 /// \brief Merge availability attributes for an override, which requires
2273 /// an exact match or a weakening of constraints.
2275 /// \brief Merge availability attributes for an implementation of
2276 /// a protocol requirement.
2277 AMK_ProtocolImplementation,
2280 /// Attribute merging methods. Return true if a new attribute was added.
2281 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2282 IdentifierInfo *Platform,
2284 VersionTuple Introduced,
2285 VersionTuple Deprecated,
2286 VersionTuple Obsoleted,
2289 bool IsStrict, StringRef Replacement,
2290 AvailabilityMergeKind AMK,
2291 unsigned AttrSpellingListIndex);
2292 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2293 TypeVisibilityAttr::VisibilityType Vis,
2294 unsigned AttrSpellingListIndex);
2295 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2296 VisibilityAttr::VisibilityType Vis,
2297 unsigned AttrSpellingListIndex);
2298 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2299 unsigned AttrSpellingListIndex, StringRef Uuid);
2300 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2301 unsigned AttrSpellingListIndex);
2302 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2303 unsigned AttrSpellingListIndex);
2305 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2306 unsigned AttrSpellingListIndex,
2307 MSInheritanceAttr::Spelling SemanticSpelling);
2308 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2309 IdentifierInfo *Format, int FormatIdx,
2310 int FirstArg, unsigned AttrSpellingListIndex);
2311 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2312 unsigned AttrSpellingListIndex);
2313 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2314 IdentifierInfo *Ident,
2315 unsigned AttrSpellingListIndex);
2316 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2317 unsigned AttrSpellingListIndex);
2318 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2319 unsigned AttrSpellingListIndex);
2320 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2321 IdentifierInfo *Ident,
2322 unsigned AttrSpellingListIndex);
2323 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2324 unsigned AttrSpellingListIndex);
2326 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2327 AvailabilityMergeKind AMK = AMK_Redeclaration);
2328 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2329 LookupResult &OldDecls);
2330 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2331 bool MergeTypeWithOld);
2332 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2333 Scope *S, bool MergeTypeWithOld);
2334 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2335 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2336 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2337 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2338 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2339 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2341 // AssignmentAction - This is used by all the assignment diagnostic functions
2342 // to represent what is actually causing the operation
2343 enum AssignmentAction {
2351 AA_Passing_CFAudited
2354 /// C++ Overloading.
2356 /// This is a legitimate overload: the existing declarations are
2357 /// functions or function templates with different signatures.
2360 /// This is not an overload because the signature exactly matches
2361 /// an existing declaration.
2364 /// This is not an overload because the lookup results contain a
2368 OverloadKind CheckOverload(Scope *S,
2370 const LookupResult &OldDecls,
2371 NamedDecl *&OldDecl,
2372 bool IsForUsingDecl);
2373 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2374 bool ConsiderCudaAttrs = true);
2376 /// \brief Checks availability of the function depending on the current
2377 /// function context.Inside an unavailable function,unavailability is ignored.
2379 /// \returns true if \p FD is unavailable and current context is inside
2380 /// an available function, false otherwise.
2381 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2383 ImplicitConversionSequence
2384 TryImplicitConversion(Expr *From, QualType ToType,
2385 bool SuppressUserConversions,
2387 bool InOverloadResolution,
2389 bool AllowObjCWritebackConversion);
2391 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2392 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2393 bool IsComplexPromotion(QualType FromType, QualType ToType);
2394 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2395 bool InOverloadResolution,
2396 QualType& ConvertedType, bool &IncompatibleObjC);
2397 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2398 QualType& ConvertedType, bool &IncompatibleObjC);
2399 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2400 QualType &ConvertedType);
2401 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2402 QualType& ConvertedType);
2403 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2404 const FunctionProtoType *NewType,
2405 unsigned *ArgPos = nullptr);
2406 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2407 QualType FromType, QualType ToType);
2409 void maybeExtendBlockObject(ExprResult &E);
2410 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2411 bool CheckPointerConversion(Expr *From, QualType ToType,
2413 CXXCastPath& BasePath,
2414 bool IgnoreBaseAccess,
2415 bool Diagnose = true);
2416 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2417 bool InOverloadResolution,
2418 QualType &ConvertedType);
2419 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2421 CXXCastPath &BasePath,
2422 bool IgnoreBaseAccess);
2423 bool IsQualificationConversion(QualType FromType, QualType ToType,
2424 bool CStyle, bool &ObjCLifetimeConversion);
2425 bool IsFunctionConversion(QualType FromType, QualType ToType,
2426 QualType &ResultTy);
2427 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2428 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2430 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2431 const VarDecl *NRVOCandidate,
2432 QualType ResultType,
2434 bool AllowNRVO = true);
2436 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2438 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2439 SourceLocation EqualLoc,
2441 bool TopLevelOfInitList = false,
2442 bool AllowExplicit = false);
2443 ExprResult PerformObjectArgumentInitialization(Expr *From,
2444 NestedNameSpecifier *Qualifier,
2445 NamedDecl *FoundDecl,
2446 CXXMethodDecl *Method);
2448 ExprResult PerformContextuallyConvertToBool(Expr *From);
2449 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2451 /// Contexts in which a converted constant expression is required.
2453 CCEK_CaseValue, ///< Expression in a case label.
2454 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2455 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2456 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2457 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2459 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2460 llvm::APSInt &Value, CCEKind CCE);
2461 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2462 APValue &Value, CCEKind CCE);
2464 /// \brief Abstract base class used to perform a contextual implicit
2465 /// conversion from an expression to any type passing a filter.
2466 class ContextualImplicitConverter {
2469 bool SuppressConversion;
2471 ContextualImplicitConverter(bool Suppress = false,
2472 bool SuppressConversion = false)
2473 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2475 /// \brief Determine whether the specified type is a valid destination type
2476 /// for this conversion.
2477 virtual bool match(QualType T) = 0;
2479 /// \brief Emits a diagnostic complaining that the expression does not have
2480 /// integral or enumeration type.
2481 virtual SemaDiagnosticBuilder
2482 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2484 /// \brief Emits a diagnostic when the expression has incomplete class type.
2485 virtual SemaDiagnosticBuilder
2486 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2488 /// \brief Emits a diagnostic when the only matching conversion function
2490 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2491 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2493 /// \brief Emits a note for the explicit conversion function.
2494 virtual SemaDiagnosticBuilder
2495 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2497 /// \brief Emits a diagnostic when there are multiple possible conversion
2499 virtual SemaDiagnosticBuilder
2500 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2502 /// \brief Emits a note for one of the candidate conversions.
2503 virtual SemaDiagnosticBuilder
2504 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2506 /// \brief Emits a diagnostic when we picked a conversion function
2507 /// (for cases when we are not allowed to pick a conversion function).
2508 virtual SemaDiagnosticBuilder diagnoseConversion(
2509 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2511 virtual ~ContextualImplicitConverter() {}
2514 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2515 bool AllowScopedEnumerations;
2518 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2519 bool Suppress, bool SuppressConversion)
2520 : ContextualImplicitConverter(Suppress, SuppressConversion),
2521 AllowScopedEnumerations(AllowScopedEnumerations) {}
2523 /// Match an integral or (possibly scoped) enumeration type.
2524 bool match(QualType T) override;
2526 SemaDiagnosticBuilder
2527 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2528 return diagnoseNotInt(S, Loc, T);
2531 /// \brief Emits a diagnostic complaining that the expression does not have
2532 /// integral or enumeration type.
2533 virtual SemaDiagnosticBuilder
2534 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2537 /// Perform a contextual implicit conversion.
2538 ExprResult PerformContextualImplicitConversion(
2539 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2542 enum ObjCSubscriptKind {
2547 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2549 // Note that LK_String is intentionally after the other literals, as
2550 // this is used for diagnostics logic.
2551 enum ObjCLiteralKind {
2560 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2562 ExprResult PerformObjectMemberConversion(Expr *From,
2563 NestedNameSpecifier *Qualifier,
2564 NamedDecl *FoundDecl,
2567 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2568 // TODO: make this is a typesafe union.
2569 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2570 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2572 void AddOverloadCandidate(FunctionDecl *Function,
2573 DeclAccessPair FoundDecl,
2574 ArrayRef<Expr *> Args,
2575 OverloadCandidateSet &CandidateSet,
2576 bool SuppressUserConversions = false,
2577 bool PartialOverloading = false,
2578 bool AllowExplicit = false,
2579 ConversionSequenceList EarlyConversions = None);
2580 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2581 ArrayRef<Expr *> Args,
2582 OverloadCandidateSet &CandidateSet,
2583 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2584 bool SuppressUserConversions = false,
2585 bool PartialOverloading = false);
2586 void AddMethodCandidate(DeclAccessPair FoundDecl,
2587 QualType ObjectType,
2588 Expr::Classification ObjectClassification,
2589 ArrayRef<Expr *> Args,
2590 OverloadCandidateSet& CandidateSet,
2591 bool SuppressUserConversion = false);
2592 void AddMethodCandidate(CXXMethodDecl *Method,
2593 DeclAccessPair FoundDecl,
2594 CXXRecordDecl *ActingContext, QualType ObjectType,
2595 Expr::Classification ObjectClassification,
2596 ArrayRef<Expr *> Args,
2597 OverloadCandidateSet& CandidateSet,
2598 bool SuppressUserConversions = false,
2599 bool PartialOverloading = false,
2600 ConversionSequenceList EarlyConversions = None);
2601 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2602 DeclAccessPair FoundDecl,
2603 CXXRecordDecl *ActingContext,
2604 TemplateArgumentListInfo *ExplicitTemplateArgs,
2605 QualType ObjectType,
2606 Expr::Classification ObjectClassification,
2607 ArrayRef<Expr *> Args,
2608 OverloadCandidateSet& CandidateSet,
2609 bool SuppressUserConversions = false,
2610 bool PartialOverloading = false);
2611 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2612 DeclAccessPair FoundDecl,
2613 TemplateArgumentListInfo *ExplicitTemplateArgs,
2614 ArrayRef<Expr *> Args,
2615 OverloadCandidateSet& CandidateSet,
2616 bool SuppressUserConversions = false,
2617 bool PartialOverloading = false);
2618 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2619 ArrayRef<QualType> ParamTypes,
2620 ArrayRef<Expr *> Args,
2621 OverloadCandidateSet &CandidateSet,
2622 ConversionSequenceList &Conversions,
2623 bool SuppressUserConversions,
2624 CXXRecordDecl *ActingContext = nullptr,
2625 QualType ObjectType = QualType(),
2626 Expr::Classification
2627 ObjectClassification = {});
2628 void AddConversionCandidate(CXXConversionDecl *Conversion,
2629 DeclAccessPair FoundDecl,
2630 CXXRecordDecl *ActingContext,
2631 Expr *From, QualType ToType,
2632 OverloadCandidateSet& CandidateSet,
2633 bool AllowObjCConversionOnExplicit);
2634 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2635 DeclAccessPair FoundDecl,
2636 CXXRecordDecl *ActingContext,
2637 Expr *From, QualType ToType,
2638 OverloadCandidateSet &CandidateSet,
2639 bool AllowObjCConversionOnExplicit);
2640 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2641 DeclAccessPair FoundDecl,
2642 CXXRecordDecl *ActingContext,
2643 const FunctionProtoType *Proto,
2644 Expr *Object, ArrayRef<Expr *> Args,
2645 OverloadCandidateSet& CandidateSet);
2646 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2647 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2648 OverloadCandidateSet& CandidateSet,
2649 SourceRange OpRange = SourceRange());
2650 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2651 ArrayRef<Expr *> Args,
2652 OverloadCandidateSet& CandidateSet,
2653 bool IsAssignmentOperator = false,
2654 unsigned NumContextualBoolArguments = 0);
2655 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2656 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2657 OverloadCandidateSet& CandidateSet);
2658 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2660 ArrayRef<Expr *> Args,
2661 TemplateArgumentListInfo *ExplicitTemplateArgs,
2662 OverloadCandidateSet& CandidateSet,
2663 bool PartialOverloading = false);
2665 // Emit as a 'note' the specific overload candidate
2666 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2667 QualType DestType = QualType(),
2668 bool TakingAddress = false);
2670 // Emit as a series of 'note's all template and non-templates identified by
2671 // the expression Expr
2672 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2673 bool TakingAddress = false);
2675 /// Check the enable_if expressions on the given function. Returns the first
2676 /// failing attribute, or NULL if they were all successful.
2677 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2678 bool MissingImplicitThis = false);
2680 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2681 /// non-ArgDependent DiagnoseIfAttrs.
2683 /// Argument-dependent diagnose_if attributes should be checked each time a
2684 /// function is used as a direct callee of a function call.
2686 /// Returns true if any errors were emitted.
2687 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2688 const Expr *ThisArg,
2689 ArrayRef<const Expr *> Args,
2690 SourceLocation Loc);
2692 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2693 /// ArgDependent DiagnoseIfAttrs.
2695 /// Argument-independent diagnose_if attributes should be checked on every use
2698 /// Returns true if any errors were emitted.
2699 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2700 SourceLocation Loc);
2702 /// Returns whether the given function's address can be taken or not,
2703 /// optionally emitting a diagnostic if the address can't be taken.
2705 /// Returns false if taking the address of the function is illegal.
2706 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2707 bool Complain = false,
2708 SourceLocation Loc = SourceLocation());
2710 // [PossiblyAFunctionType] --> [Return]
2711 // NonFunctionType --> NonFunctionType
2713 // R (*)(A) --> R (A)
2714 // R (&)(A) --> R (A)
2715 // R (S::*)(A) --> R (A)
2716 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2719 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2720 QualType TargetType,
2722 DeclAccessPair &Found,
2723 bool *pHadMultipleCandidates = nullptr);
2726 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2727 DeclAccessPair &FoundResult);
2729 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2732 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2733 bool Complain = false,
2734 DeclAccessPair *Found = nullptr);
2736 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2737 ExprResult &SrcExpr,
2738 bool DoFunctionPointerConverion = false,
2739 bool Complain = false,
2740 SourceRange OpRangeForComplaining = SourceRange(),
2741 QualType DestTypeForComplaining = QualType(),
2742 unsigned DiagIDForComplaining = 0);
2745 Expr *FixOverloadedFunctionReference(Expr *E,
2746 DeclAccessPair FoundDecl,
2748 ExprResult FixOverloadedFunctionReference(ExprResult,
2749 DeclAccessPair FoundDecl,
2752 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2753 ArrayRef<Expr *> Args,
2754 OverloadCandidateSet &CandidateSet,
2755 bool PartialOverloading = false);
2757 // An enum used to represent the different possible results of building a
2758 // range-based for loop.
2759 enum ForRangeStatus {
2761 FRS_NoViableFunction,
2762 FRS_DiagnosticIssued
2765 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2766 SourceLocation RangeLoc,
2767 const DeclarationNameInfo &NameInfo,
2768 LookupResult &MemberLookup,
2769 OverloadCandidateSet *CandidateSet,
2770 Expr *Range, ExprResult *CallExpr);
2772 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2773 UnresolvedLookupExpr *ULE,
2774 SourceLocation LParenLoc,
2776 SourceLocation RParenLoc,
2778 bool AllowTypoCorrection=true,
2779 bool CalleesAddressIsTaken=false);
2781 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2782 MultiExprArg Args, SourceLocation RParenLoc,
2783 OverloadCandidateSet *CandidateSet,
2784 ExprResult *Result);
2786 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2787 UnaryOperatorKind Opc,
2788 const UnresolvedSetImpl &Fns,
2791 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2792 BinaryOperatorKind Opc,
2793 const UnresolvedSetImpl &Fns,
2794 Expr *LHS, Expr *RHS);
2796 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2797 SourceLocation RLoc,
2798 Expr *Base,Expr *Idx);
2801 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2802 SourceLocation LParenLoc,
2804 SourceLocation RParenLoc);
2806 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2808 SourceLocation RParenLoc);
2810 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2811 SourceLocation OpLoc,
2812 bool *NoArrowOperatorFound = nullptr);
2814 /// CheckCallReturnType - Checks that a call expression's return type is
2815 /// complete. Returns true on failure. The location passed in is the location
2816 /// that best represents the call.
2817 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2818 CallExpr *CE, FunctionDecl *FD);
2820 /// Helpers for dealing with blocks and functions.
2821 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2822 bool CheckParameterNames);
2823 void CheckCXXDefaultArguments(FunctionDecl *FD);
2824 void CheckExtraCXXDefaultArguments(Declarator &D);
2825 Scope *getNonFieldDeclScope(Scope *S);
2827 /// \name Name lookup
2829 /// These routines provide name lookup that is used during semantic
2830 /// analysis to resolve the various kinds of names (identifiers,
2831 /// overloaded operator names, constructor names, etc.) into zero or
2832 /// more declarations within a particular scope. The major entry
2833 /// points are LookupName, which performs unqualified name lookup,
2834 /// and LookupQualifiedName, which performs qualified name lookup.
2836 /// All name lookup is performed based on some specific criteria,
2837 /// which specify what names will be visible to name lookup and how
2838 /// far name lookup should work. These criteria are important both
2839 /// for capturing language semantics (certain lookups will ignore
2840 /// certain names, for example) and for performance, since name
2841 /// lookup is often a bottleneck in the compilation of C++. Name
2842 /// lookup criteria is specified via the LookupCriteria enumeration.
2844 /// The results of name lookup can vary based on the kind of name
2845 /// lookup performed, the current language, and the translation
2846 /// unit. In C, for example, name lookup will either return nothing
2847 /// (no entity found) or a single declaration. In C++, name lookup
2848 /// can additionally refer to a set of overloaded functions or
2849 /// result in an ambiguity. All of the possible results of name
2850 /// lookup are captured by the LookupResult class, which provides
2851 /// the ability to distinguish among them.
2854 /// @brief Describes the kind of name lookup to perform.
2855 enum LookupNameKind {
2856 /// Ordinary name lookup, which finds ordinary names (functions,
2857 /// variables, typedefs, etc.) in C and most kinds of names
2858 /// (functions, variables, members, types, etc.) in C++.
2859 LookupOrdinaryName = 0,
2860 /// Tag name lookup, which finds the names of enums, classes,
2861 /// structs, and unions.
2863 /// Label name lookup.
2865 /// Member name lookup, which finds the names of
2866 /// class/struct/union members.
2868 /// Look up of an operator name (e.g., operator+) for use with
2869 /// operator overloading. This lookup is similar to ordinary name
2870 /// lookup, but will ignore any declarations that are class members.
2872 /// Look up of a name that precedes the '::' scope resolution
2873 /// operator in C++. This lookup completely ignores operator, object,
2874 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2875 LookupNestedNameSpecifierName,
2876 /// Look up a namespace name within a C++ using directive or
2877 /// namespace alias definition, ignoring non-namespace names (C++
2878 /// [basic.lookup.udir]p1).
2879 LookupNamespaceName,
2880 /// Look up all declarations in a scope with the given name,
2881 /// including resolved using declarations. This is appropriate
2882 /// for checking redeclarations for a using declaration.
2883 LookupUsingDeclName,
2884 /// Look up an ordinary name that is going to be redeclared as a
2885 /// name with linkage. This lookup ignores any declarations that
2886 /// are outside of the current scope unless they have linkage. See
2887 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2888 LookupRedeclarationWithLinkage,
2889 /// Look up a friend of a local class. This lookup does not look
2890 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2891 LookupLocalFriendName,
2892 /// Look up the name of an Objective-C protocol.
2893 LookupObjCProtocolName,
2894 /// Look up implicit 'self' parameter of an objective-c method.
2895 LookupObjCImplicitSelfParam,
2896 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2897 LookupOMPReductionName,
2898 /// \brief Look up any declaration with any name.
2902 /// \brief Specifies whether (or how) name lookup is being performed for a
2903 /// redeclaration (vs. a reference).
2904 enum RedeclarationKind {
2905 /// \brief The lookup is a reference to this name that is not for the
2906 /// purpose of redeclaring the name.
2907 NotForRedeclaration = 0,
2908 /// \brief The lookup results will be used for redeclaration of a name,
2909 /// if an entity by that name already exists.
2913 /// \brief The possible outcomes of name lookup for a literal operator.
2914 enum LiteralOperatorLookupResult {
2915 /// \brief The lookup resulted in an error.
2917 /// \brief The lookup found a single 'cooked' literal operator, which
2918 /// expects a normal literal to be built and passed to it.
2920 /// \brief The lookup found a single 'raw' literal operator, which expects
2921 /// a string literal containing the spelling of the literal token.
2923 /// \brief The lookup found an overload set of literal operator templates,
2924 /// which expect the characters of the spelling of the literal token to be
2925 /// passed as a non-type template argument pack.
2927 /// \brief The lookup found an overload set of literal operator templates,
2928 /// which expect the character type and characters of the spelling of the
2929 /// string literal token to be passed as template arguments.
2933 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2934 CXXSpecialMember SM,
2941 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2942 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2943 TypoRecoveryCallback;
2946 bool CppLookupName(LookupResult &R, Scope *S);
2948 struct TypoExprState {
2949 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2950 TypoDiagnosticGenerator DiagHandler;
2951 TypoRecoveryCallback RecoveryHandler;
2953 TypoExprState(TypoExprState &&other) noexcept;
2954 TypoExprState &operator=(TypoExprState &&other) noexcept;
2957 /// \brief The set of unhandled TypoExprs and their associated state.
2958 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2960 /// \brief Creates a new TypoExpr AST node.
2961 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2962 TypoDiagnosticGenerator TDG,
2963 TypoRecoveryCallback TRC);
2965 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2967 // The boolean value will be true to indicate that the namespace was loaded
2968 // from an AST/PCH file, or false otherwise.
2969 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2971 /// \brief Whether we have already loaded known namespaces from an extenal
2973 bool LoadedExternalKnownNamespaces;
2975 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2976 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2977 /// should be skipped entirely.
2978 std::unique_ptr<TypoCorrectionConsumer>
2979 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2980 Sema::LookupNameKind LookupKind, Scope *S,
2982 std::unique_ptr<CorrectionCandidateCallback> CCC,
2983 DeclContext *MemberContext, bool EnteringContext,
2984 const ObjCObjectPointerType *OPT,
2985 bool ErrorRecovery);
2988 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2990 /// \brief Clears the state of the given TypoExpr.
2991 void clearDelayedTypo(TypoExpr *TE);
2993 /// \brief Look up a name, looking for a single declaration. Return
2994 /// null if the results were absent, ambiguous, or overloaded.
2996 /// It is preferable to use the elaborated form and explicitly handle
2997 /// ambiguity and overloaded.
2998 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3000 LookupNameKind NameKind,
3001 RedeclarationKind Redecl
3002 = NotForRedeclaration);
3003 bool LookupName(LookupResult &R, Scope *S,
3004 bool AllowBuiltinCreation = false);
3005 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3006 bool InUnqualifiedLookup = false);
3007 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3009 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3010 bool AllowBuiltinCreation = false,
3011 bool EnteringContext = false);
3012 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3013 RedeclarationKind Redecl
3014 = NotForRedeclaration);
3015 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3017 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3018 QualType T1, QualType T2,
3019 UnresolvedSetImpl &Functions);
3021 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3022 SourceLocation GnuLabelLoc = SourceLocation());
3024 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3025 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3026 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3028 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3029 bool RValueThis, unsigned ThisQuals);
3030 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3032 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3033 bool RValueThis, unsigned ThisQuals);
3034 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3036 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3037 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3038 ArrayRef<QualType> ArgTys,
3041 bool AllowStringTemplate);
3042 bool isKnownName(StringRef name);
3044 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3045 ArrayRef<Expr *> Args, ADLResult &Functions);
3047 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3048 VisibleDeclConsumer &Consumer,
3049 bool IncludeGlobalScope = true);
3050 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3051 VisibleDeclConsumer &Consumer,
3052 bool IncludeGlobalScope = true);
3054 enum CorrectTypoKind {
3055 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3056 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3059 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3060 Sema::LookupNameKind LookupKind,
3061 Scope *S, CXXScopeSpec *SS,
3062 std::unique_ptr<CorrectionCandidateCallback> CCC,
3063 CorrectTypoKind Mode,
3064 DeclContext *MemberContext = nullptr,
3065 bool EnteringContext = false,
3066 const ObjCObjectPointerType *OPT = nullptr,
3067 bool RecordFailure = true);
3069 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3070 Sema::LookupNameKind LookupKind, Scope *S,
3072 std::unique_ptr<CorrectionCandidateCallback> CCC,
3073 TypoDiagnosticGenerator TDG,
3074 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3075 DeclContext *MemberContext = nullptr,
3076 bool EnteringContext = false,
3077 const ObjCObjectPointerType *OPT = nullptr);
3079 /// \brief Process any TypoExprs in the given Expr and its children,
3080 /// generating diagnostics as appropriate and returning a new Expr if there
3081 /// were typos that were all successfully corrected and ExprError if one or
3082 /// more typos could not be corrected.
3084 /// \param E The Expr to check for TypoExprs.
3086 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3089 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3090 /// it is an acceptable/usable result from a single combination of typo
3091 /// corrections. As long as the filter returns ExprError, different
3092 /// combinations of corrections will be tried until all are exhausted.
3094 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3095 llvm::function_ref<ExprResult(Expr *)> Filter =
3096 [](Expr *E) -> ExprResult { return E; });
3099 CorrectDelayedTyposInExpr(Expr *E,
3100 llvm::function_ref<ExprResult(Expr *)> Filter) {
3101 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3105 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3106 llvm::function_ref<ExprResult(Expr *)> Filter =
3107 [](Expr *E) -> ExprResult { return E; }) {
3108 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3112 CorrectDelayedTyposInExpr(ExprResult ER,
3113 llvm::function_ref<ExprResult(Expr *)> Filter) {
3114 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3117 void diagnoseTypo(const TypoCorrection &Correction,
3118 const PartialDiagnostic &TypoDiag,
3119 bool ErrorRecovery = true);
3121 void diagnoseTypo(const TypoCorrection &Correction,
3122 const PartialDiagnostic &TypoDiag,
3123 const PartialDiagnostic &PrevNote,
3124 bool ErrorRecovery = true);
3126 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3128 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3129 ArrayRef<Expr *> Args,
3130 AssociatedNamespaceSet &AssociatedNamespaces,
3131 AssociatedClassSet &AssociatedClasses);
3133 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3134 bool ConsiderLinkage, bool AllowInlineNamespace);
3136 void DiagnoseAmbiguousLookup(LookupResult &Result);
3139 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3140 SourceLocation IdLoc,
3141 bool TypoCorrection = false);
3142 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3143 Scope *S, bool ForRedeclaration,
3144 SourceLocation Loc);
3145 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3147 void AddKnownFunctionAttributes(FunctionDecl *FD);
3149 // More parsing and symbol table subroutines.
3151 void ProcessPragmaWeak(Scope *S, Decl *D);
3152 // Decl attributes - this routine is the top level dispatcher.
3153 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3154 // Helper for delayed proccessing of attributes.
3155 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3156 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3157 bool IncludeCXX11Attributes = true);
3158 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3159 const AttributeList *AttrList);
3161 void checkUnusedDeclAttributes(Declarator &D);
3163 /// Determine if type T is a valid subject for a nonnull and similar
3164 /// attributes. By default, we look through references (the behavior used by
3165 /// nonnull), but if the second parameter is true, then we treat a reference
3167 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3169 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3170 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3171 const FunctionDecl *FD = nullptr);
3172 bool CheckNoReturnAttr(const AttributeList &attr);
3173 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3174 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3175 unsigned ArgNum, StringRef &Str,
3176 SourceLocation *ArgLocation = nullptr);
3177 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3178 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3179 bool checkMSInheritanceAttrOnDefinition(
3180 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3181 MSInheritanceAttr::Spelling SemanticSpelling);
3183 void CheckAlignasUnderalignment(Decl *D);
3185 /// Adjust the calling convention of a method to be the ABI default if it
3186 /// wasn't specified explicitly. This handles method types formed from
3187 /// function type typedefs and typename template arguments.
3188 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3189 SourceLocation Loc);
3191 // Check if there is an explicit attribute, but only look through parens.
3192 // The intent is to look for an attribute on the current declarator, but not
3193 // one that came from a typedef.
3194 bool hasExplicitCallingConv(QualType &T);
3196 /// Get the outermost AttributedType node that sets a calling convention.
3197 /// Valid types should not have multiple attributes with different CCs.
3198 const AttributedType *getCallingConvAttributedType(QualType T) const;
3200 /// Check whether a nullability type specifier can be added to the given
3203 /// \param type The type to which the nullability specifier will be
3204 /// added. On success, this type will be updated appropriately.
3206 /// \param nullability The nullability specifier to add.
3208 /// \param nullabilityLoc The location of the nullability specifier.
3210 /// \param isContextSensitive Whether this nullability specifier was
3211 /// written as a context-sensitive keyword (in an Objective-C
3212 /// method) or an Objective-C property attribute, rather than as an
3213 /// underscored type specifier.
3215 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3216 /// array type (e.g., because it will decay to a pointer).
3218 /// \returns true if nullability cannot be applied, false otherwise.
3219 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3220 SourceLocation nullabilityLoc,
3221 bool isContextSensitive,
3222 bool allowArrayTypes);
3224 /// \brief Stmt attributes - this routine is the top level dispatcher.
3225 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3228 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3229 ObjCMethodDecl *MethodDecl,
3230 bool IsProtocolMethodDecl);
3232 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3233 ObjCMethodDecl *Overridden,
3234 bool IsProtocolMethodDecl);
3236 /// WarnExactTypedMethods - This routine issues a warning if method
3237 /// implementation declaration matches exactly that of its declaration.
3238 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3239 ObjCMethodDecl *MethodDecl,
3240 bool IsProtocolMethodDecl);
3242 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3244 /// CheckImplementationIvars - This routine checks if the instance variables
3245 /// listed in the implelementation match those listed in the interface.
3246 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3247 ObjCIvarDecl **Fields, unsigned nIvars,
3248 SourceLocation Loc);
3250 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3251 /// remains unimplemented in the class or category \@implementation.
3252 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3253 ObjCContainerDecl* IDecl,
3254 bool IncompleteImpl = false);
3256 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3257 /// which must be implemented by this implementation.
3258 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3259 ObjCContainerDecl *CDecl,
3260 bool SynthesizeProperties);
3262 /// Diagnose any null-resettable synthesized setters.
3263 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3265 /// DefaultSynthesizeProperties - This routine default synthesizes all
3266 /// properties which must be synthesized in the class's \@implementation.
3267 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3268 ObjCInterfaceDecl *IDecl);
3269 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3271 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3272 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3273 /// declared in class 'IFace'.
3274 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3275 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3277 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3278 /// backs the property is not used in the property's accessor.
3279 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3280 const ObjCImplementationDecl *ImplD);
3282 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3283 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3284 /// It also returns ivar's property on success.
3285 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3286 const ObjCPropertyDecl *&PDecl) const;
3288 /// Called by ActOnProperty to handle \@property declarations in
3289 /// class extensions.
3290 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3291 SourceLocation AtLoc,
3292 SourceLocation LParenLoc,
3293 FieldDeclarator &FD,
3295 SourceLocation GetterNameLoc,
3297 SourceLocation SetterNameLoc,
3298 const bool isReadWrite,
3299 unsigned &Attributes,
3300 const unsigned AttributesAsWritten,
3302 TypeSourceInfo *TSI,
3303 tok::ObjCKeywordKind MethodImplKind);
3305 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3306 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3307 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3308 ObjCContainerDecl *CDecl,
3309 SourceLocation AtLoc,
3310 SourceLocation LParenLoc,
3311 FieldDeclarator &FD,
3313 SourceLocation GetterNameLoc,
3315 SourceLocation SetterNameLoc,
3316 const bool isReadWrite,
3317 const unsigned Attributes,
3318 const unsigned AttributesAsWritten,
3320 TypeSourceInfo *TSI,
3321 tok::ObjCKeywordKind MethodImplKind,
3322 DeclContext *lexicalDC = nullptr);
3324 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3325 /// warning) when atomic property has one but not the other user-declared
3326 /// setter or getter.
3327 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3328 ObjCInterfaceDecl* IDecl);
3330 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3332 void DiagnoseMissingDesignatedInitOverrides(
3333 const ObjCImplementationDecl *ImplD,
3334 const ObjCInterfaceDecl *IFD);
3336 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3338 enum MethodMatchStrategy {
3343 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3344 /// true, or false, accordingly.
3345 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3346 const ObjCMethodDecl *PrevMethod,
3347 MethodMatchStrategy strategy = MMS_strict);
3349 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3350 /// or protocol against those declared in their implementations.
3351 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3352 const SelectorSet &ClsMap,
3353 SelectorSet &InsMapSeen,
3354 SelectorSet &ClsMapSeen,
3355 ObjCImplDecl* IMPDecl,
3356 ObjCContainerDecl* IDecl,
3357 bool &IncompleteImpl,
3358 bool ImmediateClass,
3359 bool WarnCategoryMethodImpl=false);
3361 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3362 /// category matches with those implemented in its primary class and
3363 /// warns each time an exact match is found.
3364 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3366 /// \brief Add the given method to the list of globally-known methods.
3367 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3370 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3371 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3372 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3374 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3375 /// optionally warns if there are multiple signatures.
3376 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3377 bool receiverIdOrClass,
3381 /// \brief - Returns instance or factory methods in global method pool for
3382 /// given selector. It checks the desired kind first, if none is found, and
3383 /// parameter checkTheOther is set, it then checks the other kind. If no such
3384 /// method or only one method is found, function returns false; otherwise, it
3387 CollectMultipleMethodsInGlobalPool(Selector Sel,
3388 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3389 bool InstanceFirst, bool CheckTheOther,
3390 const ObjCObjectType *TypeBound = nullptr);
3393 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3394 SourceRange R, bool receiverIdOrClass,
3395 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3398 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3399 Selector Sel, SourceRange R,
3400 bool receiverIdOrClass);
3403 /// \brief - Returns a selector which best matches given argument list or
3404 /// nullptr if none could be found
3405 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3407 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3410 /// \brief Record the typo correction failure and return an empty correction.
3411 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3412 bool RecordFailure = true) {
3414 TypoCorrectionFailures[Typo].insert(TypoLoc);
3415 return TypoCorrection();
3419 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3420 /// unit are added to a global pool. This allows us to efficiently associate
3421 /// a selector with a method declaraation for purposes of typechecking
3422 /// messages sent to "id" (where the class of the object is unknown).
3423 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3424 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3427 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3428 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3429 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3432 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3434 void AddAnyMethodToGlobalPool(Decl *D);
3436 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3437 /// there are multiple signatures.
3438 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3439 bool receiverIdOrClass=false) {
3440 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3444 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3445 /// there are multiple signatures.
3446 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3447 bool receiverIdOrClass=false) {
3448 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3452 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3453 QualType ObjectType=QualType());
3454 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3456 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3458 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3460 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3461 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3463 //===--------------------------------------------------------------------===//
3464 // Statement Parsing Callbacks: SemaStmt.cpp.
3468 FullExprArg() : E(nullptr) { }
3469 FullExprArg(Sema &actions) : E(nullptr) { }
3471 ExprResult release() {
3475 Expr *get() const { return E; }
3477 Expr *operator->() {
3482 // FIXME: No need to make the entire Sema class a friend when it's just
3483 // Sema::MakeFullExpr that needs access to the constructor below.
3486 explicit FullExprArg(Expr *expr) : E(expr) {}
3491 FullExprArg MakeFullExpr(Expr *Arg) {
3492 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3494 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3495 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3497 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3499 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3500 /*DiscardedValue*/ true);
3501 return FullExprArg(FE.get());
3504 StmtResult ActOnExprStmt(ExprResult Arg);
3505 StmtResult ActOnExprStmtError();
3507 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3508 bool HasLeadingEmptyMacro = false);
3510 void ActOnStartOfCompoundStmt();
3511 void ActOnFinishOfCompoundStmt();
3512 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3513 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3515 /// \brief A RAII object to enter scope of a compound statement.
3516 class CompoundScopeRAII {
3518 CompoundScopeRAII(Sema &S): S(S) {
3519 S.ActOnStartOfCompoundStmt();
3522 ~CompoundScopeRAII() {
3523 S.ActOnFinishOfCompoundStmt();
3530 /// An RAII helper that pops function a function scope on exit.
3531 struct FunctionScopeRAII {
3534 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3535 ~FunctionScopeRAII() {
3537 S.PopFunctionScopeInfo();
3539 void disable() { Active = false; }
3542 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3543 SourceLocation StartLoc,
3544 SourceLocation EndLoc);
3545 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3546 StmtResult ActOnForEachLValueExpr(Expr *E);
3547 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3548 SourceLocation DotDotDotLoc, Expr *RHSVal,
3549 SourceLocation ColonLoc);
3550 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3552 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3553 SourceLocation ColonLoc,
3554 Stmt *SubStmt, Scope *CurScope);
3555 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3556 SourceLocation ColonLoc, Stmt *SubStmt);
3558 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3559 ArrayRef<const Attr*> Attrs,
3562 class ConditionResult;
3563 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3565 ConditionResult Cond, Stmt *ThenVal,
3566 SourceLocation ElseLoc, Stmt *ElseVal);
3567 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3569 ConditionResult Cond, Stmt *ThenVal,
3570 SourceLocation ElseLoc, Stmt *ElseVal);
3571 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3573 ConditionResult Cond);
3574 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3575 Stmt *Switch, Stmt *Body);
3576 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3578 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3579 SourceLocation WhileLoc, SourceLocation CondLParen,
3580 Expr *Cond, SourceLocation CondRParen);
3582 StmtResult ActOnForStmt(SourceLocation ForLoc,
3583 SourceLocation LParenLoc,
3585 ConditionResult Second,
3587 SourceLocation RParenLoc,
3589 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3591 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3592 Stmt *First, Expr *collection,
3593 SourceLocation RParenLoc);
3594 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3596 enum BuildForRangeKind {
3597 /// Initial building of a for-range statement.
3599 /// Instantiation or recovery rebuild of a for-range statement. Don't
3600 /// attempt any typo-correction.
3602 /// Determining whether a for-range statement could be built. Avoid any
3603 /// unnecessary or irreversible actions.
3607 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3608 SourceLocation CoawaitLoc,
3610 SourceLocation ColonLoc, Expr *Collection,
3611 SourceLocation RParenLoc,
3612 BuildForRangeKind Kind);
3613 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3614 SourceLocation CoawaitLoc,
3615 SourceLocation ColonLoc,
3616 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3617 Expr *Cond, Expr *Inc,
3619 SourceLocation RParenLoc,
3620 BuildForRangeKind Kind);
3621 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3623 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3624 SourceLocation LabelLoc,
3625 LabelDecl *TheDecl);
3626 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3627 SourceLocation StarLoc,
3629 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3630 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3632 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3633 CapturedRegionKind Kind, unsigned NumParams);
3634 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3635 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3636 CapturedRegionKind Kind,
3637 ArrayRef<CapturedParamNameType> Params);
3638 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3639 void ActOnCapturedRegionError();
3640 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3642 unsigned NumParams);
3643 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3644 bool AllowParamOrMoveConstructible);
3645 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3646 bool AllowParamOrMoveConstructible);
3648 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3650 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3651 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3653 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3654 bool IsVolatile, unsigned NumOutputs,
3655 unsigned NumInputs, IdentifierInfo **Names,
3656 MultiExprArg Constraints, MultiExprArg Exprs,
3657 Expr *AsmString, MultiExprArg Clobbers,
3658 SourceLocation RParenLoc);
3660 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3661 SourceLocation TemplateKWLoc,
3663 llvm::InlineAsmIdentifierInfo &Info,
3664 bool IsUnevaluatedContext);
3665 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3666 unsigned &Offset, SourceLocation AsmLoc);
3667 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3668 llvm::InlineAsmIdentifierInfo &Info,
3669 SourceLocation AsmLoc);
3670 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3671 ArrayRef<Token> AsmToks,
3672 StringRef AsmString,
3673 unsigned NumOutputs, unsigned NumInputs,
3674 ArrayRef<StringRef> Constraints,
3675 ArrayRef<StringRef> Clobbers,
3676 ArrayRef<Expr*> Exprs,
3677 SourceLocation EndLoc);
3678 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3679 SourceLocation Location,
3682 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3683 SourceLocation StartLoc,
3684 SourceLocation IdLoc, IdentifierInfo *Id,
3685 bool Invalid = false);
3687 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3689 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3690 Decl *Parm, Stmt *Body);
3692 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3694 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3695 MultiStmtArg Catch, Stmt *Finally);
3697 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3698 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3700 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3702 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3706 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3708 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3709 SourceLocation StartLoc,
3710 SourceLocation IdLoc,
3711 IdentifierInfo *Id);
3713 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3715 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3716 Decl *ExDecl, Stmt *HandlerBlock);
3717 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3718 ArrayRef<Stmt *> Handlers);
3720 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3721 SourceLocation TryLoc, Stmt *TryBlock,
3723 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3726 void ActOnStartSEHFinallyBlock();
3727 void ActOnAbortSEHFinallyBlock();
3728 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3729 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3731 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3733 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3735 /// \brief If it's a file scoped decl that must warn if not used, keep track
3737 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3739 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3740 /// whose result is unused, warn.
3741 void DiagnoseUnusedExprResult(const Stmt *S);
3742 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3743 void DiagnoseUnusedDecl(const NamedDecl *ND);
3745 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3746 /// statement as a \p Body, and it is located on the same line.
3748 /// This helps prevent bugs due to typos, such as:
3751 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3755 /// Warn if a for/while loop statement \p S, which is followed by
3756 /// \p PossibleBody, has a suspicious null statement as a body.
3757 void DiagnoseEmptyLoopBody(const Stmt *S,
3758 const Stmt *PossibleBody);
3760 /// Warn if a value is moved to itself.
3761 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3762 SourceLocation OpLoc);
3764 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3766 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3767 SourceLocation Loc);
3769 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3770 return DelayedDiagnostics.push(pool);
3772 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3774 typedef ProcessingContextState ParsingClassState;
3775 ParsingClassState PushParsingClass() {
3776 return DelayedDiagnostics.pushUndelayed();
3778 void PopParsingClass(ParsingClassState state) {
3779 DelayedDiagnostics.popUndelayed(state);
3782 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3784 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3785 StringRef Message, SourceLocation Loc,
3786 const ObjCInterfaceDecl *UnknownObjCClass,
3787 const ObjCPropertyDecl *ObjCProperty,
3788 bool ObjCPropertyAccess);
3790 bool makeUnavailableInSystemHeader(SourceLocation loc,
3791 UnavailableAttr::ImplicitReason reason);
3793 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3794 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3796 //===--------------------------------------------------------------------===//
3797 // Expression Parsing Callbacks: SemaExpr.cpp.
3799 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3800 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3801 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3802 bool ObjCPropertyAccess=false);
3803 void NoteDeletedFunction(FunctionDecl *FD);
3804 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3805 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3806 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3807 ObjCMethodDecl *Getter,
3808 SourceLocation Loc);
3809 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3810 ArrayRef<Expr *> Args);
3812 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3813 Decl *LambdaContextDecl = nullptr,
3814 bool IsDecltype = false);
3815 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3816 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3817 ReuseLambdaContextDecl_t,
3818 bool IsDecltype = false);
3819 void PopExpressionEvaluationContext();
3821 void DiscardCleanupsInEvaluationContext();
3823 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3824 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3826 ExprResult ActOnConstantExpression(ExprResult Res);
3828 // Functions for marking a declaration referenced. These functions also
3829 // contain the relevant logic for marking if a reference to a function or
3830 // variable is an odr-use (in the C++11 sense). There are separate variants
3831 // for expressions referring to a decl; these exist because odr-use marking
3832 // needs to be delayed for some constant variables when we build one of the
3833 // named expressions.
3835 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3836 // should usually be true. This only needs to be set to false if the lack of
3837 // odr-use cannot be determined from the current context (for instance,
3838 // because the name denotes a virtual function and was written without an
3839 // explicit nested-name-specifier).
3840 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3841 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3842 bool MightBeOdrUse = true);
3843 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3844 void MarkDeclRefReferenced(DeclRefExpr *E);
3845 void MarkMemberReferenced(MemberExpr *E);
3847 void UpdateMarkingForLValueToRValue(Expr *E);
3848 void CleanupVarDeclMarking();
3850 enum TryCaptureKind {
3851 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3854 /// \brief Try to capture the given variable.
3856 /// \param Var The variable to capture.
3858 /// \param Loc The location at which the capture occurs.
3860 /// \param Kind The kind of capture, which may be implicit (for either a
3861 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3863 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3864 /// an explicit lambda capture.
3866 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3867 /// captures or diagnose errors. If false, this routine merely check whether
3868 /// the capture can occur without performing the capture itself or complaining
3869 /// if the variable cannot be captured.
3871 /// \param CaptureType Will be set to the type of the field used to capture
3872 /// this variable in the innermost block or lambda. Only valid when the
3873 /// variable can be captured.
3875 /// \param DeclRefType Will be set to the type of a reference to the capture
3876 /// from within the current scope. Only valid when the variable can be
3879 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3880 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3881 /// This is useful when enclosing lambdas must speculatively capture
3882 /// variables that may or may not be used in certain specializations of
3883 /// a nested generic lambda.
3885 /// \returns true if an error occurred (i.e., the variable cannot be
3886 /// captured) and false if the capture succeeded.
3887 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3888 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3889 QualType &CaptureType,
3890 QualType &DeclRefType,
3891 const unsigned *const FunctionScopeIndexToStopAt);
3893 /// \brief Try to capture the given variable.
3894 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3895 TryCaptureKind Kind = TryCapture_Implicit,
3896 SourceLocation EllipsisLoc = SourceLocation());
3898 /// \brief Checks if the variable must be captured.
3899 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3901 /// \brief Given a variable, determine the type that a reference to that
3902 /// variable will have in the given scope.
3903 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3905 /// Mark all of the declarations referenced within a particular AST node as
3906 /// referenced. Used when template instantiation instantiates a non-dependent
3907 /// type -- entities referenced by the type are now referenced.
3908 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3909 void MarkDeclarationsReferencedInExpr(Expr *E,
3910 bool SkipLocalVariables = false);
3912 /// \brief Try to recover by turning the given expression into a
3913 /// call. Returns true if recovery was attempted or an error was
3914 /// emitted; this may also leave the ExprResult invalid.
3915 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3916 bool ForceComplain = false,
3917 bool (*IsPlausibleResult)(QualType) = nullptr);
3919 /// \brief Figure out if an expression could be turned into a call.
3920 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3921 UnresolvedSetImpl &NonTemplateOverloads);
3923 /// \brief Conditionally issue a diagnostic based on the current
3924 /// evaluation context.
3926 /// \param Statement If Statement is non-null, delay reporting the
3927 /// diagnostic until the function body is parsed, and then do a basic
3928 /// reachability analysis to determine if the statement is reachable.
3929 /// If it is unreachable, the diagnostic will not be emitted.
3930 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3931 const PartialDiagnostic &PD);
3933 // Primary Expressions.
3934 SourceRange getExprRange(Expr *E) const;
3936 ExprResult ActOnIdExpression(
3937 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3938 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3939 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3940 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3942 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3943 TemplateArgumentListInfo &Buffer,
3944 DeclarationNameInfo &NameInfo,
3945 const TemplateArgumentListInfo *&TemplateArgs);
3948 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3949 std::unique_ptr<CorrectionCandidateCallback> CCC,
3950 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3951 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3953 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3955 bool AllowBuiltinCreation=false);
3957 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3958 SourceLocation TemplateKWLoc,
3959 const DeclarationNameInfo &NameInfo,
3960 bool isAddressOfOperand,
3961 const TemplateArgumentListInfo *TemplateArgs);
3963 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3966 const CXXScopeSpec *SS = nullptr);
3968 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3969 const DeclarationNameInfo &NameInfo,
3970 const CXXScopeSpec *SS = nullptr,
3971 NamedDecl *FoundD = nullptr,
3972 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3974 BuildAnonymousStructUnionMemberReference(
3975 const CXXScopeSpec &SS,
3976 SourceLocation nameLoc,
3977 IndirectFieldDecl *indirectField,
3978 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3979 Expr *baseObjectExpr = nullptr,
3980 SourceLocation opLoc = SourceLocation());
3982 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3983 SourceLocation TemplateKWLoc,
3985 const TemplateArgumentListInfo *TemplateArgs,
3987 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3988 SourceLocation TemplateKWLoc,
3990 const TemplateArgumentListInfo *TemplateArgs,
3991 bool IsDefiniteInstance,
3993 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3994 const LookupResult &R,
3995 bool HasTrailingLParen);
3998 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3999 const DeclarationNameInfo &NameInfo,
4000 bool IsAddressOfOperand, const Scope *S,
4001 TypeSourceInfo **RecoveryTSI = nullptr);
4003 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4004 SourceLocation TemplateKWLoc,
4005 const DeclarationNameInfo &NameInfo,
4006 const TemplateArgumentListInfo *TemplateArgs);
4008 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4011 bool AcceptInvalidDecl = false);
4012 ExprResult BuildDeclarationNameExpr(
4013 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4014 NamedDecl *FoundD = nullptr,
4015 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4016 bool AcceptInvalidDecl = false);
4018 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4019 DeclarationNameInfo &SuffixInfo,
4020 ArrayRef<Expr *> Args,
4021 SourceLocation LitEndLoc,
4022 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4024 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4025 PredefinedExpr::IdentType IT);
4026 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4027 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4029 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4031 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4032 ExprResult ActOnCharacterConstant(const Token &Tok,
4033 Scope *UDLScope = nullptr);
4034 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4035 ExprResult ActOnParenListExpr(SourceLocation L,
4039 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4040 /// fragments (e.g. "foo" "bar" L"baz").
4041 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4042 Scope *UDLScope = nullptr);
4044 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4045 SourceLocation DefaultLoc,
4046 SourceLocation RParenLoc,
4047 Expr *ControllingExpr,
4048 ArrayRef<ParsedType> ArgTypes,
4049 ArrayRef<Expr *> ArgExprs);
4050 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4051 SourceLocation DefaultLoc,
4052 SourceLocation RParenLoc,
4053 Expr *ControllingExpr,
4054 ArrayRef<TypeSourceInfo *> Types,
4055 ArrayRef<Expr *> Exprs);
4057 // Binary/Unary Operators. 'Tok' is the token for the operator.
4058 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4060 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4061 UnaryOperatorKind Opc, Expr *Input);
4062 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4063 tok::TokenKind Op, Expr *Input);
4065 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4067 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4068 SourceLocation OpLoc,
4069 UnaryExprOrTypeTrait ExprKind,
4071 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4072 UnaryExprOrTypeTrait ExprKind);
4074 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4075 UnaryExprOrTypeTrait ExprKind,
4076 bool IsType, void *TyOrEx,
4077 SourceRange ArgRange);
4079 ExprResult CheckPlaceholderExpr(Expr *E);
4080 bool CheckVecStepExpr(Expr *E);
4082 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4083 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4084 SourceRange ExprRange,
4085 UnaryExprOrTypeTrait ExprKind);
4086 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4087 SourceLocation OpLoc,
4088 IdentifierInfo &Name,
4089 SourceLocation NameLoc,
4090 SourceLocation RParenLoc);
4091 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4092 tok::TokenKind Kind, Expr *Input);
4094 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4095 Expr *Idx, SourceLocation RLoc);
4096 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4097 Expr *Idx, SourceLocation RLoc);
4098 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4099 Expr *LowerBound, SourceLocation ColonLoc,
4100 Expr *Length, SourceLocation RBLoc);
4102 // This struct is for use by ActOnMemberAccess to allow
4103 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4104 // changing the access operator from a '.' to a '->' (to see if that is the
4105 // change needed to fix an error about an unknown member, e.g. when the class
4106 // defines a custom operator->).
4107 struct ActOnMemberAccessExtraArgs {
4113 ExprResult BuildMemberReferenceExpr(
4114 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4115 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4116 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4117 const TemplateArgumentListInfo *TemplateArgs,
4119 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4122 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4123 bool IsArrow, const CXXScopeSpec &SS,
4124 SourceLocation TemplateKWLoc,
4125 NamedDecl *FirstQualifierInScope, LookupResult &R,
4126 const TemplateArgumentListInfo *TemplateArgs,
4128 bool SuppressQualifierCheck = false,
4129 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4131 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4132 SourceLocation OpLoc,
4133 const CXXScopeSpec &SS, FieldDecl *Field,
4134 DeclAccessPair FoundDecl,
4135 const DeclarationNameInfo &MemberNameInfo);
4137 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4139 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4140 const CXXScopeSpec &SS,
4141 const LookupResult &R);
4143 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4144 bool IsArrow, SourceLocation OpLoc,
4145 const CXXScopeSpec &SS,
4146 SourceLocation TemplateKWLoc,
4147 NamedDecl *FirstQualifierInScope,
4148 const DeclarationNameInfo &NameInfo,
4149 const TemplateArgumentListInfo *TemplateArgs);
4151 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4152 SourceLocation OpLoc,
4153 tok::TokenKind OpKind,
4155 SourceLocation TemplateKWLoc,
4156 UnqualifiedId &Member,
4159 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4160 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4161 FunctionDecl *FDecl,
4162 const FunctionProtoType *Proto,
4163 ArrayRef<Expr *> Args,
4164 SourceLocation RParenLoc,
4165 bool ExecConfig = false);
4166 void CheckStaticArrayArgument(SourceLocation CallLoc,
4168 const Expr *ArgExpr);
4170 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4171 /// This provides the location of the left/right parens and a list of comma
4173 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4174 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4175 Expr *ExecConfig = nullptr,
4176 bool IsExecConfig = false);
4177 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4178 SourceLocation LParenLoc,
4179 ArrayRef<Expr *> Arg,
4180 SourceLocation RParenLoc,
4181 Expr *Config = nullptr,
4182 bool IsExecConfig = false);
4184 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4185 MultiExprArg ExecConfig,
4186 SourceLocation GGGLoc);
4188 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4189 Declarator &D, ParsedType &Ty,
4190 SourceLocation RParenLoc, Expr *CastExpr);
4191 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4193 SourceLocation RParenLoc,
4195 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4197 /// \brief Build an altivec or OpenCL literal.
4198 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4199 SourceLocation RParenLoc, Expr *E,
4200 TypeSourceInfo *TInfo);
4202 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4204 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4206 SourceLocation RParenLoc,
4209 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4210 TypeSourceInfo *TInfo,
4211 SourceLocation RParenLoc,
4214 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4215 MultiExprArg InitArgList,
4216 SourceLocation RBraceLoc);
4218 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4224 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4227 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4228 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4229 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4230 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4231 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4232 Expr *LHSExpr, Expr *RHSExpr);
4234 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4236 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4237 /// in the case of a the GNU conditional expr extension.
4238 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4239 SourceLocation ColonLoc,
4240 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4242 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4243 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4244 LabelDecl *TheDecl);
4246 void ActOnStartStmtExpr();
4247 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4248 SourceLocation RPLoc); // "({..})"
4249 void ActOnStmtExprError();
4251 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4252 struct OffsetOfComponent {
4253 SourceLocation LocStart, LocEnd;
4254 bool isBrackets; // true if [expr], false if .ident
4256 IdentifierInfo *IdentInfo;
4261 /// __builtin_offsetof(type, a.b[123][456].c)
4262 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4263 TypeSourceInfo *TInfo,
4264 ArrayRef<OffsetOfComponent> Components,
4265 SourceLocation RParenLoc);
4266 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4267 SourceLocation BuiltinLoc,
4268 SourceLocation TypeLoc,
4269 ParsedType ParsedArgTy,
4270 ArrayRef<OffsetOfComponent> Components,
4271 SourceLocation RParenLoc);
4273 // __builtin_choose_expr(constExpr, expr1, expr2)
4274 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4275 Expr *CondExpr, Expr *LHSExpr,
4276 Expr *RHSExpr, SourceLocation RPLoc);
4278 // __builtin_va_arg(expr, type)
4279 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4280 SourceLocation RPLoc);
4281 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4282 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4285 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4287 bool CheckCaseExpression(Expr *E);
4289 /// \brief Describes the result of an "if-exists" condition check.
4290 enum IfExistsResult {
4291 /// \brief The symbol exists.
4294 /// \brief The symbol does not exist.
4297 /// \brief The name is a dependent name, so the results will differ
4298 /// from one instantiation to the next.
4301 /// \brief An error occurred.
4306 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4307 const DeclarationNameInfo &TargetNameInfo);
4310 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4311 bool IsIfExists, CXXScopeSpec &SS,
4312 UnqualifiedId &Name);
4314 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4316 NestedNameSpecifierLoc QualifierLoc,
4317 DeclarationNameInfo NameInfo,
4319 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4321 CXXScopeSpec &SS, UnqualifiedId &Name,
4324 //===------------------------- "Block" Extension ------------------------===//
4326 /// ActOnBlockStart - This callback is invoked when a block literal is
4328 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4330 /// ActOnBlockArguments - This callback allows processing of block arguments.
4331 /// If there are no arguments, this is still invoked.
4332 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4335 /// ActOnBlockError - If there is an error parsing a block, this callback
4336 /// is invoked to pop the information about the block from the action impl.
4337 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4339 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4340 /// literal was successfully completed. ^(int x){...}
4341 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4344 //===---------------------------- Clang Extensions ----------------------===//
4346 /// __builtin_convertvector(...)
4347 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4348 SourceLocation BuiltinLoc,
4349 SourceLocation RParenLoc);
4351 //===---------------------------- OpenCL Features -----------------------===//
4353 /// __builtin_astype(...)
4354 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4355 SourceLocation BuiltinLoc,
4356 SourceLocation RParenLoc);
4358 //===---------------------------- C++ Features --------------------------===//
4360 // Act on C++ namespaces
4361 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4362 SourceLocation NamespaceLoc,
4363 SourceLocation IdentLoc,
4364 IdentifierInfo *Ident,
4365 SourceLocation LBrace,
4366 AttributeList *AttrList,
4367 UsingDirectiveDecl * &UsingDecl);
4368 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4370 NamespaceDecl *getStdNamespace() const;
4371 NamespaceDecl *getOrCreateStdNamespace();
4373 NamespaceDecl *lookupStdExperimentalNamespace();
4375 CXXRecordDecl *getStdBadAlloc() const;
4376 EnumDecl *getStdAlignValT() const;
4378 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4379 /// it is and Element is not NULL, assigns the element type to Element.
4380 bool isStdInitializerList(QualType Ty, QualType *Element);
4382 /// \brief Looks for the std::initializer_list template and instantiates it
4383 /// with Element, or emits an error if it's not found.
4385 /// \returns The instantiated template, or null on error.
4386 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4388 /// \brief Determine whether Ctor is an initializer-list constructor, as
4389 /// defined in [dcl.init.list]p2.
4390 bool isInitListConstructor(const FunctionDecl *Ctor);
4392 Decl *ActOnUsingDirective(Scope *CurScope,
4393 SourceLocation UsingLoc,
4394 SourceLocation NamespcLoc,
4396 SourceLocation IdentLoc,
4397 IdentifierInfo *NamespcName,
4398 AttributeList *AttrList);
4400 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4402 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4403 SourceLocation NamespaceLoc,
4404 SourceLocation AliasLoc,
4405 IdentifierInfo *Alias,
4407 SourceLocation IdentLoc,
4408 IdentifierInfo *Ident);
4410 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4411 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4412 const LookupResult &PreviousDecls,
4413 UsingShadowDecl *&PrevShadow);
4414 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4416 UsingShadowDecl *PrevDecl);
4418 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4419 bool HasTypenameKeyword,
4420 const CXXScopeSpec &SS,
4421 SourceLocation NameLoc,
4422 const LookupResult &Previous);
4423 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4425 const CXXScopeSpec &SS,
4426 const DeclarationNameInfo &NameInfo,
4427 SourceLocation NameLoc);
4429 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4430 SourceLocation UsingLoc,
4431 bool HasTypenameKeyword,
4432 SourceLocation TypenameLoc,
4434 DeclarationNameInfo NameInfo,
4435 SourceLocation EllipsisLoc,
4436 AttributeList *AttrList,
4437 bool IsInstantiation);
4438 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4439 ArrayRef<NamedDecl *> Expansions);
4441 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4443 /// Given a derived-class using shadow declaration for a constructor and the
4444 /// correspnding base class constructor, find or create the implicit
4445 /// synthesized derived class constructor to use for this initialization.
4446 CXXConstructorDecl *
4447 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4448 ConstructorUsingShadowDecl *DerivedShadow);
4450 Decl *ActOnUsingDeclaration(Scope *CurScope,
4452 SourceLocation UsingLoc,
4453 SourceLocation TypenameLoc,
4455 UnqualifiedId &Name,
4456 SourceLocation EllipsisLoc,
4457 AttributeList *AttrList);
4458 Decl *ActOnAliasDeclaration(Scope *CurScope,
4460 MultiTemplateParamsArg TemplateParams,
4461 SourceLocation UsingLoc,
4462 UnqualifiedId &Name,
4463 AttributeList *AttrList,
4465 Decl *DeclFromDeclSpec);
4467 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4468 /// including handling of its default argument expressions.
4470 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4472 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4473 NamedDecl *FoundDecl,
4474 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4475 bool HadMultipleCandidates, bool IsListInitialization,
4476 bool IsStdInitListInitialization,
4477 bool RequiresZeroInit, unsigned ConstructKind,
4478 SourceRange ParenRange);
4480 /// Build a CXXConstructExpr whose constructor has already been resolved if
4481 /// it denotes an inherited constructor.
4483 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4484 CXXConstructorDecl *Constructor, bool Elidable,
4486 bool HadMultipleCandidates, bool IsListInitialization,
4487 bool IsStdInitListInitialization,
4488 bool RequiresZeroInit, unsigned ConstructKind,
4489 SourceRange ParenRange);
4491 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4492 // the constructor can be elidable?
4494 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4495 NamedDecl *FoundDecl,
4496 CXXConstructorDecl *Constructor, bool Elidable,
4497 MultiExprArg Exprs, bool HadMultipleCandidates,
4498 bool IsListInitialization,
4499 bool IsStdInitListInitialization, bool RequiresZeroInit,
4500 unsigned ConstructKind, SourceRange ParenRange);
4502 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4505 /// Instantiate or parse a C++ default argument expression as necessary.
4506 /// Return true on error.
4507 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4508 ParmVarDecl *Param);
4510 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4511 /// the default expr if needed.
4512 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4514 ParmVarDecl *Param);
4516 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4517 /// constructed variable.
4518 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4520 /// \brief Helper class that collects exception specifications for
4521 /// implicitly-declared special member functions.
4522 class ImplicitExceptionSpecification {
4523 // Pointer to allow copying
4525 // We order exception specifications thus:
4526 // noexcept is the most restrictive, but is only used in C++11.
4527 // throw() comes next.
4528 // Then a throw(collected exceptions)
4529 // Finally no specification, which is expressed as noexcept(false).
4530 // throw(...) is used instead if any called function uses it.
4531 ExceptionSpecificationType ComputedEST;
4532 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4533 SmallVector<QualType, 4> Exceptions;
4535 void ClearExceptions() {
4536 ExceptionsSeen.clear();
4541 explicit ImplicitExceptionSpecification(Sema &Self)
4542 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4543 if (!Self.getLangOpts().CPlusPlus11)
4544 ComputedEST = EST_DynamicNone;
4547 /// \brief Get the computed exception specification type.
4548 ExceptionSpecificationType getExceptionSpecType() const {
4549 assert(ComputedEST != EST_ComputedNoexcept &&
4550 "noexcept(expr) should not be a possible result");
4554 /// \brief The number of exceptions in the exception specification.
4555 unsigned size() const { return Exceptions.size(); }
4557 /// \brief The set of exceptions in the exception specification.
4558 const QualType *data() const { return Exceptions.data(); }
4560 /// \brief Integrate another called method into the collected data.
4561 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4563 /// \brief Integrate an invoked expression into the collected data.
4564 void CalledExpr(Expr *E);
4566 /// \brief Overwrite an EPI's exception specification with this
4567 /// computed exception specification.
4568 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4569 FunctionProtoType::ExceptionSpecInfo ESI;
4570 ESI.Type = getExceptionSpecType();
4571 if (ESI.Type == EST_Dynamic) {
4572 ESI.Exceptions = Exceptions;
4573 } else if (ESI.Type == EST_None) {
4574 /// C++11 [except.spec]p14:
4575 /// The exception-specification is noexcept(false) if the set of
4576 /// potential exceptions of the special member function contains "any"
4577 ESI.Type = EST_ComputedNoexcept;
4578 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4579 tok::kw_false).get();
4585 /// \brief Determine what sort of exception specification a defaulted
4586 /// copy constructor of a class will have.
4587 ImplicitExceptionSpecification
4588 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4591 /// \brief Determine what sort of exception specification a defaulted
4592 /// default constructor of a class will have, and whether the parameter
4594 ImplicitExceptionSpecification
4595 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4597 /// \brief Determine what sort of exception specification a defautled
4598 /// copy assignment operator of a class will have, and whether the
4599 /// parameter will be const.
4600 ImplicitExceptionSpecification
4601 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4603 /// \brief Determine what sort of exception specification a defaulted move
4604 /// constructor of a class will have.
4605 ImplicitExceptionSpecification
4606 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4608 /// \brief Determine what sort of exception specification a defaulted move
4609 /// assignment operator of a class will have.
4610 ImplicitExceptionSpecification
4611 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4613 /// \brief Determine what sort of exception specification a defaulted
4614 /// destructor of a class will have.
4615 ImplicitExceptionSpecification
4616 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4618 /// \brief Determine what sort of exception specification an inheriting
4619 /// constructor of a class will have.
4620 ImplicitExceptionSpecification
4621 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4622 CXXConstructorDecl *CD);
4624 /// \brief Evaluate the implicit exception specification for a defaulted
4625 /// special member function.
4626 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4628 /// \brief Check the given exception-specification and update the
4629 /// exception specification information with the results.
4630 void checkExceptionSpecification(bool IsTopLevel,
4631 ExceptionSpecificationType EST,
4632 ArrayRef<ParsedType> DynamicExceptions,
4633 ArrayRef<SourceRange> DynamicExceptionRanges,
4635 SmallVectorImpl<QualType> &Exceptions,
4636 FunctionProtoType::ExceptionSpecInfo &ESI);
4638 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4639 /// parse an exception specification to work around a libstdc++ bug.
4640 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4642 /// \brief Add an exception-specification to the given member function
4643 /// (or member function template). The exception-specification was parsed
4644 /// after the method itself was declared.
4645 void actOnDelayedExceptionSpecification(Decl *Method,
4646 ExceptionSpecificationType EST,
4647 SourceRange SpecificationRange,
4648 ArrayRef<ParsedType> DynamicExceptions,
4649 ArrayRef<SourceRange> DynamicExceptionRanges,
4650 Expr *NoexceptExpr);
4652 class InheritedConstructorInfo;
4654 /// \brief Determine if a special member function should have a deleted
4655 /// definition when it is defaulted.
4656 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4657 InheritedConstructorInfo *ICI = nullptr,
4658 bool Diagnose = false);
4660 /// \brief Declare the implicit default constructor for the given class.
4662 /// \param ClassDecl The class declaration into which the implicit
4663 /// default constructor will be added.
4665 /// \returns The implicitly-declared default constructor.
4666 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4667 CXXRecordDecl *ClassDecl);
4669 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4670 /// defining this constructor as the default constructor.
4671 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4672 CXXConstructorDecl *Constructor);
4674 /// \brief Declare the implicit destructor for the given class.
4676 /// \param ClassDecl The class declaration into which the implicit
4677 /// destructor will be added.
4679 /// \returns The implicitly-declared destructor.
4680 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4682 /// DefineImplicitDestructor - Checks for feasibility of
4683 /// defining this destructor as the default destructor.
4684 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4685 CXXDestructorDecl *Destructor);
4687 /// \brief Build an exception spec for destructors that don't have one.
4689 /// C++11 says that user-defined destructors with no exception spec get one
4690 /// that looks as if the destructor was implicitly declared.
4691 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4692 CXXDestructorDecl *Destructor);
4694 /// \brief Define the specified inheriting constructor.
4695 void DefineInheritingConstructor(SourceLocation UseLoc,
4696 CXXConstructorDecl *Constructor);
4698 /// \brief Declare the implicit copy constructor for the given class.
4700 /// \param ClassDecl The class declaration into which the implicit
4701 /// copy constructor will be added.
4703 /// \returns The implicitly-declared copy constructor.
4704 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4706 /// DefineImplicitCopyConstructor - Checks for feasibility of
4707 /// defining this constructor as the copy constructor.
4708 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4709 CXXConstructorDecl *Constructor);
4711 /// \brief Declare the implicit move constructor for the given class.
4713 /// \param ClassDecl The Class declaration into which the implicit
4714 /// move constructor will be added.
4716 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4718 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4720 /// DefineImplicitMoveConstructor - Checks for feasibility of
4721 /// defining this constructor as the move constructor.
4722 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4723 CXXConstructorDecl *Constructor);
4725 /// \brief Declare the implicit copy assignment operator for the given class.
4727 /// \param ClassDecl The class declaration into which the implicit
4728 /// copy assignment operator will be added.
4730 /// \returns The implicitly-declared copy assignment operator.
4731 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4733 /// \brief Defines an implicitly-declared copy assignment operator.
4734 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4735 CXXMethodDecl *MethodDecl);
4737 /// \brief Declare the implicit move assignment operator for the given class.
4739 /// \param ClassDecl The Class declaration into which the implicit
4740 /// move assignment operator will be added.
4742 /// \returns The implicitly-declared move assignment operator, or NULL if it
4743 /// wasn't declared.
4744 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4746 /// \brief Defines an implicitly-declared move assignment operator.
4747 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4748 CXXMethodDecl *MethodDecl);
4750 /// \brief Force the declaration of any implicitly-declared members of this
4752 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4754 /// \brief Check a completed declaration of an implicit special member.
4755 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4757 /// \brief Determine whether the given function is an implicitly-deleted
4758 /// special member function.
4759 bool isImplicitlyDeleted(FunctionDecl *FD);
4761 /// \brief Check whether 'this' shows up in the type of a static member
4762 /// function after the (naturally empty) cv-qualifier-seq would be.
4764 /// \returns true if an error occurred.
4765 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4767 /// \brief Whether this' shows up in the exception specification of a static
4768 /// member function.
4769 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4771 /// \brief Check whether 'this' shows up in the attributes of the given
4772 /// static member function.
4774 /// \returns true if an error occurred.
4775 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4777 /// MaybeBindToTemporary - If the passed in expression has a record type with
4778 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4779 /// it simply returns the passed in expression.
4780 ExprResult MaybeBindToTemporary(Expr *E);
4782 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4783 MultiExprArg ArgsPtr,
4785 SmallVectorImpl<Expr*> &ConvertedArgs,
4786 bool AllowExplicit = false,
4787 bool IsListInitialization = false);
4789 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4790 SourceLocation NameLoc,
4791 IdentifierInfo &Name);
4793 ParsedType getDestructorName(SourceLocation TildeLoc,
4794 IdentifierInfo &II, SourceLocation NameLoc,
4795 Scope *S, CXXScopeSpec &SS,
4796 ParsedType ObjectType,
4797 bool EnteringContext);
4799 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4800 ParsedType ObjectType);
4802 // Checks that reinterpret casts don't have undefined behavior.
4803 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4804 bool IsDereference, SourceRange Range);
4806 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4807 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4808 tok::TokenKind Kind,
4809 SourceLocation LAngleBracketLoc,
4811 SourceLocation RAngleBracketLoc,
4812 SourceLocation LParenLoc,
4814 SourceLocation RParenLoc);
4816 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4817 tok::TokenKind Kind,
4820 SourceRange AngleBrackets,
4821 SourceRange Parens);
4823 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4824 SourceLocation TypeidLoc,
4825 TypeSourceInfo *Operand,
4826 SourceLocation RParenLoc);
4827 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4828 SourceLocation TypeidLoc,
4830 SourceLocation RParenLoc);
4832 /// ActOnCXXTypeid - Parse typeid( something ).
4833 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4834 SourceLocation LParenLoc, bool isType,
4836 SourceLocation RParenLoc);
4838 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4839 SourceLocation TypeidLoc,
4840 TypeSourceInfo *Operand,
4841 SourceLocation RParenLoc);
4842 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4843 SourceLocation TypeidLoc,
4845 SourceLocation RParenLoc);
4847 /// ActOnCXXUuidof - Parse __uuidof( something ).
4848 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4849 SourceLocation LParenLoc, bool isType,
4851 SourceLocation RParenLoc);
4853 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4854 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4855 tok::TokenKind Operator,
4856 SourceLocation EllipsisLoc, Expr *RHS,
4857 SourceLocation RParenLoc);
4858 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4859 BinaryOperatorKind Operator,
4860 SourceLocation EllipsisLoc, Expr *RHS,
4861 SourceLocation RParenLoc);
4862 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4863 BinaryOperatorKind Operator);
4865 //// ActOnCXXThis - Parse 'this' pointer.
4866 ExprResult ActOnCXXThis(SourceLocation loc);
4868 /// \brief Try to retrieve the type of the 'this' pointer.
4870 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4871 QualType getCurrentThisType();
4873 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4874 /// current context not being a non-static member function. In such cases,
4875 /// this provides the type used for 'this'.
4876 QualType CXXThisTypeOverride;
4878 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4879 /// to be used, with the given qualifiers on the current class type.
4880 class CXXThisScopeRAII {
4882 QualType OldCXXThisTypeOverride;
4886 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4887 /// using the given declaration (which is either a class template or a
4888 /// class) along with the given qualifiers.
4889 /// along with the qualifiers placed on '*this'.
4890 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4891 bool Enabled = true);
4893 ~CXXThisScopeRAII();
4896 /// \brief Make sure the value of 'this' is actually available in the current
4897 /// context, if it is a potentially evaluated context.
4899 /// \param Loc The location at which the capture of 'this' occurs.
4901 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4904 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4905 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4906 /// This is useful when enclosing lambdas must speculatively capture
4907 /// 'this' that may or may not be used in certain specializations of
4908 /// a nested generic lambda (depending on whether the name resolves to
4909 /// a non-static member function or a static function).
4910 /// \return returns 'true' if failed, 'false' if success.
4911 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4912 bool BuildAndDiagnose = true,
4913 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4914 bool ByCopy = false);
4916 /// \brief Determine whether the given type is the type of *this that is used
4917 /// outside of the body of a member function for a type that is currently
4919 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4921 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4922 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4925 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4926 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4929 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4930 SourceLocation AtLoc, SourceLocation RParen);
4932 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4933 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4935 //// ActOnCXXThrow - Parse throw expressions.
4936 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4937 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4938 bool IsThrownVarInScope);
4939 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4941 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4942 /// Can be interpreted either as function-style casting ("int(x)")
4943 /// or class type construction ("ClassType(x,y,z)")
4944 /// or creation of a value-initialized type ("int()").
4945 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4946 SourceLocation LParenLoc,
4948 SourceLocation RParenLoc);
4950 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4951 SourceLocation LParenLoc,
4953 SourceLocation RParenLoc);
4955 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4956 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4957 SourceLocation PlacementLParen,
4958 MultiExprArg PlacementArgs,
4959 SourceLocation PlacementRParen,
4960 SourceRange TypeIdParens, Declarator &D,
4962 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4963 SourceLocation PlacementLParen,
4964 MultiExprArg PlacementArgs,
4965 SourceLocation PlacementRParen,
4966 SourceRange TypeIdParens,
4968 TypeSourceInfo *AllocTypeInfo,
4970 SourceRange DirectInitRange,
4973 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4975 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4976 bool UseGlobal, QualType AllocType, bool IsArray,
4977 bool &PassAlignment, MultiExprArg PlaceArgs,
4978 FunctionDecl *&OperatorNew,
4979 FunctionDecl *&OperatorDelete);
4980 void DeclareGlobalNewDelete();
4981 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4982 ArrayRef<QualType> Params);
4984 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4985 DeclarationName Name, FunctionDecl* &Operator,
4986 bool Diagnose = true);
4987 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4988 bool CanProvideSize,
4990 DeclarationName Name);
4991 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4994 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4995 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4996 bool UseGlobal, bool ArrayForm,
4998 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4999 bool IsDelete, bool CallCanBeVirtual,
5000 bool WarnOnNonAbstractTypes,
5001 SourceLocation DtorLoc);
5003 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5004 Expr *Operand, SourceLocation RParen);
5005 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5006 SourceLocation RParen);
5008 /// \brief Parsed one of the type trait support pseudo-functions.
5009 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5010 ArrayRef<ParsedType> Args,
5011 SourceLocation RParenLoc);
5012 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5013 ArrayRef<TypeSourceInfo *> Args,
5014 SourceLocation RParenLoc);
5016 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5017 /// pseudo-functions.
5018 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5019 SourceLocation KWLoc,
5022 SourceLocation RParen);
5024 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5025 SourceLocation KWLoc,
5026 TypeSourceInfo *TSInfo,
5028 SourceLocation RParen);
5030 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5031 /// pseudo-functions.
5032 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5033 SourceLocation KWLoc,
5035 SourceLocation RParen);
5037 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5038 SourceLocation KWLoc,
5040 SourceLocation RParen);
5042 ExprResult ActOnStartCXXMemberReference(Scope *S,
5044 SourceLocation OpLoc,
5045 tok::TokenKind OpKind,
5046 ParsedType &ObjectType,
5047 bool &MayBePseudoDestructor);
5049 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5050 SourceLocation OpLoc,
5051 tok::TokenKind OpKind,
5052 const CXXScopeSpec &SS,
5053 TypeSourceInfo *ScopeType,
5054 SourceLocation CCLoc,
5055 SourceLocation TildeLoc,
5056 PseudoDestructorTypeStorage DestroyedType);
5058 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5059 SourceLocation OpLoc,
5060 tok::TokenKind OpKind,
5062 UnqualifiedId &FirstTypeName,
5063 SourceLocation CCLoc,
5064 SourceLocation TildeLoc,
5065 UnqualifiedId &SecondTypeName);
5067 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5068 SourceLocation OpLoc,
5069 tok::TokenKind OpKind,
5070 SourceLocation TildeLoc,
5071 const DeclSpec& DS);
5073 /// MaybeCreateExprWithCleanups - If the current full-expression
5074 /// requires any cleanups, surround it with a ExprWithCleanups node.
5075 /// Otherwise, just returns the passed-in expression.
5076 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5077 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5078 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5080 MaterializeTemporaryExpr *
5081 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5082 bool BoundToLvalueReference);
5084 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5085 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5086 : SourceLocation());
5088 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5089 bool DiscardedValue = false,
5090 bool IsConstexpr = false,
5091 bool IsLambdaInitCaptureInitializer = false);
5092 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5094 // Marks SS invalid if it represents an incomplete type.
5095 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5097 DeclContext *computeDeclContext(QualType T);
5098 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5099 bool EnteringContext = false);
5100 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5101 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5103 /// \brief The parser has parsed a global nested-name-specifier '::'.
5105 /// \param CCLoc The location of the '::'.
5107 /// \param SS The nested-name-specifier, which will be updated in-place
5108 /// to reflect the parsed nested-name-specifier.
5110 /// \returns true if an error occurred, false otherwise.
5111 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5113 /// \brief The parser has parsed a '__super' nested-name-specifier.
5115 /// \param SuperLoc The location of the '__super' keyword.
5117 /// \param ColonColonLoc The location of the '::'.
5119 /// \param SS The nested-name-specifier, which will be updated in-place
5120 /// to reflect the parsed nested-name-specifier.
5122 /// \returns true if an error occurred, false otherwise.
5123 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5124 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5126 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5127 bool *CanCorrect = nullptr);
5128 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5130 /// \brief Keeps information about an identifier in a nested-name-spec.
5132 struct NestedNameSpecInfo {
5133 /// \brief The type of the object, if we're parsing nested-name-specifier in
5134 /// a member access expression.
5135 ParsedType ObjectType;
5137 /// \brief The identifier preceding the '::'.
5138 IdentifierInfo *Identifier;
5140 /// \brief The location of the identifier.
5141 SourceLocation IdentifierLoc;
5143 /// \brief The location of the '::'.
5144 SourceLocation CCLoc;
5146 /// \brief Creates info object for the most typical case.
5147 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5148 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5149 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5150 CCLoc(ColonColonLoc) {
5153 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5154 SourceLocation ColonColonLoc, QualType ObjectType)
5155 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5156 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5160 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5161 NestedNameSpecInfo &IdInfo);
5163 bool BuildCXXNestedNameSpecifier(Scope *S,
5164 NestedNameSpecInfo &IdInfo,
5165 bool EnteringContext,
5167 NamedDecl *ScopeLookupResult,
5168 bool ErrorRecoveryLookup,
5169 bool *IsCorrectedToColon = nullptr,
5170 bool OnlyNamespace = false);
5172 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5174 /// \param S The scope in which this nested-name-specifier occurs.
5176 /// \param IdInfo Parser information about an identifier in the
5177 /// nested-name-spec.
5179 /// \param EnteringContext Whether we're entering the context nominated by
5180 /// this nested-name-specifier.
5182 /// \param SS The nested-name-specifier, which is both an input
5183 /// parameter (the nested-name-specifier before this type) and an
5184 /// output parameter (containing the full nested-name-specifier,
5185 /// including this new type).
5187 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5188 /// error recovery. In this case do not emit error message.
5190 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5191 /// are allowed. The bool value pointed by this parameter is set to 'true'
5192 /// if the identifier is treated as if it was followed by ':', not '::'.
5194 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5196 /// \returns true if an error occurred, false otherwise.
5197 bool ActOnCXXNestedNameSpecifier(Scope *S,
5198 NestedNameSpecInfo &IdInfo,
5199 bool EnteringContext,
5201 bool ErrorRecoveryLookup = false,
5202 bool *IsCorrectedToColon = nullptr,
5203 bool OnlyNamespace = false);
5205 ExprResult ActOnDecltypeExpression(Expr *E);
5207 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5209 SourceLocation ColonColonLoc);
5211 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5212 NestedNameSpecInfo &IdInfo,
5213 bool EnteringContext);
5215 /// \brief The parser has parsed a nested-name-specifier
5216 /// 'template[opt] template-name < template-args >::'.
5218 /// \param S The scope in which this nested-name-specifier occurs.
5220 /// \param SS The nested-name-specifier, which is both an input
5221 /// parameter (the nested-name-specifier before this type) and an
5222 /// output parameter (containing the full nested-name-specifier,
5223 /// including this new type).
5225 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5226 /// \param TemplateName the template name.
5227 /// \param TemplateNameLoc The location of the template name.
5228 /// \param LAngleLoc The location of the opening angle bracket ('<').
5229 /// \param TemplateArgs The template arguments.
5230 /// \param RAngleLoc The location of the closing angle bracket ('>').
5231 /// \param CCLoc The location of the '::'.
5233 /// \param EnteringContext Whether we're entering the context of the
5234 /// nested-name-specifier.
5237 /// \returns true if an error occurred, false otherwise.
5238 bool ActOnCXXNestedNameSpecifier(Scope *S,
5240 SourceLocation TemplateKWLoc,
5241 TemplateTy TemplateName,
5242 SourceLocation TemplateNameLoc,
5243 SourceLocation LAngleLoc,
5244 ASTTemplateArgsPtr TemplateArgs,
5245 SourceLocation RAngleLoc,
5246 SourceLocation CCLoc,
5247 bool EnteringContext);
5249 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5250 /// that the parser can use later to reconstruct the given
5251 /// nested-name-specifier.
5253 /// \param SS A nested-name-specifier.
5255 /// \returns A pointer containing all of the information in the
5256 /// nested-name-specifier \p SS.
5257 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5259 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5260 /// the nested-name-specifier structure.
5262 /// \param Annotation The annotation pointer, produced by
5263 /// \c SaveNestedNameSpecifierAnnotation().
5265 /// \param AnnotationRange The source range corresponding to the annotation.
5267 /// \param SS The nested-name-specifier that will be updated with the contents
5268 /// of the annotation pointer.
5269 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5270 SourceRange AnnotationRange,
5273 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5275 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5276 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5277 /// After this method is called, according to [C++ 3.4.3p3], names should be
5278 /// looked up in the declarator-id's scope, until the declarator is parsed and
5279 /// ActOnCXXExitDeclaratorScope is called.
5280 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5281 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5283 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5284 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5285 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5286 /// Used to indicate that names should revert to being looked up in the
5288 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5290 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5291 /// initializer for the declaration 'Dcl'.
5292 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5293 /// static data member of class X, names should be looked up in the scope of
5295 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5297 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5298 /// initializer for the declaration 'Dcl'.
5299 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5301 /// \brief Create a new lambda closure type.
5302 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5303 TypeSourceInfo *Info,
5304 bool KnownDependent,
5305 LambdaCaptureDefault CaptureDefault);
5307 /// \brief Start the definition of a lambda expression.
5308 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5309 SourceRange IntroducerRange,
5310 TypeSourceInfo *MethodType,
5311 SourceLocation EndLoc,
5312 ArrayRef<ParmVarDecl *> Params,
5313 bool IsConstexprSpecified);
5315 /// \brief Endow the lambda scope info with the relevant properties.
5316 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5317 CXXMethodDecl *CallOperator,
5318 SourceRange IntroducerRange,
5319 LambdaCaptureDefault CaptureDefault,
5320 SourceLocation CaptureDefaultLoc,
5321 bool ExplicitParams,
5322 bool ExplicitResultType,
5325 /// \brief Perform initialization analysis of the init-capture and perform
5326 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5327 /// not being used to initialize a reference.
5328 ParsedType actOnLambdaInitCaptureInitialization(
5329 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5330 LambdaCaptureInitKind InitKind, Expr *&Init) {
5331 return ParsedType::make(buildLambdaInitCaptureInitialization(
5332 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5334 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5336 bool DirectInit, Expr *&Init);
5338 /// \brief Create a dummy variable within the declcontext of the lambda's
5339 /// call operator, for name lookup purposes for a lambda init capture.
5341 /// CodeGen handles emission of lambda captures, ignoring these dummy
5342 /// variables appropriately.
5343 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5344 QualType InitCaptureType,
5346 unsigned InitStyle, Expr *Init);
5348 /// \brief Build the implicit field for an init-capture.
5349 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5351 /// \brief Note that we have finished the explicit captures for the
5353 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5355 /// \brief Introduce the lambda parameters into scope.
5356 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5358 /// \brief Deduce a block or lambda's return type based on the return
5359 /// statements present in the body.
5360 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5362 /// ActOnStartOfLambdaDefinition - This is called just before we start
5363 /// parsing the body of a lambda; it analyzes the explicit captures and
5364 /// arguments, and sets up various data-structures for the body of the
5366 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5367 Declarator &ParamInfo, Scope *CurScope);
5369 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5370 /// is invoked to pop the information about the lambda.
5371 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5372 bool IsInstantiation = false);
5374 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5375 /// was successfully completed.
5376 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5379 /// \brief Does copying/destroying the captured variable have side effects?
5380 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5382 /// \brief Diagnose if an explicit lambda capture is unused.
5383 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5385 /// \brief Complete a lambda-expression having processed and attached the
5387 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5388 sema::LambdaScopeInfo *LSI);
5390 /// \brief Define the "body" of the conversion from a lambda object to a
5391 /// function pointer.
5393 /// This routine doesn't actually define a sensible body; rather, it fills
5394 /// in the initialization expression needed to copy the lambda object into
5395 /// the block, and IR generation actually generates the real body of the
5396 /// block pointer conversion.
5397 void DefineImplicitLambdaToFunctionPointerConversion(
5398 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5400 /// \brief Define the "body" of the conversion from a lambda object to a
5403 /// This routine doesn't actually define a sensible body; rather, it fills
5404 /// in the initialization expression needed to copy the lambda object into
5405 /// the block, and IR generation actually generates the real body of the
5406 /// block pointer conversion.
5407 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5408 CXXConversionDecl *Conv);
5410 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5411 SourceLocation ConvLocation,
5412 CXXConversionDecl *Conv,
5415 // ParseObjCStringLiteral - Parse Objective-C string literals.
5416 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5417 ArrayRef<Expr *> Strings);
5419 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5421 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5422 /// numeric literal expression. Type of the expression will be "NSNumber *"
5423 /// or "id" if NSNumber is unavailable.
5424 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5425 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5427 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5429 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5430 /// '@' prefixed parenthesized expression. The type of the expression will
5431 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5432 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5433 /// "const char *" or C structure with attribute 'objc_boxable'.
5434 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5436 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5438 ObjCMethodDecl *getterMethod,
5439 ObjCMethodDecl *setterMethod);
5441 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5442 MutableArrayRef<ObjCDictionaryElement> Elements);
5444 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5445 TypeSourceInfo *EncodedTypeInfo,
5446 SourceLocation RParenLoc);
5447 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5448 CXXConversionDecl *Method,
5449 bool HadMultipleCandidates);
5451 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5452 SourceLocation EncodeLoc,
5453 SourceLocation LParenLoc,
5455 SourceLocation RParenLoc);
5457 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5458 ExprResult ParseObjCSelectorExpression(Selector Sel,
5459 SourceLocation AtLoc,
5460 SourceLocation SelLoc,
5461 SourceLocation LParenLoc,
5462 SourceLocation RParenLoc,
5463 bool WarnMultipleSelectors);
5465 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5466 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5467 SourceLocation AtLoc,
5468 SourceLocation ProtoLoc,
5469 SourceLocation LParenLoc,
5470 SourceLocation ProtoIdLoc,
5471 SourceLocation RParenLoc);
5473 //===--------------------------------------------------------------------===//
5476 Decl *ActOnStartLinkageSpecification(Scope *S,
5477 SourceLocation ExternLoc,
5479 SourceLocation LBraceLoc);
5480 Decl *ActOnFinishLinkageSpecification(Scope *S,
5482 SourceLocation RBraceLoc);
5485 //===--------------------------------------------------------------------===//
5488 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5489 const CXXScopeSpec *SS = nullptr);
5490 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5492 bool ActOnAccessSpecifier(AccessSpecifier Access,
5493 SourceLocation ASLoc,
5494 SourceLocation ColonLoc,
5495 AttributeList *Attrs = nullptr);
5497 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5499 MultiTemplateParamsArg TemplateParameterLists,
5500 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5501 InClassInitStyle InitStyle);
5503 void ActOnStartCXXInClassMemberInitializer();
5504 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5505 SourceLocation EqualLoc,
5508 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5511 IdentifierInfo *MemberOrBase,
5512 ParsedType TemplateTypeTy,
5514 SourceLocation IdLoc,
5515 SourceLocation LParenLoc,
5516 ArrayRef<Expr *> Args,
5517 SourceLocation RParenLoc,
5518 SourceLocation EllipsisLoc);
5520 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5523 IdentifierInfo *MemberOrBase,
5524 ParsedType TemplateTypeTy,
5526 SourceLocation IdLoc,
5528 SourceLocation EllipsisLoc);
5530 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5533 IdentifierInfo *MemberOrBase,
5534 ParsedType TemplateTypeTy,
5536 SourceLocation IdLoc,
5538 SourceLocation EllipsisLoc);
5540 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5542 SourceLocation IdLoc);
5544 MemInitResult BuildBaseInitializer(QualType BaseType,
5545 TypeSourceInfo *BaseTInfo,
5547 CXXRecordDecl *ClassDecl,
5548 SourceLocation EllipsisLoc);
5550 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5552 CXXRecordDecl *ClassDecl);
5554 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5555 CXXCtorInitializer *Initializer);
5557 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5558 ArrayRef<CXXCtorInitializer *> Initializers = None);
5560 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5563 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5564 /// mark all the non-trivial destructors of its members and bases as
5566 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5567 CXXRecordDecl *Record);
5569 /// \brief The list of classes whose vtables have been used within
5570 /// this translation unit, and the source locations at which the
5571 /// first use occurred.
5572 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5574 /// \brief The list of vtables that are required but have not yet been
5576 SmallVector<VTableUse, 16> VTableUses;
5578 /// \brief The set of classes whose vtables have been used within
5579 /// this translation unit, and a bit that will be true if the vtable is
5580 /// required to be emitted (otherwise, it should be emitted only if needed
5581 /// by code generation).
5582 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5584 /// \brief Load any externally-stored vtable uses.
5585 void LoadExternalVTableUses();
5587 /// \brief Note that the vtable for the given class was used at the
5589 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5590 bool DefinitionRequired = false);
5592 /// \brief Mark the exception specifications of all virtual member functions
5593 /// in the given class as needed.
5594 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5595 const CXXRecordDecl *RD);
5597 /// MarkVirtualMembersReferenced - Will mark all members of the given
5598 /// CXXRecordDecl referenced.
5599 void MarkVirtualMembersReferenced(SourceLocation Loc,
5600 const CXXRecordDecl *RD);
5602 /// \brief Define all of the vtables that have been used in this
5603 /// translation unit and reference any virtual members used by those
5606 /// \returns true if any work was done, false otherwise.
5607 bool DefineUsedVTables();
5609 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5611 void ActOnMemInitializers(Decl *ConstructorDecl,
5612 SourceLocation ColonLoc,
5613 ArrayRef<CXXCtorInitializer*> MemInits,
5616 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5617 /// ensure that referenceDLLExportedClassMethods is called some point later
5618 /// when all outer classes of Class are complete.
5619 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5621 void referenceDLLExportedClassMethods();
5623 void propagateDLLAttrToBaseClassTemplate(
5624 CXXRecordDecl *Class, Attr *ClassAttr,
5625 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5626 SourceLocation BaseLoc);
5628 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5629 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5631 SourceLocation LBrac,
5632 SourceLocation RBrac,
5633 AttributeList *AttrList);
5634 void ActOnFinishCXXMemberDecls();
5635 void ActOnFinishCXXNonNestedClass(Decl *D);
5637 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5638 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5639 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5640 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5641 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5642 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5643 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5644 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5645 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5646 CachedTokens &Toks);
5647 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5648 bool IsInsideALocalClassWithinATemplateFunction();
5650 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5652 Expr *AssertMessageExpr,
5653 SourceLocation RParenLoc);
5654 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5656 StringLiteral *AssertMessageExpr,
5657 SourceLocation RParenLoc,
5660 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5661 SourceLocation FriendLoc,
5662 TypeSourceInfo *TSInfo);
5663 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5664 MultiTemplateParamsArg TemplateParams);
5665 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5666 MultiTemplateParamsArg TemplateParams);
5668 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5670 void CheckConstructor(CXXConstructorDecl *Constructor);
5671 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5673 bool CheckDestructor(CXXDestructorDecl *Destructor);
5674 void CheckConversionDeclarator(Declarator &D, QualType &R,
5676 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5677 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5679 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5681 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5682 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5683 const FunctionProtoType *T);
5684 void CheckDelayedMemberExceptionSpecs();
5686 //===--------------------------------------------------------------------===//
5687 // C++ Derived Classes
5690 /// ActOnBaseSpecifier - Parsed a base specifier
5691 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5692 SourceRange SpecifierRange,
5693 bool Virtual, AccessSpecifier Access,
5694 TypeSourceInfo *TInfo,
5695 SourceLocation EllipsisLoc);
5697 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5698 SourceRange SpecifierRange,
5699 ParsedAttributes &Attrs,
5700 bool Virtual, AccessSpecifier Access,
5701 ParsedType basetype,
5702 SourceLocation BaseLoc,
5703 SourceLocation EllipsisLoc);
5705 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5706 MutableArrayRef<CXXBaseSpecifier *> Bases);
5707 void ActOnBaseSpecifiers(Decl *ClassDecl,
5708 MutableArrayRef<CXXBaseSpecifier *> Bases);
5710 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5711 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5712 CXXBasePaths &Paths);
5714 // FIXME: I don't like this name.
5715 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5717 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5718 SourceLocation Loc, SourceRange Range,
5719 CXXCastPath *BasePath = nullptr,
5720 bool IgnoreAccess = false);
5721 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5722 unsigned InaccessibleBaseID,
5723 unsigned AmbigiousBaseConvID,
5724 SourceLocation Loc, SourceRange Range,
5725 DeclarationName Name,
5726 CXXCastPath *BasePath,
5727 bool IgnoreAccess = false);
5729 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5731 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5732 const CXXMethodDecl *Old);
5734 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5735 /// covariant, according to C++ [class.virtual]p5.
5736 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5737 const CXXMethodDecl *Old);
5739 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5740 /// spec is a subset of base spec.
5741 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5742 const CXXMethodDecl *Old);
5744 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5746 /// CheckOverrideControl - Check C++11 override control semantics.
5747 void CheckOverrideControl(NamedDecl *D);
5749 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5750 /// not used in the declaration of an overriding method.
5751 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5753 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5754 /// overrides a virtual member function marked 'final', according to
5755 /// C++11 [class.virtual]p4.
5756 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5757 const CXXMethodDecl *Old);
5760 //===--------------------------------------------------------------------===//
5761 // C++ Access Control
5771 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5772 NamedDecl *PrevMemberDecl,
5773 AccessSpecifier LexicalAS);
5775 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5776 DeclAccessPair FoundDecl);
5777 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5778 DeclAccessPair FoundDecl);
5779 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5780 SourceRange PlacementRange,
5781 CXXRecordDecl *NamingClass,
5782 DeclAccessPair FoundDecl,
5783 bool Diagnose = true);
5784 AccessResult CheckConstructorAccess(SourceLocation Loc,
5785 CXXConstructorDecl *D,
5786 DeclAccessPair FoundDecl,
5787 const InitializedEntity &Entity,
5788 bool IsCopyBindingRefToTemp = false);
5789 AccessResult CheckConstructorAccess(SourceLocation Loc,
5790 CXXConstructorDecl *D,
5791 DeclAccessPair FoundDecl,
5792 const InitializedEntity &Entity,
5793 const PartialDiagnostic &PDiag);
5794 AccessResult CheckDestructorAccess(SourceLocation Loc,
5795 CXXDestructorDecl *Dtor,
5796 const PartialDiagnostic &PDiag,
5797 QualType objectType = QualType());
5798 AccessResult CheckFriendAccess(NamedDecl *D);
5799 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5800 CXXRecordDecl *NamingClass,
5801 DeclAccessPair Found);
5802 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5805 DeclAccessPair FoundDecl);
5806 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5807 DeclAccessPair FoundDecl);
5808 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5809 QualType Base, QualType Derived,
5810 const CXXBasePath &Path,
5812 bool ForceCheck = false,
5813 bool ForceUnprivileged = false);
5814 void CheckLookupAccess(const LookupResult &R);
5815 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5816 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5817 AccessSpecifier access,
5818 QualType objectType);
5820 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5821 const MultiLevelTemplateArgumentList &TemplateArgs);
5822 void PerformDependentDiagnostics(const DeclContext *Pattern,
5823 const MultiLevelTemplateArgumentList &TemplateArgs);
5825 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5827 /// \brief When true, access checking violations are treated as SFINAE
5828 /// failures rather than hard errors.
5829 bool AccessCheckingSFINAE;
5831 enum AbstractDiagSelID {
5835 AbstractVariableType,
5838 AbstractSynthesizedIvarType,
5842 bool isAbstractType(SourceLocation Loc, QualType T);
5843 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5844 TypeDiagnoser &Diagnoser);
5845 template <typename... Ts>
5846 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5847 const Ts &...Args) {
5848 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5849 return RequireNonAbstractType(Loc, T, Diagnoser);
5852 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5854 //===--------------------------------------------------------------------===//
5855 // C++ Overloaded Operators [C++ 13.5]
5858 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5860 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5862 //===--------------------------------------------------------------------===//
5863 // C++ Templates [C++ 14]
5865 void FilterAcceptableTemplateNames(LookupResult &R,
5866 bool AllowFunctionTemplates = true);
5867 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5868 bool AllowFunctionTemplates = true);
5870 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5871 QualType ObjectType, bool EnteringContext,
5872 bool &MemberOfUnknownSpecialization);
5874 TemplateNameKind isTemplateName(Scope *S,
5876 bool hasTemplateKeyword,
5877 UnqualifiedId &Name,
5878 ParsedType ObjectType,
5879 bool EnteringContext,
5880 TemplateTy &Template,
5881 bool &MemberOfUnknownSpecialization);
5883 /// Determine whether a particular identifier might be the name in a C++1z
5884 /// deduction-guide declaration.
5885 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5886 SourceLocation NameLoc,
5887 ParsedTemplateTy *Template = nullptr);
5889 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5890 SourceLocation IILoc,
5892 const CXXScopeSpec *SS,
5893 TemplateTy &SuggestedTemplate,
5894 TemplateNameKind &SuggestedKind);
5896 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5897 NamedDecl *Instantiation,
5898 bool InstantiatedFromMember,
5899 const NamedDecl *Pattern,
5900 const NamedDecl *PatternDef,
5901 TemplateSpecializationKind TSK,
5902 bool Complain = true);
5904 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5905 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5907 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5908 SourceLocation EllipsisLoc,
5909 SourceLocation KeyLoc,
5910 IdentifierInfo *ParamName,
5911 SourceLocation ParamNameLoc,
5912 unsigned Depth, unsigned Position,
5913 SourceLocation EqualLoc,
5914 ParsedType DefaultArg);
5916 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5917 SourceLocation Loc);
5918 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5920 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5923 SourceLocation EqualLoc,
5925 Decl *ActOnTemplateTemplateParameter(Scope *S,
5926 SourceLocation TmpLoc,
5927 TemplateParameterList *Params,
5928 SourceLocation EllipsisLoc,
5929 IdentifierInfo *ParamName,
5930 SourceLocation ParamNameLoc,
5933 SourceLocation EqualLoc,
5934 ParsedTemplateArgument DefaultArg);
5936 TemplateParameterList *
5937 ActOnTemplateParameterList(unsigned Depth,
5938 SourceLocation ExportLoc,
5939 SourceLocation TemplateLoc,
5940 SourceLocation LAngleLoc,
5941 ArrayRef<Decl *> Params,
5942 SourceLocation RAngleLoc,
5943 Expr *RequiresClause);
5945 /// \brief The context in which we are checking a template parameter list.
5946 enum TemplateParamListContext {
5949 TPC_FunctionTemplate,
5950 TPC_ClassTemplateMember,
5951 TPC_FriendClassTemplate,
5952 TPC_FriendFunctionTemplate,
5953 TPC_FriendFunctionTemplateDefinition,
5954 TPC_TypeAliasTemplate
5957 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5958 TemplateParameterList *OldParams,
5959 TemplateParamListContext TPC);
5960 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5961 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5962 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5963 ArrayRef<TemplateParameterList *> ParamLists,
5964 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5966 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5967 SourceLocation KWLoc, CXXScopeSpec &SS,
5968 IdentifierInfo *Name, SourceLocation NameLoc,
5969 AttributeList *Attr,
5970 TemplateParameterList *TemplateParams,
5972 SourceLocation ModulePrivateLoc,
5973 SourceLocation FriendLoc,
5974 unsigned NumOuterTemplateParamLists,
5975 TemplateParameterList **OuterTemplateParamLists,
5976 SkipBodyInfo *SkipBody = nullptr);
5978 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5980 SourceLocation Loc);
5982 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5983 TemplateArgumentListInfo &Out);
5985 void NoteAllFoundTemplates(TemplateName Name);
5987 QualType CheckTemplateIdType(TemplateName Template,
5988 SourceLocation TemplateLoc,
5989 TemplateArgumentListInfo &TemplateArgs);
5992 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5993 TemplateTy Template, IdentifierInfo *TemplateII,
5994 SourceLocation TemplateIILoc,
5995 SourceLocation LAngleLoc,
5996 ASTTemplateArgsPtr TemplateArgs,
5997 SourceLocation RAngleLoc,
5998 bool IsCtorOrDtorName = false,
5999 bool IsClassName = false);
6001 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6002 /// such as \c class T::template apply<U>.
6003 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6004 TypeSpecifierType TagSpec,
6005 SourceLocation TagLoc,
6007 SourceLocation TemplateKWLoc,
6008 TemplateTy TemplateD,
6009 SourceLocation TemplateLoc,
6010 SourceLocation LAngleLoc,
6011 ASTTemplateArgsPtr TemplateArgsIn,
6012 SourceLocation RAngleLoc);
6014 DeclResult ActOnVarTemplateSpecialization(
6015 Scope *S, Declarator &D, TypeSourceInfo *DI,
6016 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6017 StorageClass SC, bool IsPartialSpecialization);
6019 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6020 SourceLocation TemplateLoc,
6021 SourceLocation TemplateNameLoc,
6022 const TemplateArgumentListInfo &TemplateArgs);
6024 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6025 const DeclarationNameInfo &NameInfo,
6026 VarTemplateDecl *Template,
6027 SourceLocation TemplateLoc,
6028 const TemplateArgumentListInfo *TemplateArgs);
6030 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6031 SourceLocation TemplateKWLoc,
6034 const TemplateArgumentListInfo *TemplateArgs);
6036 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6037 SourceLocation TemplateKWLoc,
6038 const DeclarationNameInfo &NameInfo,
6039 const TemplateArgumentListInfo *TemplateArgs);
6041 TemplateNameKind ActOnDependentTemplateName(
6042 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6043 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6044 TemplateTy &Template, bool AllowInjectedClassName = false);
6047 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6048 SourceLocation KWLoc,
6049 SourceLocation ModulePrivateLoc,
6050 TemplateIdAnnotation &TemplateId,
6051 AttributeList *Attr,
6052 MultiTemplateParamsArg TemplateParameterLists,
6053 SkipBodyInfo *SkipBody = nullptr);
6055 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6056 TemplateDecl *PrimaryTemplate,
6057 unsigned NumExplicitArgs,
6058 ArrayRef<TemplateArgument> Args);
6059 void CheckTemplatePartialSpecialization(
6060 ClassTemplatePartialSpecializationDecl *Partial);
6061 void CheckTemplatePartialSpecialization(
6062 VarTemplatePartialSpecializationDecl *Partial);
6064 Decl *ActOnTemplateDeclarator(Scope *S,
6065 MultiTemplateParamsArg TemplateParameterLists,
6069 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6070 TemplateSpecializationKind NewTSK,
6071 NamedDecl *PrevDecl,
6072 TemplateSpecializationKind PrevTSK,
6073 SourceLocation PrevPtOfInstantiation,
6076 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6077 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6078 LookupResult &Previous);
6080 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6081 TemplateArgumentListInfo *ExplicitTemplateArgs,
6082 LookupResult &Previous);
6083 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6086 ActOnExplicitInstantiation(Scope *S,
6087 SourceLocation ExternLoc,
6088 SourceLocation TemplateLoc,
6090 SourceLocation KWLoc,
6091 const CXXScopeSpec &SS,
6092 TemplateTy Template,
6093 SourceLocation TemplateNameLoc,
6094 SourceLocation LAngleLoc,
6095 ASTTemplateArgsPtr TemplateArgs,
6096 SourceLocation RAngleLoc,
6097 AttributeList *Attr);
6100 ActOnExplicitInstantiation(Scope *S,
6101 SourceLocation ExternLoc,
6102 SourceLocation TemplateLoc,
6104 SourceLocation KWLoc,
6106 IdentifierInfo *Name,
6107 SourceLocation NameLoc,
6108 AttributeList *Attr);
6110 DeclResult ActOnExplicitInstantiation(Scope *S,
6111 SourceLocation ExternLoc,
6112 SourceLocation TemplateLoc,
6116 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6117 SourceLocation TemplateLoc,
6118 SourceLocation RAngleLoc,
6120 SmallVectorImpl<TemplateArgument>
6122 bool &HasDefaultArg);
6124 /// \brief Specifies the context in which a particular template
6125 /// argument is being checked.
6126 enum CheckTemplateArgumentKind {
6127 /// \brief The template argument was specified in the code or was
6128 /// instantiated with some deduced template arguments.
6131 /// \brief The template argument was deduced via template argument
6135 /// \brief The template argument was deduced from an array bound
6136 /// via template argument deduction.
6137 CTAK_DeducedFromArrayBound
6140 bool CheckTemplateArgument(NamedDecl *Param,
6141 TemplateArgumentLoc &Arg,
6142 NamedDecl *Template,
6143 SourceLocation TemplateLoc,
6144 SourceLocation RAngleLoc,
6145 unsigned ArgumentPackIndex,
6146 SmallVectorImpl<TemplateArgument> &Converted,
6147 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6149 /// \brief Check that the given template arguments can be be provided to
6150 /// the given template, converting the arguments along the way.
6152 /// \param Template The template to which the template arguments are being
6155 /// \param TemplateLoc The location of the template name in the source.
6157 /// \param TemplateArgs The list of template arguments. If the template is
6158 /// a template template parameter, this function may extend the set of
6159 /// template arguments to also include substituted, defaulted template
6162 /// \param PartialTemplateArgs True if the list of template arguments is
6163 /// intentionally partial, e.g., because we're checking just the initial
6164 /// set of template arguments.
6166 /// \param Converted Will receive the converted, canonicalized template
6169 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6170 /// contain the converted forms of the template arguments as written.
6171 /// Otherwise, \p TemplateArgs will not be modified.
6173 /// \returns true if an error occurred, false otherwise.
6174 bool CheckTemplateArgumentList(TemplateDecl *Template,
6175 SourceLocation TemplateLoc,
6176 TemplateArgumentListInfo &TemplateArgs,
6177 bool PartialTemplateArgs,
6178 SmallVectorImpl<TemplateArgument> &Converted,
6179 bool UpdateArgsWithConversions = true);
6181 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6182 TemplateArgumentLoc &Arg,
6183 SmallVectorImpl<TemplateArgument> &Converted);
6185 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6186 TypeSourceInfo *Arg);
6187 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6188 QualType InstantiatedParamType, Expr *Arg,
6189 TemplateArgument &Converted,
6190 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6191 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6192 TemplateArgumentLoc &Arg,
6193 unsigned ArgumentPackIndex);
6196 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6198 SourceLocation Loc);
6200 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6201 SourceLocation Loc);
6203 /// \brief Enumeration describing how template parameter lists are compared
6205 enum TemplateParameterListEqualKind {
6206 /// \brief We are matching the template parameter lists of two templates
6207 /// that might be redeclarations.
6210 /// template<typename T> struct X;
6211 /// template<typename T> struct X;
6215 /// \brief We are matching the template parameter lists of two template
6216 /// template parameters as part of matching the template parameter lists
6217 /// of two templates that might be redeclarations.
6220 /// template<template<int I> class TT> struct X;
6221 /// template<template<int Value> class Other> struct X;
6223 TPL_TemplateTemplateParmMatch,
6225 /// \brief We are matching the template parameter lists of a template
6226 /// template argument against the template parameter lists of a template
6227 /// template parameter.
6230 /// template<template<int Value> class Metafun> struct X;
6231 /// template<int Value> struct integer_c;
6232 /// X<integer_c> xic;
6234 TPL_TemplateTemplateArgumentMatch
6237 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6238 TemplateParameterList *Old,
6240 TemplateParameterListEqualKind Kind,
6241 SourceLocation TemplateArgLoc
6242 = SourceLocation());
6244 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6246 /// \brief Called when the parser has parsed a C++ typename
6247 /// specifier, e.g., "typename T::type".
6249 /// \param S The scope in which this typename type occurs.
6250 /// \param TypenameLoc the location of the 'typename' keyword
6251 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6252 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6253 /// \param IdLoc the location of the identifier.
6255 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6256 const CXXScopeSpec &SS, const IdentifierInfo &II,
6257 SourceLocation IdLoc);
6259 /// \brief Called when the parser has parsed a C++ typename
6260 /// specifier that ends in a template-id, e.g.,
6261 /// "typename MetaFun::template apply<T1, T2>".
6263 /// \param S The scope in which this typename type occurs.
6264 /// \param TypenameLoc the location of the 'typename' keyword
6265 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6266 /// \param TemplateLoc the location of the 'template' keyword, if any.
6267 /// \param TemplateName The template name.
6268 /// \param TemplateII The identifier used to name the template.
6269 /// \param TemplateIILoc The location of the template name.
6270 /// \param LAngleLoc The location of the opening angle bracket ('<').
6271 /// \param TemplateArgs The template arguments.
6272 /// \param RAngleLoc The location of the closing angle bracket ('>').
6274 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6275 const CXXScopeSpec &SS,
6276 SourceLocation TemplateLoc,
6277 TemplateTy TemplateName,
6278 IdentifierInfo *TemplateII,
6279 SourceLocation TemplateIILoc,
6280 SourceLocation LAngleLoc,
6281 ASTTemplateArgsPtr TemplateArgs,
6282 SourceLocation RAngleLoc);
6284 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6285 SourceLocation KeywordLoc,
6286 NestedNameSpecifierLoc QualifierLoc,
6287 const IdentifierInfo &II,
6288 SourceLocation IILoc);
6290 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6292 DeclarationName Name);
6293 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6295 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6296 bool RebuildTemplateParamsInCurrentInstantiation(
6297 TemplateParameterList *Params);
6300 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6301 const TemplateArgumentList &Args);
6304 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6305 const TemplateArgument *Args,
6308 //===--------------------------------------------------------------------===//
6309 // C++ Variadic Templates (C++0x [temp.variadic])
6310 //===--------------------------------------------------------------------===//
6312 /// Determine whether an unexpanded parameter pack might be permitted in this
6313 /// location. Useful for error recovery.
6314 bool isUnexpandedParameterPackPermitted();
6316 /// \brief The context in which an unexpanded parameter pack is
6317 /// being diagnosed.
6319 /// Note that the values of this enumeration line up with the first
6320 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6321 enum UnexpandedParameterPackContext {
6322 /// \brief An arbitrary expression.
6323 UPPC_Expression = 0,
6325 /// \brief The base type of a class type.
6328 /// \brief The type of an arbitrary declaration.
6329 UPPC_DeclarationType,
6331 /// \brief The type of a data member.
6332 UPPC_DataMemberType,
6334 /// \brief The size of a bit-field.
6337 /// \brief The expression in a static assertion.
6338 UPPC_StaticAssertExpression,
6340 /// \brief The fixed underlying type of an enumeration.
6341 UPPC_FixedUnderlyingType,
6343 /// \brief The enumerator value.
6344 UPPC_EnumeratorValue,
6346 /// \brief A using declaration.
6347 UPPC_UsingDeclaration,
6349 /// \brief A friend declaration.
6350 UPPC_FriendDeclaration,
6352 /// \brief A declaration qualifier.
6353 UPPC_DeclarationQualifier,
6355 /// \brief An initializer.
6358 /// \brief A default argument.
6359 UPPC_DefaultArgument,
6361 /// \brief The type of a non-type template parameter.
6362 UPPC_NonTypeTemplateParameterType,
6364 /// \brief The type of an exception.
6367 /// \brief Partial specialization.
6368 UPPC_PartialSpecialization,
6370 /// \brief Microsoft __if_exists.
6373 /// \brief Microsoft __if_not_exists.
6376 /// \brief Lambda expression.
6379 /// \brief Block expression,
6383 /// \brief Diagnose unexpanded parameter packs.
6385 /// \param Loc The location at which we should emit the diagnostic.
6387 /// \param UPPC The context in which we are diagnosing unexpanded
6388 /// parameter packs.
6390 /// \param Unexpanded the set of unexpanded parameter packs.
6392 /// \returns true if an error occurred, false otherwise.
6393 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6394 UnexpandedParameterPackContext UPPC,
6395 ArrayRef<UnexpandedParameterPack> Unexpanded);
6397 /// \brief If the given type contains an unexpanded parameter pack,
6398 /// diagnose the error.
6400 /// \param Loc The source location where a diagnostc should be emitted.
6402 /// \param T The type that is being checked for unexpanded parameter
6405 /// \returns true if an error occurred, false otherwise.
6406 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6407 UnexpandedParameterPackContext UPPC);
6409 /// \brief If the given expression contains an unexpanded parameter
6410 /// pack, diagnose the error.
6412 /// \param E The expression that is being checked for unexpanded
6413 /// parameter packs.
6415 /// \returns true if an error occurred, false otherwise.
6416 bool DiagnoseUnexpandedParameterPack(Expr *E,
6417 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6419 /// \brief If the given nested-name-specifier contains an unexpanded
6420 /// parameter pack, diagnose the error.
6422 /// \param SS The nested-name-specifier that is being checked for
6423 /// unexpanded parameter packs.
6425 /// \returns true if an error occurred, false otherwise.
6426 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6427 UnexpandedParameterPackContext UPPC);
6429 /// \brief If the given name contains an unexpanded parameter pack,
6430 /// diagnose the error.
6432 /// \param NameInfo The name (with source location information) that
6433 /// is being checked for unexpanded parameter packs.
6435 /// \returns true if an error occurred, false otherwise.
6436 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6437 UnexpandedParameterPackContext UPPC);
6439 /// \brief If the given template name contains an unexpanded parameter pack,
6440 /// diagnose the error.
6442 /// \param Loc The location of the template name.
6444 /// \param Template The template name that is being checked for unexpanded
6445 /// parameter packs.
6447 /// \returns true if an error occurred, false otherwise.
6448 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6449 TemplateName Template,
6450 UnexpandedParameterPackContext UPPC);
6452 /// \brief If the given template argument contains an unexpanded parameter
6453 /// pack, diagnose the error.
6455 /// \param Arg The template argument that is being checked for unexpanded
6456 /// parameter packs.
6458 /// \returns true if an error occurred, false otherwise.
6459 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6460 UnexpandedParameterPackContext UPPC);
6462 /// \brief Collect the set of unexpanded parameter packs within the given
6463 /// template argument.
6465 /// \param Arg The template argument that will be traversed to find
6466 /// unexpanded parameter packs.
6467 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6468 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6470 /// \brief Collect the set of unexpanded parameter packs within the given
6471 /// template argument.
6473 /// \param Arg The template argument that will be traversed to find
6474 /// unexpanded parameter packs.
6475 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6476 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6478 /// \brief Collect the set of unexpanded parameter packs within the given
6481 /// \param T The type that will be traversed to find
6482 /// unexpanded parameter packs.
6483 void collectUnexpandedParameterPacks(QualType T,
6484 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6486 /// \brief Collect the set of unexpanded parameter packs within the given
6489 /// \param TL The type that will be traversed to find
6490 /// unexpanded parameter packs.
6491 void collectUnexpandedParameterPacks(TypeLoc TL,
6492 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6494 /// \brief Collect the set of unexpanded parameter packs within the given
6495 /// nested-name-specifier.
6497 /// \param NNS The nested-name-specifier that will be traversed to find
6498 /// unexpanded parameter packs.
6499 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6500 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6502 /// \brief Collect the set of unexpanded parameter packs within the given
6505 /// \param NameInfo The name that will be traversed to find
6506 /// unexpanded parameter packs.
6507 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6508 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6510 /// \brief Invoked when parsing a template argument followed by an
6511 /// ellipsis, which creates a pack expansion.
6513 /// \param Arg The template argument preceding the ellipsis, which
6514 /// may already be invalid.
6516 /// \param EllipsisLoc The location of the ellipsis.
6517 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6518 SourceLocation EllipsisLoc);
6520 /// \brief Invoked when parsing a type followed by an ellipsis, which
6521 /// creates a pack expansion.
6523 /// \param Type The type preceding the ellipsis, which will become
6524 /// the pattern of the pack expansion.
6526 /// \param EllipsisLoc The location of the ellipsis.
6527 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6529 /// \brief Construct a pack expansion type from the pattern of the pack
6531 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6532 SourceLocation EllipsisLoc,
6533 Optional<unsigned> NumExpansions);
6535 /// \brief Construct a pack expansion type from the pattern of the pack
6537 QualType CheckPackExpansion(QualType Pattern,
6538 SourceRange PatternRange,
6539 SourceLocation EllipsisLoc,
6540 Optional<unsigned> NumExpansions);
6542 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6543 /// creates a pack expansion.
6545 /// \param Pattern The expression preceding the ellipsis, which will become
6546 /// the pattern of the pack expansion.
6548 /// \param EllipsisLoc The location of the ellipsis.
6549 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6551 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6552 /// creates a pack expansion.
6554 /// \param Pattern The expression preceding the ellipsis, which will become
6555 /// the pattern of the pack expansion.
6557 /// \param EllipsisLoc The location of the ellipsis.
6558 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6559 Optional<unsigned> NumExpansions);
6561 /// \brief Determine whether we could expand a pack expansion with the
6562 /// given set of parameter packs into separate arguments by repeatedly
6563 /// transforming the pattern.
6565 /// \param EllipsisLoc The location of the ellipsis that identifies the
6568 /// \param PatternRange The source range that covers the entire pattern of
6569 /// the pack expansion.
6571 /// \param Unexpanded The set of unexpanded parameter packs within the
6574 /// \param ShouldExpand Will be set to \c true if the transformer should
6575 /// expand the corresponding pack expansions into separate arguments. When
6576 /// set, \c NumExpansions must also be set.
6578 /// \param RetainExpansion Whether the caller should add an unexpanded
6579 /// pack expansion after all of the expanded arguments. This is used
6580 /// when extending explicitly-specified template argument packs per
6581 /// C++0x [temp.arg.explicit]p9.
6583 /// \param NumExpansions The number of separate arguments that will be in
6584 /// the expanded form of the corresponding pack expansion. This is both an
6585 /// input and an output parameter, which can be set by the caller if the
6586 /// number of expansions is known a priori (e.g., due to a prior substitution)
6587 /// and will be set by the callee when the number of expansions is known.
6588 /// The callee must set this value when \c ShouldExpand is \c true; it may
6589 /// set this value in other cases.
6591 /// \returns true if an error occurred (e.g., because the parameter packs
6592 /// are to be instantiated with arguments of different lengths), false
6593 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6595 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6596 SourceRange PatternRange,
6597 ArrayRef<UnexpandedParameterPack> Unexpanded,
6598 const MultiLevelTemplateArgumentList &TemplateArgs,
6600 bool &RetainExpansion,
6601 Optional<unsigned> &NumExpansions);
6603 /// \brief Determine the number of arguments in the given pack expansion
6606 /// This routine assumes that the number of arguments in the expansion is
6607 /// consistent across all of the unexpanded parameter packs in its pattern.
6609 /// Returns an empty Optional if the type can't be expanded.
6610 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6611 const MultiLevelTemplateArgumentList &TemplateArgs);
6613 /// \brief Determine whether the given declarator contains any unexpanded
6614 /// parameter packs.
6616 /// This routine is used by the parser to disambiguate function declarators
6617 /// with an ellipsis prior to the ')', e.g.,
6623 /// To determine whether we have an (unnamed) function parameter pack or
6624 /// a variadic function.
6626 /// \returns true if the declarator contains any unexpanded parameter packs,
6627 /// false otherwise.
6628 bool containsUnexpandedParameterPacks(Declarator &D);
6630 /// \brief Returns the pattern of the pack expansion for a template argument.
6632 /// \param OrigLoc The template argument to expand.
6634 /// \param Ellipsis Will be set to the location of the ellipsis.
6636 /// \param NumExpansions Will be set to the number of expansions that will
6637 /// be generated from this pack expansion, if known a priori.
6638 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6639 TemplateArgumentLoc OrigLoc,
6640 SourceLocation &Ellipsis,
6641 Optional<unsigned> &NumExpansions) const;
6643 /// Given a template argument that contains an unexpanded parameter pack, but
6644 /// which has already been substituted, attempt to determine the number of
6645 /// elements that will be produced once this argument is fully-expanded.
6647 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6648 /// avoid actually expanding the pack where possible.
6649 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6651 //===--------------------------------------------------------------------===//
6652 // C++ Template Argument Deduction (C++ [temp.deduct])
6653 //===--------------------------------------------------------------------===//
6655 /// Adjust the type \p ArgFunctionType to match the calling convention,
6656 /// noreturn, and optionally the exception specification of \p FunctionType.
6657 /// Deduction often wants to ignore these properties when matching function
6659 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6660 bool AdjustExceptionSpec = false);
6662 /// \brief Describes the result of template argument deduction.
6664 /// The TemplateDeductionResult enumeration describes the result of
6665 /// template argument deduction, as returned from
6666 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6667 /// structure provides additional information about the results of
6668 /// template argument deduction, e.g., the deduced template argument
6669 /// list (if successful) or the specific template parameters or
6670 /// deduced arguments that were involved in the failure.
6671 enum TemplateDeductionResult {
6672 /// \brief Template argument deduction was successful.
6674 /// \brief The declaration was invalid; do nothing.
6676 /// \brief Template argument deduction exceeded the maximum template
6677 /// instantiation depth (which has already been diagnosed).
6678 TDK_InstantiationDepth,
6679 /// \brief Template argument deduction did not deduce a value
6680 /// for every template parameter.
6682 /// \brief Template argument deduction produced inconsistent
6683 /// deduced values for the given template parameter.
6685 /// \brief Template argument deduction failed due to inconsistent
6686 /// cv-qualifiers on a template parameter type that would
6687 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6688 /// but were given a non-const "X".
6690 /// \brief Substitution of the deduced template argument values
6691 /// resulted in an error.
6692 TDK_SubstitutionFailure,
6693 /// \brief After substituting deduced template arguments, a dependent
6694 /// parameter type did not match the corresponding argument.
6695 TDK_DeducedMismatch,
6696 /// \brief After substituting deduced template arguments, an element of
6697 /// a dependent parameter type did not match the corresponding element
6698 /// of the corresponding argument (when deducing from an initializer list).
6699 TDK_DeducedMismatchNested,
6700 /// \brief A non-depnedent component of the parameter did not match the
6701 /// corresponding component of the argument.
6702 TDK_NonDeducedMismatch,
6703 /// \brief When performing template argument deduction for a function
6704 /// template, there were too many call arguments.
6705 TDK_TooManyArguments,
6706 /// \brief When performing template argument deduction for a function
6707 /// template, there were too few call arguments.
6708 TDK_TooFewArguments,
6709 /// \brief The explicitly-specified template arguments were not valid
6710 /// template arguments for the given template.
6711 TDK_InvalidExplicitArguments,
6712 /// \brief Checking non-dependent argument conversions failed.
6713 TDK_NonDependentConversionFailure,
6714 /// \brief Deduction failed; that's all we know.
6715 TDK_MiscellaneousDeductionFailure,
6716 /// \brief CUDA Target attributes do not match.
6717 TDK_CUDATargetMismatch
6720 TemplateDeductionResult
6721 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6722 const TemplateArgumentList &TemplateArgs,
6723 sema::TemplateDeductionInfo &Info);
6725 TemplateDeductionResult
6726 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6727 const TemplateArgumentList &TemplateArgs,
6728 sema::TemplateDeductionInfo &Info);
6730 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6731 FunctionTemplateDecl *FunctionTemplate,
6732 TemplateArgumentListInfo &ExplicitTemplateArgs,
6733 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6734 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6735 sema::TemplateDeductionInfo &Info);
6737 /// brief A function argument from which we performed template argument
6738 // deduction for a call.
6739 struct OriginalCallArg {
6740 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6741 unsigned ArgIdx, QualType OriginalArgType)
6742 : OriginalParamType(OriginalParamType),
6743 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6744 OriginalArgType(OriginalArgType) {}
6746 QualType OriginalParamType;
6747 bool DecomposedParam;
6749 QualType OriginalArgType;
6752 TemplateDeductionResult FinishTemplateArgumentDeduction(
6753 FunctionTemplateDecl *FunctionTemplate,
6754 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6755 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6756 sema::TemplateDeductionInfo &Info,
6757 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6758 bool PartialOverloading = false,
6759 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6761 TemplateDeductionResult DeduceTemplateArguments(
6762 FunctionTemplateDecl *FunctionTemplate,
6763 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6764 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6765 bool PartialOverloading,
6766 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6768 TemplateDeductionResult
6769 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6770 TemplateArgumentListInfo *ExplicitTemplateArgs,
6771 QualType ArgFunctionType,
6772 FunctionDecl *&Specialization,
6773 sema::TemplateDeductionInfo &Info,
6774 bool IsAddressOfFunction = false);
6776 TemplateDeductionResult
6777 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6779 CXXConversionDecl *&Specialization,
6780 sema::TemplateDeductionInfo &Info);
6782 TemplateDeductionResult
6783 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6784 TemplateArgumentListInfo *ExplicitTemplateArgs,
6785 FunctionDecl *&Specialization,
6786 sema::TemplateDeductionInfo &Info,
6787 bool IsAddressOfFunction = false);
6789 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6790 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6791 /// \brief Substitute Replacement for auto in TypeWithAuto
6792 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6793 QualType Replacement);
6794 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6795 /// \p Replacement. This does not retain any \c auto type sugar.
6796 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6798 /// \brief Result type of DeduceAutoType.
6799 enum DeduceAutoResult {
6802 DAR_FailedAlreadyDiagnosed
6806 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6807 Optional<unsigned> DependentDeductionDepth = None);
6809 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6810 Optional<unsigned> DependentDeductionDepth = None);
6811 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6812 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6813 bool Diagnose = true);
6815 /// \brief Declare implicit deduction guides for a class template if we've
6816 /// not already done so.
6817 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6818 SourceLocation Loc);
6820 QualType DeduceTemplateSpecializationFromInitializer(
6821 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6822 const InitializationKind &Kind, MultiExprArg Init);
6824 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6825 QualType Type, TypeSourceInfo *TSI,
6826 SourceRange Range, bool DirectInit,
6829 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6831 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6832 SourceLocation ReturnLoc,
6833 Expr *&RetExpr, AutoType *AT);
6835 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6836 FunctionTemplateDecl *FT2,
6838 TemplatePartialOrderingContext TPOC,
6839 unsigned NumCallArguments1,
6840 unsigned NumCallArguments2);
6841 UnresolvedSetIterator
6842 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6843 TemplateSpecCandidateSet &FailedCandidates,
6845 const PartialDiagnostic &NoneDiag,
6846 const PartialDiagnostic &AmbigDiag,
6847 const PartialDiagnostic &CandidateDiag,
6848 bool Complain = true, QualType TargetType = QualType());
6850 ClassTemplatePartialSpecializationDecl *
6851 getMoreSpecializedPartialSpecialization(
6852 ClassTemplatePartialSpecializationDecl *PS1,
6853 ClassTemplatePartialSpecializationDecl *PS2,
6854 SourceLocation Loc);
6856 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6857 sema::TemplateDeductionInfo &Info);
6859 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6860 VarTemplatePartialSpecializationDecl *PS1,
6861 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6863 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6864 sema::TemplateDeductionInfo &Info);
6866 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6867 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6869 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6872 llvm::SmallBitVector &Used);
6873 void MarkDeducedTemplateParameters(
6874 const FunctionTemplateDecl *FunctionTemplate,
6875 llvm::SmallBitVector &Deduced) {
6876 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6878 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6879 const FunctionTemplateDecl *FunctionTemplate,
6880 llvm::SmallBitVector &Deduced);
6882 //===--------------------------------------------------------------------===//
6883 // C++ Template Instantiation
6886 MultiLevelTemplateArgumentList
6887 getTemplateInstantiationArgs(NamedDecl *D,
6888 const TemplateArgumentList *Innermost = nullptr,
6889 bool RelativeToPrimary = false,
6890 const FunctionDecl *Pattern = nullptr);
6892 /// A context in which code is being synthesized (where a source location
6893 /// alone is not sufficient to identify the context). This covers template
6894 /// instantiation and various forms of implicitly-generated functions.
6895 struct CodeSynthesisContext {
6896 /// \brief The kind of template instantiation we are performing
6897 enum SynthesisKind {
6898 /// We are instantiating a template declaration. The entity is
6899 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6900 TemplateInstantiation,
6902 /// We are instantiating a default argument for a template
6903 /// parameter. The Entity is the template parameter whose argument is
6904 /// being instantiated, the Template is the template, and the
6905 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6907 DefaultTemplateArgumentInstantiation,
6909 /// We are instantiating a default argument for a function.
6910 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6911 /// provides the template arguments as specified.
6912 DefaultFunctionArgumentInstantiation,
6914 /// We are substituting explicit template arguments provided for
6915 /// a function template. The entity is a FunctionTemplateDecl.
6916 ExplicitTemplateArgumentSubstitution,
6918 /// We are substituting template argument determined as part of
6919 /// template argument deduction for either a class template
6920 /// partial specialization or a function template. The
6921 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6923 DeducedTemplateArgumentSubstitution,
6925 /// We are substituting prior template arguments into a new
6926 /// template parameter. The template parameter itself is either a
6927 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6928 PriorTemplateArgumentSubstitution,
6930 /// We are checking the validity of a default template argument that
6931 /// has been used when naming a template-id.
6932 DefaultTemplateArgumentChecking,
6934 /// We are instantiating the exception specification for a function
6935 /// template which was deferred until it was needed.
6936 ExceptionSpecInstantiation,
6938 /// We are declaring an implicit special member function.
6939 DeclaringSpecialMember,
6942 /// \brief Was the enclosing context a non-instantiation SFINAE context?
6943 bool SavedInNonInstantiationSFINAEContext;
6945 /// \brief The point of instantiation or synthesis within the source code.
6946 SourceLocation PointOfInstantiation;
6948 /// \brief The entity that is being synthesized.
6951 /// \brief The template (or partial specialization) in which we are
6952 /// performing the instantiation, for substitutions of prior template
6954 NamedDecl *Template;
6956 /// \brief The list of template arguments we are substituting, if they
6957 /// are not part of the entity.
6958 const TemplateArgument *TemplateArgs;
6960 // FIXME: Wrap this union around more members, or perhaps store the
6961 // kind-specific members in the RAII object owning the context.
6963 /// \brief The number of template arguments in TemplateArgs.
6964 unsigned NumTemplateArgs;
6966 /// \brief The special member being declared or defined.
6967 CXXSpecialMember SpecialMember;
6970 ArrayRef<TemplateArgument> template_arguments() const {
6971 assert(Kind != DeclaringSpecialMember);
6972 return {TemplateArgs, NumTemplateArgs};
6975 /// \brief The template deduction info object associated with the
6976 /// substitution or checking of explicit or deduced template arguments.
6977 sema::TemplateDeductionInfo *DeductionInfo;
6979 /// \brief The source range that covers the construct that cause
6980 /// the instantiation, e.g., the template-id that causes a class
6981 /// template instantiation.
6982 SourceRange InstantiationRange;
6984 CodeSynthesisContext()
6985 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
6986 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6988 /// \brief Determines whether this template is an actual instantiation
6989 /// that should be counted toward the maximum instantiation depth.
6990 bool isInstantiationRecord() const;
6993 /// \brief List of active code synthesis contexts.
6995 /// This vector is treated as a stack. As synthesis of one entity requires
6996 /// synthesis of another, additional contexts are pushed onto the stack.
6997 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
6999 /// Specializations whose definitions are currently being instantiated.
7000 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7002 /// Non-dependent types used in templates that have already been instantiated
7003 /// by some template instantiation.
7004 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7006 /// \brief Extra modules inspected when performing a lookup during a template
7007 /// instantiation. Computed lazily.
7008 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7010 /// \brief Cache of additional modules that should be used for name lookup
7011 /// within the current template instantiation. Computed lazily; use
7012 /// getLookupModules() to get a complete set.
7013 llvm::DenseSet<Module*> LookupModulesCache;
7015 /// \brief Get the set of additional modules that should be checked during
7016 /// name lookup. A module and its imports become visible when instanting a
7017 /// template defined within it.
7018 llvm::DenseSet<Module*> &getLookupModules();
7020 /// \brief Map from the most recent declaration of a namespace to the most
7021 /// recent visible declaration of that namespace.
7022 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7024 /// \brief Whether we are in a SFINAE context that is not associated with
7025 /// template instantiation.
7027 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7028 /// of a template instantiation or template argument deduction.
7029 bool InNonInstantiationSFINAEContext;
7031 /// \brief The number of \p CodeSynthesisContexts that are not template
7032 /// instantiations and, therefore, should not be counted as part of the
7033 /// instantiation depth.
7035 /// When the instantiation depth reaches the user-configurable limit
7036 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7037 // FIXME: Should we have a similar limit for other forms of synthesis?
7038 unsigned NonInstantiationEntries;
7040 /// \brief The depth of the context stack at the point when the most recent
7041 /// error or warning was produced.
7043 /// This value is used to suppress printing of redundant context stacks
7044 /// when there are multiple errors or warnings in the same instantiation.
7045 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7046 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7048 /// \brief The current index into pack expansion arguments that will be
7049 /// used for substitution of parameter packs.
7051 /// The pack expansion index will be -1 to indicate that parameter packs
7052 /// should be instantiated as themselves. Otherwise, the index specifies
7053 /// which argument within the parameter pack will be used for substitution.
7054 int ArgumentPackSubstitutionIndex;
7056 /// \brief RAII object used to change the argument pack substitution index
7057 /// within a \c Sema object.
7059 /// See \c ArgumentPackSubstitutionIndex for more information.
7060 class ArgumentPackSubstitutionIndexRAII {
7062 int OldSubstitutionIndex;
7065 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7066 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7067 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7070 ~ArgumentPackSubstitutionIndexRAII() {
7071 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7075 friend class ArgumentPackSubstitutionRAII;
7077 /// \brief For each declaration that involved template argument deduction, the
7078 /// set of diagnostics that were suppressed during that template argument
7081 /// FIXME: Serialize this structure to the AST file.
7082 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7083 SuppressedDiagnosticsMap;
7084 SuppressedDiagnosticsMap SuppressedDiagnostics;
7086 /// \brief A stack object to be created when performing template
7089 /// Construction of an object of type \c InstantiatingTemplate
7090 /// pushes the current instantiation onto the stack of active
7091 /// instantiations. If the size of this stack exceeds the maximum
7092 /// number of recursive template instantiations, construction
7093 /// produces an error and evaluates true.
7095 /// Destruction of this object will pop the named instantiation off
7097 struct InstantiatingTemplate {
7098 /// \brief Note that we are instantiating a class template,
7099 /// function template, variable template, alias template,
7100 /// or a member thereof.
7101 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7103 SourceRange InstantiationRange = SourceRange());
7105 struct ExceptionSpecification {};
7106 /// \brief Note that we are instantiating an exception specification
7107 /// of a function template.
7108 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7109 FunctionDecl *Entity, ExceptionSpecification,
7110 SourceRange InstantiationRange = SourceRange());
7112 /// \brief Note that we are instantiating a default argument in a
7114 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7115 TemplateParameter Param, TemplateDecl *Template,
7116 ArrayRef<TemplateArgument> TemplateArgs,
7117 SourceRange InstantiationRange = SourceRange());
7119 /// \brief Note that we are substituting either explicitly-specified or
7120 /// deduced template arguments during function template argument deduction.
7121 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7122 FunctionTemplateDecl *FunctionTemplate,
7123 ArrayRef<TemplateArgument> TemplateArgs,
7124 CodeSynthesisContext::SynthesisKind Kind,
7125 sema::TemplateDeductionInfo &DeductionInfo,
7126 SourceRange InstantiationRange = SourceRange());
7128 /// \brief Note that we are instantiating as part of template
7129 /// argument deduction for a class template declaration.
7130 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7131 TemplateDecl *Template,
7132 ArrayRef<TemplateArgument> TemplateArgs,
7133 sema::TemplateDeductionInfo &DeductionInfo,
7134 SourceRange InstantiationRange = SourceRange());
7136 /// \brief Note that we are instantiating as part of template
7137 /// argument deduction for a class template partial
7139 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7140 ClassTemplatePartialSpecializationDecl *PartialSpec,
7141 ArrayRef<TemplateArgument> TemplateArgs,
7142 sema::TemplateDeductionInfo &DeductionInfo,
7143 SourceRange InstantiationRange = SourceRange());
7145 /// \brief Note that we are instantiating as part of template
7146 /// argument deduction for a variable template partial
7148 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7149 VarTemplatePartialSpecializationDecl *PartialSpec,
7150 ArrayRef<TemplateArgument> TemplateArgs,
7151 sema::TemplateDeductionInfo &DeductionInfo,
7152 SourceRange InstantiationRange = SourceRange());
7154 /// \brief Note that we are instantiating a default argument for a function
7156 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7158 ArrayRef<TemplateArgument> TemplateArgs,
7159 SourceRange InstantiationRange = SourceRange());
7161 /// \brief Note that we are substituting prior template arguments into a
7162 /// non-type parameter.
7163 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7164 NamedDecl *Template,
7165 NonTypeTemplateParmDecl *Param,
7166 ArrayRef<TemplateArgument> TemplateArgs,
7167 SourceRange InstantiationRange);
7169 /// \brief Note that we are substituting prior template arguments into a
7170 /// template template parameter.
7171 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7172 NamedDecl *Template,
7173 TemplateTemplateParmDecl *Param,
7174 ArrayRef<TemplateArgument> TemplateArgs,
7175 SourceRange InstantiationRange);
7177 /// \brief Note that we are checking the default template argument
7178 /// against the template parameter for a given template-id.
7179 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7180 TemplateDecl *Template,
7182 ArrayRef<TemplateArgument> TemplateArgs,
7183 SourceRange InstantiationRange);
7186 /// \brief Note that we have finished instantiating this template.
7189 ~InstantiatingTemplate() { Clear(); }
7191 /// \brief Determines whether we have exceeded the maximum
7192 /// recursive template instantiations.
7193 bool isInvalid() const { return Invalid; }
7195 /// \brief Determine whether we are already instantiating this
7196 /// specialization in some surrounding active instantiation.
7197 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7202 bool AlreadyInstantiating;
7203 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7204 SourceRange InstantiationRange);
7206 InstantiatingTemplate(
7207 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7208 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7209 Decl *Entity, NamedDecl *Template = nullptr,
7210 ArrayRef<TemplateArgument> TemplateArgs = None,
7211 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7213 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7215 InstantiatingTemplate&
7216 operator=(const InstantiatingTemplate&) = delete;
7219 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7220 void popCodeSynthesisContext();
7222 /// Determine whether we are currently performing template instantiation.
7223 bool inTemplateInstantiation() const {
7224 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7227 void PrintContextStack() {
7228 if (!CodeSynthesisContexts.empty() &&
7229 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7230 PrintInstantiationStack();
7231 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7233 if (PragmaAttributeCurrentTargetDecl)
7234 PrintPragmaAttributeInstantiationPoint();
7236 void PrintInstantiationStack();
7238 void PrintPragmaAttributeInstantiationPoint();
7240 /// \brief Determines whether we are currently in a context where
7241 /// template argument substitution failures are not considered
7244 /// \returns An empty \c Optional if we're not in a SFINAE context.
7245 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7246 /// template-deduction context object, which can be used to capture
7247 /// diagnostics that will be suppressed.
7248 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7250 /// \brief Determines whether we are currently in a context that
7251 /// is not evaluated as per C++ [expr] p5.
7252 bool isUnevaluatedContext() const {
7253 assert(!ExprEvalContexts.empty() &&
7254 "Must be in an expression evaluation context");
7255 return ExprEvalContexts.back().isUnevaluated();
7258 /// \brief RAII class used to determine whether SFINAE has
7259 /// trapped any errors that occur during template argument
7263 unsigned PrevSFINAEErrors;
7264 bool PrevInNonInstantiationSFINAEContext;
7265 bool PrevAccessCheckingSFINAE;
7268 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7269 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7270 PrevInNonInstantiationSFINAEContext(
7271 SemaRef.InNonInstantiationSFINAEContext),
7272 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7274 if (!SemaRef.isSFINAEContext())
7275 SemaRef.InNonInstantiationSFINAEContext = true;
7276 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7280 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7281 SemaRef.InNonInstantiationSFINAEContext
7282 = PrevInNonInstantiationSFINAEContext;
7283 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7286 /// \brief Determine whether any SFINAE errors have been trapped.
7287 bool hasErrorOccurred() const {
7288 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7292 /// \brief RAII class used to indicate that we are performing provisional
7293 /// semantic analysis to determine the validity of a construct, so
7294 /// typo-correction and diagnostics in the immediate context (not within
7295 /// implicitly-instantiated templates) should be suppressed.
7296 class TentativeAnalysisScope {
7298 // FIXME: Using a SFINAETrap for this is a hack.
7300 bool PrevDisableTypoCorrection;
7302 explicit TentativeAnalysisScope(Sema &SemaRef)
7303 : SemaRef(SemaRef), Trap(SemaRef, true),
7304 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7305 SemaRef.DisableTypoCorrection = true;
7307 ~TentativeAnalysisScope() {
7308 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7312 /// \brief The current instantiation scope used to store local
7314 LocalInstantiationScope *CurrentInstantiationScope;
7316 /// \brief Tracks whether we are in a context where typo correction is
7318 bool DisableTypoCorrection;
7320 /// \brief The number of typos corrected by CorrectTypo.
7321 unsigned TyposCorrected;
7323 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7324 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7326 /// \brief A cache containing identifiers for which typo correction failed and
7327 /// their locations, so that repeated attempts to correct an identifier in a
7328 /// given location are ignored if typo correction already failed for it.
7329 IdentifierSourceLocations TypoCorrectionFailures;
7331 /// \brief Worker object for performing CFG-based warnings.
7332 sema::AnalysisBasedWarnings AnalysisWarnings;
7333 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7335 /// \brief An entity for which implicit template instantiation is required.
7337 /// The source location associated with the declaration is the first place in
7338 /// the source code where the declaration was "used". It is not necessarily
7339 /// the point of instantiation (which will be either before or after the
7340 /// namespace-scope declaration that triggered this implicit instantiation),
7341 /// However, it is the location that diagnostics should generally refer to,
7342 /// because users will need to know what code triggered the instantiation.
7343 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7345 /// \brief The queue of implicit template instantiations that are required
7346 /// but have not yet been performed.
7347 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7349 class SavePendingInstantiationsAndVTableUsesRAII {
7351 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7352 : S(S), Enabled(Enabled) {
7353 if (!Enabled) return;
7355 SavedPendingInstantiations.swap(S.PendingInstantiations);
7356 SavedVTableUses.swap(S.VTableUses);
7359 ~SavePendingInstantiationsAndVTableUsesRAII() {
7360 if (!Enabled) return;
7362 // Restore the set of pending vtables.
7363 assert(S.VTableUses.empty() &&
7364 "VTableUses should be empty before it is discarded.");
7365 S.VTableUses.swap(SavedVTableUses);
7367 // Restore the set of pending implicit instantiations.
7368 assert(S.PendingInstantiations.empty() &&
7369 "PendingInstantiations should be empty before it is discarded.");
7370 S.PendingInstantiations.swap(SavedPendingInstantiations);
7375 SmallVector<VTableUse, 16> SavedVTableUses;
7376 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7380 /// \brief The queue of implicit template instantiations that are required
7381 /// and must be performed within the current local scope.
7383 /// This queue is only used for member functions of local classes in
7384 /// templates, which must be instantiated in the same scope as their
7385 /// enclosing function, so that they can reference function-local
7386 /// types, static variables, enumerators, etc.
7387 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7389 class SavePendingLocalImplicitInstantiationsRAII {
7391 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7392 SavedPendingLocalImplicitInstantiations.swap(
7393 S.PendingLocalImplicitInstantiations);
7396 ~SavePendingLocalImplicitInstantiationsRAII() {
7397 assert(S.PendingLocalImplicitInstantiations.empty() &&
7398 "there shouldn't be any pending local implicit instantiations");
7399 SavedPendingLocalImplicitInstantiations.swap(
7400 S.PendingLocalImplicitInstantiations);
7405 std::deque<PendingImplicitInstantiation>
7406 SavedPendingLocalImplicitInstantiations;
7409 /// A helper class for building up ExtParameterInfos.
7410 class ExtParameterInfoBuilder {
7411 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7412 bool HasInteresting = false;
7415 /// Set the ExtParameterInfo for the parameter at the given index,
7417 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7418 assert(Infos.size() <= index);
7419 Infos.resize(index);
7420 Infos.push_back(info);
7422 if (!HasInteresting)
7423 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7426 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7427 /// ExtParameterInfo array we've built up.
7428 const FunctionProtoType::ExtParameterInfo *
7429 getPointerOrNull(unsigned numParams) {
7430 if (!HasInteresting) return nullptr;
7431 Infos.resize(numParams);
7432 return Infos.data();
7436 void PerformPendingInstantiations(bool LocalOnly = false);
7438 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7439 const MultiLevelTemplateArgumentList &TemplateArgs,
7440 SourceLocation Loc, DeclarationName Entity,
7441 bool AllowDeducedTST = false);
7443 QualType SubstType(QualType T,
7444 const MultiLevelTemplateArgumentList &TemplateArgs,
7445 SourceLocation Loc, DeclarationName Entity);
7447 TypeSourceInfo *SubstType(TypeLoc TL,
7448 const MultiLevelTemplateArgumentList &TemplateArgs,
7449 SourceLocation Loc, DeclarationName Entity);
7451 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7452 const MultiLevelTemplateArgumentList &TemplateArgs,
7454 DeclarationName Entity,
7455 CXXRecordDecl *ThisContext,
7456 unsigned ThisTypeQuals);
7457 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7458 const MultiLevelTemplateArgumentList &Args);
7459 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7460 const MultiLevelTemplateArgumentList &TemplateArgs,
7461 int indexAdjustment,
7462 Optional<unsigned> NumExpansions,
7463 bool ExpectParameterPack);
7464 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7465 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7466 const MultiLevelTemplateArgumentList &TemplateArgs,
7467 SmallVectorImpl<QualType> &ParamTypes,
7468 SmallVectorImpl<ParmVarDecl *> *OutParams,
7469 ExtParameterInfoBuilder &ParamInfos);
7470 ExprResult SubstExpr(Expr *E,
7471 const MultiLevelTemplateArgumentList &TemplateArgs);
7473 /// \brief Substitute the given template arguments into a list of
7474 /// expressions, expanding pack expansions if required.
7476 /// \param Exprs The list of expressions to substitute into.
7478 /// \param IsCall Whether this is some form of call, in which case
7479 /// default arguments will be dropped.
7481 /// \param TemplateArgs The set of template arguments to substitute.
7483 /// \param Outputs Will receive all of the substituted arguments.
7485 /// \returns true if an error occurred, false otherwise.
7486 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7487 const MultiLevelTemplateArgumentList &TemplateArgs,
7488 SmallVectorImpl<Expr *> &Outputs);
7490 StmtResult SubstStmt(Stmt *S,
7491 const MultiLevelTemplateArgumentList &TemplateArgs);
7493 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7494 const MultiLevelTemplateArgumentList &TemplateArgs);
7496 ExprResult SubstInitializer(Expr *E,
7497 const MultiLevelTemplateArgumentList &TemplateArgs,
7498 bool CXXDirectInit);
7501 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7502 CXXRecordDecl *Pattern,
7503 const MultiLevelTemplateArgumentList &TemplateArgs);
7506 InstantiateClass(SourceLocation PointOfInstantiation,
7507 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7508 const MultiLevelTemplateArgumentList &TemplateArgs,
7509 TemplateSpecializationKind TSK,
7510 bool Complain = true);
7512 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7513 EnumDecl *Instantiation, EnumDecl *Pattern,
7514 const MultiLevelTemplateArgumentList &TemplateArgs,
7515 TemplateSpecializationKind TSK);
7517 bool InstantiateInClassInitializer(
7518 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7519 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7521 struct LateInstantiatedAttribute {
7522 const Attr *TmplAttr;
7523 LocalInstantiationScope *Scope;
7526 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7528 : TmplAttr(A), Scope(S), NewDecl(D)
7531 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7533 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7534 const Decl *Pattern, Decl *Inst,
7535 LateInstantiatedAttrVec *LateAttrs = nullptr,
7536 LocalInstantiationScope *OuterMostScope = nullptr);
7539 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7540 const Decl *Pattern, Decl *Inst,
7541 LateInstantiatedAttrVec *LateAttrs = nullptr,
7542 LocalInstantiationScope *OuterMostScope = nullptr);
7545 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7546 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7547 TemplateSpecializationKind TSK,
7548 bool Complain = true);
7550 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7551 CXXRecordDecl *Instantiation,
7552 const MultiLevelTemplateArgumentList &TemplateArgs,
7553 TemplateSpecializationKind TSK);
7555 void InstantiateClassTemplateSpecializationMembers(
7556 SourceLocation PointOfInstantiation,
7557 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7558 TemplateSpecializationKind TSK);
7560 NestedNameSpecifierLoc
7561 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7562 const MultiLevelTemplateArgumentList &TemplateArgs);
7565 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7566 const MultiLevelTemplateArgumentList &TemplateArgs);
7568 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7570 const MultiLevelTemplateArgumentList &TemplateArgs);
7571 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7572 TemplateArgumentListInfo &Result,
7573 const MultiLevelTemplateArgumentList &TemplateArgs);
7575 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7576 FunctionDecl *Function);
7577 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7578 FunctionDecl *Function,
7579 bool Recursive = false,
7580 bool DefinitionRequired = false,
7581 bool AtEndOfTU = false);
7582 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7583 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7584 const TemplateArgumentList &TemplateArgList,
7585 const TemplateArgumentListInfo &TemplateArgsInfo,
7586 SmallVectorImpl<TemplateArgument> &Converted,
7587 SourceLocation PointOfInstantiation, void *InsertPos,
7588 LateInstantiatedAttrVec *LateAttrs = nullptr,
7589 LocalInstantiationScope *StartingScope = nullptr);
7590 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7591 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7592 const MultiLevelTemplateArgumentList &TemplateArgs);
7594 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7595 const MultiLevelTemplateArgumentList &TemplateArgs,
7596 LateInstantiatedAttrVec *LateAttrs,
7598 LocalInstantiationScope *StartingScope,
7599 bool InstantiatingVarTemplate = false);
7600 void InstantiateVariableInitializer(
7601 VarDecl *Var, VarDecl *OldVar,
7602 const MultiLevelTemplateArgumentList &TemplateArgs);
7603 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7604 VarDecl *Var, bool Recursive = false,
7605 bool DefinitionRequired = false,
7606 bool AtEndOfTU = false);
7607 void InstantiateStaticDataMemberDefinition(
7608 SourceLocation PointOfInstantiation,
7610 bool Recursive = false,
7611 bool DefinitionRequired = false);
7613 void InstantiateMemInitializers(CXXConstructorDecl *New,
7614 const CXXConstructorDecl *Tmpl,
7615 const MultiLevelTemplateArgumentList &TemplateArgs);
7617 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7618 const MultiLevelTemplateArgumentList &TemplateArgs);
7619 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7620 const MultiLevelTemplateArgumentList &TemplateArgs);
7622 // Objective-C declarations.
7623 enum ObjCContainerKind {
7630 OCK_CategoryImplementation
7632 ObjCContainerKind getObjCContainerKind() const;
7634 DeclResult actOnObjCTypeParam(Scope *S,
7635 ObjCTypeParamVariance variance,
7636 SourceLocation varianceLoc,
7638 IdentifierInfo *paramName,
7639 SourceLocation paramLoc,
7640 SourceLocation colonLoc,
7641 ParsedType typeBound);
7643 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7644 ArrayRef<Decl *> typeParams,
7645 SourceLocation rAngleLoc);
7646 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7648 Decl *ActOnStartClassInterface(Scope *S,
7649 SourceLocation AtInterfaceLoc,
7650 IdentifierInfo *ClassName,
7651 SourceLocation ClassLoc,
7652 ObjCTypeParamList *typeParamList,
7653 IdentifierInfo *SuperName,
7654 SourceLocation SuperLoc,
7655 ArrayRef<ParsedType> SuperTypeArgs,
7656 SourceRange SuperTypeArgsRange,
7657 Decl * const *ProtoRefs,
7658 unsigned NumProtoRefs,
7659 const SourceLocation *ProtoLocs,
7660 SourceLocation EndProtoLoc,
7661 AttributeList *AttrList);
7663 void ActOnSuperClassOfClassInterface(Scope *S,
7664 SourceLocation AtInterfaceLoc,
7665 ObjCInterfaceDecl *IDecl,
7666 IdentifierInfo *ClassName,
7667 SourceLocation ClassLoc,
7668 IdentifierInfo *SuperName,
7669 SourceLocation SuperLoc,
7670 ArrayRef<ParsedType> SuperTypeArgs,
7671 SourceRange SuperTypeArgsRange);
7673 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7674 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7675 IdentifierInfo *SuperName,
7676 SourceLocation SuperLoc);
7678 Decl *ActOnCompatibilityAlias(
7679 SourceLocation AtCompatibilityAliasLoc,
7680 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7681 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7683 bool CheckForwardProtocolDeclarationForCircularDependency(
7684 IdentifierInfo *PName,
7685 SourceLocation &PLoc, SourceLocation PrevLoc,
7686 const ObjCList<ObjCProtocolDecl> &PList);
7688 Decl *ActOnStartProtocolInterface(
7689 SourceLocation AtProtoInterfaceLoc,
7690 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7691 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7692 const SourceLocation *ProtoLocs,
7693 SourceLocation EndProtoLoc,
7694 AttributeList *AttrList);
7696 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7697 IdentifierInfo *ClassName,
7698 SourceLocation ClassLoc,
7699 ObjCTypeParamList *typeParamList,
7700 IdentifierInfo *CategoryName,
7701 SourceLocation CategoryLoc,
7702 Decl * const *ProtoRefs,
7703 unsigned NumProtoRefs,
7704 const SourceLocation *ProtoLocs,
7705 SourceLocation EndProtoLoc,
7706 AttributeList *AttrList);
7708 Decl *ActOnStartClassImplementation(
7709 SourceLocation AtClassImplLoc,
7710 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7711 IdentifierInfo *SuperClassname,
7712 SourceLocation SuperClassLoc);
7714 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7715 IdentifierInfo *ClassName,
7716 SourceLocation ClassLoc,
7717 IdentifierInfo *CatName,
7718 SourceLocation CatLoc);
7720 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7721 ArrayRef<Decl *> Decls);
7723 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7724 IdentifierInfo **IdentList,
7725 SourceLocation *IdentLocs,
7726 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7729 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7730 ArrayRef<IdentifierLocPair> IdentList,
7731 AttributeList *attrList);
7733 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7734 ArrayRef<IdentifierLocPair> ProtocolId,
7735 SmallVectorImpl<Decl *> &Protocols);
7737 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7738 SourceLocation ProtocolLoc,
7739 IdentifierInfo *TypeArgId,
7740 SourceLocation TypeArgLoc,
7741 bool SelectProtocolFirst = false);
7743 /// Given a list of identifiers (and their locations), resolve the
7744 /// names to either Objective-C protocol qualifiers or type
7745 /// arguments, as appropriate.
7746 void actOnObjCTypeArgsOrProtocolQualifiers(
7748 ParsedType baseType,
7749 SourceLocation lAngleLoc,
7750 ArrayRef<IdentifierInfo *> identifiers,
7751 ArrayRef<SourceLocation> identifierLocs,
7752 SourceLocation rAngleLoc,
7753 SourceLocation &typeArgsLAngleLoc,
7754 SmallVectorImpl<ParsedType> &typeArgs,
7755 SourceLocation &typeArgsRAngleLoc,
7756 SourceLocation &protocolLAngleLoc,
7757 SmallVectorImpl<Decl *> &protocols,
7758 SourceLocation &protocolRAngleLoc,
7759 bool warnOnIncompleteProtocols);
7761 /// Build a an Objective-C protocol-qualified 'id' type where no
7762 /// base type was specified.
7763 TypeResult actOnObjCProtocolQualifierType(
7764 SourceLocation lAngleLoc,
7765 ArrayRef<Decl *> protocols,
7766 ArrayRef<SourceLocation> protocolLocs,
7767 SourceLocation rAngleLoc);
7769 /// Build a specialized and/or protocol-qualified Objective-C type.
7770 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7773 ParsedType BaseType,
7774 SourceLocation TypeArgsLAngleLoc,
7775 ArrayRef<ParsedType> TypeArgs,
7776 SourceLocation TypeArgsRAngleLoc,
7777 SourceLocation ProtocolLAngleLoc,
7778 ArrayRef<Decl *> Protocols,
7779 ArrayRef<SourceLocation> ProtocolLocs,
7780 SourceLocation ProtocolRAngleLoc);
7782 /// Build an Objective-C type parameter type.
7783 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7784 SourceLocation ProtocolLAngleLoc,
7785 ArrayRef<ObjCProtocolDecl *> Protocols,
7786 ArrayRef<SourceLocation> ProtocolLocs,
7787 SourceLocation ProtocolRAngleLoc,
7788 bool FailOnError = false);
7790 /// Build an Objective-C object pointer type.
7791 QualType BuildObjCObjectType(QualType BaseType,
7793 SourceLocation TypeArgsLAngleLoc,
7794 ArrayRef<TypeSourceInfo *> TypeArgs,
7795 SourceLocation TypeArgsRAngleLoc,
7796 SourceLocation ProtocolLAngleLoc,
7797 ArrayRef<ObjCProtocolDecl *> Protocols,
7798 ArrayRef<SourceLocation> ProtocolLocs,
7799 SourceLocation ProtocolRAngleLoc,
7800 bool FailOnError = false);
7802 /// Check the application of the Objective-C '__kindof' qualifier to
7804 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7806 /// Ensure attributes are consistent with type.
7807 /// \param [in, out] Attributes The attributes to check; they will
7808 /// be modified to be consistent with \p PropertyTy.
7809 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7811 unsigned &Attributes,
7812 bool propertyInPrimaryClass);
7814 /// Process the specified property declaration and create decls for the
7815 /// setters and getters as needed.
7816 /// \param property The property declaration being processed
7817 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7820 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7821 ObjCPropertyDecl *SuperProperty,
7822 const IdentifierInfo *Name,
7823 bool OverridingProtocolProperty);
7825 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7826 ObjCInterfaceDecl *ID);
7828 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7829 ArrayRef<Decl *> allMethods = None,
7830 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7832 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7833 SourceLocation LParenLoc,
7834 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7835 Selector GetterSel, Selector SetterSel,
7836 tok::ObjCKeywordKind MethodImplKind,
7837 DeclContext *lexicalDC = nullptr);
7839 Decl *ActOnPropertyImplDecl(Scope *S,
7840 SourceLocation AtLoc,
7841 SourceLocation PropertyLoc,
7843 IdentifierInfo *PropertyId,
7844 IdentifierInfo *PropertyIvar,
7845 SourceLocation PropertyIvarLoc,
7846 ObjCPropertyQueryKind QueryKind);
7848 enum ObjCSpecialMethodKind {
7854 OSMK_NonRetainingInit
7857 struct ObjCArgInfo {
7858 IdentifierInfo *Name;
7859 SourceLocation NameLoc;
7860 // The Type is null if no type was specified, and the DeclSpec is invalid
7863 ObjCDeclSpec DeclSpec;
7865 /// ArgAttrs - Attribute list for this argument.
7866 AttributeList *ArgAttrs;
7869 Decl *ActOnMethodDeclaration(
7871 SourceLocation BeginLoc, // location of the + or -.
7872 SourceLocation EndLoc, // location of the ; or {.
7873 tok::TokenKind MethodType,
7874 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7875 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7876 // optional arguments. The number of types/arguments is obtained
7877 // from the Sel.getNumArgs().
7878 ObjCArgInfo *ArgInfo,
7879 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7880 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7881 bool isVariadic, bool MethodDefinition);
7883 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7884 const ObjCObjectPointerType *OPT,
7886 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7889 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7890 bool inferObjCARCLifetime(ValueDecl *decl);
7893 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7895 SourceLocation OpLoc,
7896 DeclarationName MemberName,
7897 SourceLocation MemberLoc,
7898 SourceLocation SuperLoc, QualType SuperType,
7902 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7903 IdentifierInfo &propertyName,
7904 SourceLocation receiverNameLoc,
7905 SourceLocation propertyNameLoc);
7907 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7909 /// \brief Describes the kind of message expression indicated by a message
7910 /// send that starts with an identifier.
7911 enum ObjCMessageKind {
7912 /// \brief The message is sent to 'super'.
7914 /// \brief The message is an instance message.
7915 ObjCInstanceMessage,
7916 /// \brief The message is a class message, and the identifier is a type
7921 ObjCMessageKind getObjCMessageKind(Scope *S,
7922 IdentifierInfo *Name,
7923 SourceLocation NameLoc,
7925 bool HasTrailingDot,
7926 ParsedType &ReceiverType);
7928 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7930 SourceLocation LBracLoc,
7931 ArrayRef<SourceLocation> SelectorLocs,
7932 SourceLocation RBracLoc,
7935 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7936 QualType ReceiverType,
7937 SourceLocation SuperLoc,
7939 ObjCMethodDecl *Method,
7940 SourceLocation LBracLoc,
7941 ArrayRef<SourceLocation> SelectorLocs,
7942 SourceLocation RBracLoc,
7944 bool isImplicit = false);
7946 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7947 bool isSuperReceiver,
7950 ObjCMethodDecl *Method,
7953 ExprResult ActOnClassMessage(Scope *S,
7954 ParsedType Receiver,
7956 SourceLocation LBracLoc,
7957 ArrayRef<SourceLocation> SelectorLocs,
7958 SourceLocation RBracLoc,
7961 ExprResult BuildInstanceMessage(Expr *Receiver,
7962 QualType ReceiverType,
7963 SourceLocation SuperLoc,
7965 ObjCMethodDecl *Method,
7966 SourceLocation LBracLoc,
7967 ArrayRef<SourceLocation> SelectorLocs,
7968 SourceLocation RBracLoc,
7970 bool isImplicit = false);
7972 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7973 QualType ReceiverType,
7976 ObjCMethodDecl *Method,
7979 ExprResult ActOnInstanceMessage(Scope *S,
7982 SourceLocation LBracLoc,
7983 ArrayRef<SourceLocation> SelectorLocs,
7984 SourceLocation RBracLoc,
7987 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7988 ObjCBridgeCastKind Kind,
7989 SourceLocation BridgeKeywordLoc,
7990 TypeSourceInfo *TSInfo,
7993 ExprResult ActOnObjCBridgedCast(Scope *S,
7994 SourceLocation LParenLoc,
7995 ObjCBridgeCastKind Kind,
7996 SourceLocation BridgeKeywordLoc,
7998 SourceLocation RParenLoc,
8001 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8003 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8005 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8008 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8009 QualType DestType, QualType SrcType,
8010 ObjCInterfaceDecl *&RelatedClass,
8011 ObjCMethodDecl *&ClassMethod,
8012 ObjCMethodDecl *&InstanceMethod,
8013 TypedefNameDecl *&TDNDecl,
8014 bool CfToNs, bool Diagnose = true);
8016 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8017 QualType DestType, QualType SrcType,
8018 Expr *&SrcExpr, bool Diagnose = true);
8020 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8021 bool Diagnose = true);
8023 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8025 /// \brief Check whether the given new method is a valid override of the
8026 /// given overridden method, and set any properties that should be inherited.
8027 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8028 const ObjCMethodDecl *Overridden);
8030 /// \brief Describes the compatibility of a result type with its method.
8031 enum ResultTypeCompatibilityKind {
8037 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8038 ObjCInterfaceDecl *CurrentClass,
8039 ResultTypeCompatibilityKind RTC);
8041 enum PragmaOptionsAlignKind {
8042 POAK_Native, // #pragma options align=native
8043 POAK_Natural, // #pragma options align=natural
8044 POAK_Packed, // #pragma options align=packed
8045 POAK_Power, // #pragma options align=power
8046 POAK_Mac68k, // #pragma options align=mac68k
8047 POAK_Reset // #pragma options align=reset
8050 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8051 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8052 SourceLocation PragmaLoc);
8054 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8055 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8056 StringRef SlotLabel, Expr *Alignment);
8058 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8059 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8061 /// ActOnPragmaMSComment - Called on well formed
8062 /// \#pragma comment(kind, "arg").
8063 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8066 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8067 /// pointers_to_members(representation method[, general purpose
8068 /// representation]).
8069 void ActOnPragmaMSPointersToMembers(
8070 LangOptions::PragmaMSPointersToMembersKind Kind,
8071 SourceLocation PragmaLoc);
8073 /// \brief Called on well formed \#pragma vtordisp().
8074 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8075 SourceLocation PragmaLoc,
8076 MSVtorDispAttr::Mode Value);
8078 enum PragmaSectionKind {
8085 bool UnifySection(StringRef SectionName,
8087 DeclaratorDecl *TheDecl);
8088 bool UnifySection(StringRef SectionName,
8090 SourceLocation PragmaSectionLocation);
8092 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8093 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8094 PragmaMsStackAction Action,
8095 llvm::StringRef StackSlotLabel,
8096 StringLiteral *SegmentName,
8097 llvm::StringRef PragmaName);
8099 /// \brief Called on well formed \#pragma section().
8100 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8101 int SectionFlags, StringLiteral *SegmentName);
8103 /// \brief Called on well-formed \#pragma init_seg().
8104 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8105 StringLiteral *SegmentName);
8107 /// \brief Called on #pragma clang __debug dump II
8108 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8110 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8111 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8114 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8115 void ActOnPragmaUnused(const Token &Identifier,
8117 SourceLocation PragmaLoc);
8119 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8120 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8121 SourceLocation PragmaLoc);
8123 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8124 SourceLocation Loc);
8125 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8127 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8128 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8129 SourceLocation PragmaLoc,
8130 SourceLocation WeakNameLoc);
8132 /// ActOnPragmaRedefineExtname - Called on well formed
8133 /// \#pragma redefine_extname oldname newname.
8134 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8135 IdentifierInfo* AliasName,
8136 SourceLocation PragmaLoc,
8137 SourceLocation WeakNameLoc,
8138 SourceLocation AliasNameLoc);
8140 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8141 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8142 IdentifierInfo* AliasName,
8143 SourceLocation PragmaLoc,
8144 SourceLocation WeakNameLoc,
8145 SourceLocation AliasNameLoc);
8147 /// ActOnPragmaFPContract - Called on well formed
8148 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8149 /// \#pragma clang fp contract
8150 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8152 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8153 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8154 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8156 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8157 void AddMsStructLayoutForRecord(RecordDecl *RD);
8159 /// FreePackedContext - Deallocate and null out PackContext.
8160 void FreePackedContext();
8162 /// PushNamespaceVisibilityAttr - Note that we've entered a
8163 /// namespace with a visibility attribute.
8164 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8165 SourceLocation Loc);
8167 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8168 /// add an appropriate visibility attribute.
8169 void AddPushedVisibilityAttribute(Decl *RD);
8171 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8172 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8173 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8175 /// FreeVisContext - Deallocate and null out VisContext.
8176 void FreeVisContext();
8178 /// AddCFAuditedAttribute - Check whether we're currently within
8179 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8180 /// the appropriate attribute.
8181 void AddCFAuditedAttribute(Decl *D);
8183 /// \brief Called on well-formed '\#pragma clang attribute push'.
8184 void ActOnPragmaAttributePush(AttributeList &Attribute,
8185 SourceLocation PragmaLoc,
8186 attr::ParsedSubjectMatchRuleSet Rules);
8188 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8189 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8191 /// \brief Adds the attributes that have been specified using the
8192 /// '\#pragma clang attribute push' directives to the given declaration.
8193 void AddPragmaAttributes(Scope *S, Decl *D);
8195 void DiagnoseUnterminatedPragmaAttribute();
8197 /// \brief Called on well formed \#pragma clang optimize.
8198 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8200 /// \brief Get the location for the currently active "\#pragma clang optimize
8201 /// off". If this location is invalid, then the state of the pragma is "on".
8202 SourceLocation getOptimizeOffPragmaLocation() const {
8203 return OptimizeOffPragmaLocation;
8206 /// \brief Only called on function definitions; if there is a pragma in scope
8207 /// with the effect of a range-based optnone, consider marking the function
8208 /// with attribute optnone.
8209 void AddRangeBasedOptnone(FunctionDecl *FD);
8211 /// \brief Adds the 'optnone' attribute to the function declaration if there
8212 /// are no conflicts; Loc represents the location causing the 'optnone'
8213 /// attribute to be added (usually because of a pragma).
8214 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8216 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8217 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8218 unsigned SpellingListIndex, bool IsPackExpansion);
8219 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8220 unsigned SpellingListIndex, bool IsPackExpansion);
8222 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8224 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8225 unsigned SpellingListIndex);
8227 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8229 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8230 unsigned SpellingListIndex);
8232 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8234 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8235 unsigned SpellingListIndex);
8237 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8239 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8240 Expr *MinBlocks, unsigned SpellingListIndex);
8242 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8243 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8244 unsigned SpellingListIndex, bool InInstantiation = false);
8246 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8247 ParameterABI ABI, unsigned SpellingListIndex);
8249 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8250 unsigned SpellingListIndex, bool isNSConsumed,
8251 bool isTemplateInstantiation);
8253 //===--------------------------------------------------------------------===//
8254 // C++ Coroutines TS
8256 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8257 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8258 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8260 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8261 bool IsImplicit = false);
8262 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8263 UnresolvedLookupExpr* Lookup);
8264 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8265 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8266 bool IsImplicit = false);
8267 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8268 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8269 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8271 //===--------------------------------------------------------------------===//
8272 // OpenCL extensions.
8275 std::string CurrOpenCLExtension;
8276 /// Extensions required by an OpenCL type.
8277 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8278 /// Extensions required by an OpenCL declaration.
8279 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8281 llvm::StringRef getCurrentOpenCLExtension() const {
8282 return CurrOpenCLExtension;
8284 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8285 CurrOpenCLExtension = Ext;
8288 /// \brief Set OpenCL extensions for a type which can only be used when these
8289 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8290 /// \param Exts A space separated list of OpenCL extensions.
8291 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8293 /// \brief Set OpenCL extensions for a declaration which can only be
8294 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8296 /// \param Exts A space separated list of OpenCL extensions.
8297 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8299 /// \brief Set current OpenCL extensions for a type which can only be used
8300 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8301 /// empty, do nothing.
8302 void setCurrentOpenCLExtensionForType(QualType T);
8304 /// \brief Set current OpenCL extensions for a declaration which
8305 /// can only be used when these OpenCL extensions are enabled. If current
8306 /// OpenCL extension is empty, do nothing.
8307 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8309 bool isOpenCLDisabledDecl(Decl *FD);
8311 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8312 /// is disabled due to required OpenCL extensions being disabled. If so,
8313 /// emit diagnostics.
8314 /// \return true if type is disabled.
8315 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8317 /// \brief Check if declaration \p D used by expression \p E
8318 /// is disabled due to required OpenCL extensions being disabled. If so,
8319 /// emit diagnostics.
8320 /// \return true if type is disabled.
8321 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8323 //===--------------------------------------------------------------------===//
8324 // OpenMP directives and clauses.
8327 void *VarDataSharingAttributesStack;
8328 /// Set to true inside '#pragma omp declare target' region.
8329 bool IsInOpenMPDeclareTargetContext = false;
8330 /// \brief Initialization of data-sharing attributes stack.
8331 void InitDataSharingAttributesStack();
8332 void DestroyDataSharingAttributesStack();
8334 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8335 bool StrictlyPositive = true);
8336 /// Returns OpenMP nesting level for current directive.
8337 unsigned getOpenMPNestingLevel() const;
8339 /// Push new OpenMP function region for non-capturing function.
8340 void pushOpenMPFunctionRegion();
8342 /// Pop OpenMP function region for non-capturing function.
8343 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8345 /// Checks if a type or a declaration is disabled due to the owning extension
8346 /// being disabled, and emits diagnostic messages if it is disabled.
8347 /// \param D type or declaration to be checked.
8348 /// \param DiagLoc source location for the diagnostic message.
8349 /// \param DiagInfo information to be emitted for the diagnostic message.
8350 /// \param SrcRange source range of the declaration.
8351 /// \param Map maps type or declaration to the extensions.
8352 /// \param Selector selects diagnostic message: 0 for type and 1 for
8354 /// \return true if the type or declaration is disabled.
8355 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8356 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8357 MapT &Map, unsigned Selector = 0,
8358 SourceRange SrcRange = SourceRange());
8361 /// \brief Return true if the provided declaration \a VD should be captured by
8363 /// \param Level Relative level of nested OpenMP construct for that the check
8365 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8367 /// \brief Check if the specified variable is used in one of the private
8368 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8370 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8371 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8372 ExprObjectKind OK, SourceLocation Loc);
8374 /// \brief Check if the specified variable is used in 'private' clause.
8375 /// \param Level Relative level of nested OpenMP construct for that the check
8377 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8379 /// \brief Check if the specified variable is captured by 'target' directive.
8380 /// \param Level Relative level of nested OpenMP construct for that the check
8382 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8384 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8386 /// \brief Called on start of new data sharing attribute block.
8387 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8388 const DeclarationNameInfo &DirName, Scope *CurScope,
8389 SourceLocation Loc);
8390 /// \brief Start analysis of clauses.
8391 void StartOpenMPClause(OpenMPClauseKind K);
8392 /// \brief End analysis of clauses.
8393 void EndOpenMPClause();
8394 /// \brief Called on end of data sharing attribute block.
8395 void EndOpenMPDSABlock(Stmt *CurDirective);
8397 /// \brief Check if the current region is an OpenMP loop region and if it is,
8398 /// mark loop control variable, used in \p Init for loop initialization, as
8399 /// private by default.
8400 /// \param Init First part of the for loop.
8401 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8403 // OpenMP directives and clauses.
8404 /// \brief Called on correct id-expression from the '#pragma omp
8406 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8407 CXXScopeSpec &ScopeSpec,
8408 const DeclarationNameInfo &Id);
8409 /// \brief Called on well-formed '#pragma omp threadprivate'.
8410 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8412 ArrayRef<Expr *> VarList);
8413 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8414 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8416 ArrayRef<Expr *> VarList);
8417 /// \brief Check if the specified type is allowed to be used in 'omp declare
8418 /// reduction' construct.
8419 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8420 TypeResult ParsedType);
8421 /// \brief Called on start of '#pragma omp declare reduction'.
8422 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8423 Scope *S, DeclContext *DC, DeclarationName Name,
8424 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8425 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8426 /// \brief Initialize declare reduction construct initializer.
8427 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8428 /// \brief Finish current declare reduction construct initializer.
8429 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8430 /// \brief Initialize declare reduction construct initializer.
8431 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8432 /// \brief Finish current declare reduction construct initializer.
8433 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8434 /// \brief Called at the end of '#pragma omp declare reduction'.
8435 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8436 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8438 /// Called on the start of target region i.e. '#pragma omp declare target'.
8439 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8440 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8441 void ActOnFinishOpenMPDeclareTargetDirective();
8442 /// Called on correct id-expression from the '#pragma omp declare target'.
8443 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8444 const DeclarationNameInfo &Id,
8445 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8446 NamedDeclSetType &SameDirectiveDecls);
8447 /// Check declaration inside target region.
8448 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8449 /// Return true inside OpenMP target region.
8450 bool isInOpenMPDeclareTargetContext() const {
8451 return IsInOpenMPDeclareTargetContext;
8454 /// Return the number of captured regions created for an OpenMP directive.
8455 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8457 /// \brief Initialization of captured region for OpenMP region.
8458 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8459 /// \brief End of OpenMP region.
8461 /// \param S Statement associated with the current OpenMP region.
8462 /// \param Clauses List of clauses for the current OpenMP region.
8464 /// \returns Statement for finished OpenMP region.
8465 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8466 StmtResult ActOnOpenMPExecutableDirective(
8467 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8468 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8469 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8470 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8471 /// of the associated statement.
8472 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8474 SourceLocation StartLoc,
8475 SourceLocation EndLoc);
8476 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8477 /// of the associated statement.
8478 StmtResult ActOnOpenMPSimdDirective(
8479 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8480 SourceLocation EndLoc,
8481 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8482 /// \brief Called on well-formed '\#pragma omp for' after parsing
8483 /// of the associated statement.
8484 StmtResult ActOnOpenMPForDirective(
8485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8486 SourceLocation EndLoc,
8487 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8488 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8489 /// of the associated statement.
8490 StmtResult ActOnOpenMPForSimdDirective(
8491 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8492 SourceLocation EndLoc,
8493 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8494 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8495 /// of the associated statement.
8496 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8497 Stmt *AStmt, SourceLocation StartLoc,
8498 SourceLocation EndLoc);
8499 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8500 /// associated statement.
8501 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8502 SourceLocation EndLoc);
8503 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8504 /// associated statement.
8505 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8506 Stmt *AStmt, SourceLocation StartLoc,
8507 SourceLocation EndLoc);
8508 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8509 /// associated statement.
8510 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8511 SourceLocation EndLoc);
8512 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8513 /// associated statement.
8514 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8515 ArrayRef<OMPClause *> Clauses,
8516 Stmt *AStmt, SourceLocation StartLoc,
8517 SourceLocation EndLoc);
8518 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8519 /// of the associated statement.
8520 StmtResult ActOnOpenMPParallelForDirective(
8521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8522 SourceLocation EndLoc,
8523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8524 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8525 /// parsing of the associated statement.
8526 StmtResult ActOnOpenMPParallelForSimdDirective(
8527 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8528 SourceLocation EndLoc,
8529 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8530 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8531 /// parsing of the associated statement.
8532 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8534 SourceLocation StartLoc,
8535 SourceLocation EndLoc);
8536 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8537 /// associated statement.
8538 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8539 Stmt *AStmt, SourceLocation StartLoc,
8540 SourceLocation EndLoc);
8541 /// \brief Called on well-formed '\#pragma omp taskyield'.
8542 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8543 SourceLocation EndLoc);
8544 /// \brief Called on well-formed '\#pragma omp barrier'.
8545 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8546 SourceLocation EndLoc);
8547 /// \brief Called on well-formed '\#pragma omp taskwait'.
8548 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8549 SourceLocation EndLoc);
8550 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8551 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8552 SourceLocation EndLoc);
8553 /// \brief Called on well-formed '\#pragma omp flush'.
8554 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8555 SourceLocation StartLoc,
8556 SourceLocation EndLoc);
8557 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8558 /// associated statement.
8559 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8560 Stmt *AStmt, SourceLocation StartLoc,
8561 SourceLocation EndLoc);
8562 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8563 /// associated statement.
8564 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8565 Stmt *AStmt, SourceLocation StartLoc,
8566 SourceLocation EndLoc);
8567 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8568 /// associated statement.
8569 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8570 Stmt *AStmt, SourceLocation StartLoc,
8571 SourceLocation EndLoc);
8572 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8573 /// the associated statement.
8574 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8575 Stmt *AStmt, SourceLocation StartLoc,
8576 SourceLocation EndLoc);
8577 /// \brief Called on well-formed '\#pragma omp target enter data' after
8578 /// parsing of the associated statement.
8579 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8580 SourceLocation StartLoc,
8581 SourceLocation EndLoc);
8582 /// \brief Called on well-formed '\#pragma omp target exit data' after
8583 /// parsing of the associated statement.
8584 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8585 SourceLocation StartLoc,
8586 SourceLocation EndLoc);
8587 /// \brief Called on well-formed '\#pragma omp target parallel' after
8588 /// parsing of the associated statement.
8589 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8591 SourceLocation StartLoc,
8592 SourceLocation EndLoc);
8593 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8594 /// parsing of the associated statement.
8595 StmtResult ActOnOpenMPTargetParallelForDirective(
8596 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8597 SourceLocation EndLoc,
8598 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8599 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8600 /// associated statement.
8601 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8602 Stmt *AStmt, SourceLocation StartLoc,
8603 SourceLocation EndLoc);
8604 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8606 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8607 SourceLocation EndLoc,
8608 OpenMPDirectiveKind CancelRegion);
8609 /// \brief Called on well-formed '\#pragma omp cancel'.
8610 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8611 SourceLocation StartLoc,
8612 SourceLocation EndLoc,
8613 OpenMPDirectiveKind CancelRegion);
8614 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8615 /// associated statement.
8616 StmtResult ActOnOpenMPTaskLoopDirective(
8617 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8618 SourceLocation EndLoc,
8619 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8620 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8621 /// the associated statement.
8622 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8623 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8624 SourceLocation EndLoc,
8625 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8626 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8627 /// of the associated statement.
8628 StmtResult ActOnOpenMPDistributeDirective(
8629 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8630 SourceLocation EndLoc,
8631 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8632 /// \brief Called on well-formed '\#pragma omp target update'.
8633 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8634 SourceLocation StartLoc,
8635 SourceLocation EndLoc);
8636 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8637 /// parsing of the associated statement.
8638 StmtResult ActOnOpenMPDistributeParallelForDirective(
8639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8640 SourceLocation EndLoc,
8641 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8642 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8643 /// after parsing of the associated statement.
8644 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8645 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8646 SourceLocation EndLoc,
8647 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8648 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8649 /// parsing of the associated statement.
8650 StmtResult ActOnOpenMPDistributeSimdDirective(
8651 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8652 SourceLocation EndLoc,
8653 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8654 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8655 /// parsing of the associated statement.
8656 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8657 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8658 SourceLocation EndLoc,
8659 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8660 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8661 /// the associated statement.
8662 StmtResult ActOnOpenMPTargetSimdDirective(
8663 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8664 SourceLocation EndLoc,
8665 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8666 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8667 /// the associated statement.
8668 StmtResult ActOnOpenMPTeamsDistributeDirective(
8669 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8670 SourceLocation EndLoc,
8671 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8672 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8673 /// of the associated statement.
8674 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8675 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8676 SourceLocation EndLoc,
8677 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8678 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8679 /// after parsing of the associated statement.
8680 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8681 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8682 SourceLocation EndLoc,
8683 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8684 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8685 /// after parsing of the associated statement.
8686 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8687 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8688 SourceLocation EndLoc,
8689 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8690 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8691 /// associated statement.
8692 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8694 SourceLocation StartLoc,
8695 SourceLocation EndLoc);
8696 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8697 /// of the associated statement.
8698 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8699 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8700 SourceLocation EndLoc,
8701 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8702 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8703 /// after parsing of the associated statement.
8704 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8705 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8706 SourceLocation EndLoc,
8707 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8708 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8709 /// simd' after parsing of the associated statement.
8710 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8711 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8712 SourceLocation EndLoc,
8713 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8714 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8715 /// parsing of the associated statement.
8716 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8717 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8718 SourceLocation EndLoc,
8719 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8721 /// Checks correctness of linear modifiers.
8722 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8723 SourceLocation LinLoc);
8724 /// Checks that the specified declaration matches requirements for the linear
8726 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8727 OpenMPLinearClauseKind LinKind, QualType Type);
8729 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8730 /// the associated method/function.
8731 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8732 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8733 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8734 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8735 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8737 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8739 SourceLocation StartLoc,
8740 SourceLocation LParenLoc,
8741 SourceLocation EndLoc);
8742 /// \brief Called on well-formed 'if' clause.
8743 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8744 Expr *Condition, SourceLocation StartLoc,
8745 SourceLocation LParenLoc,
8746 SourceLocation NameModifierLoc,
8747 SourceLocation ColonLoc,
8748 SourceLocation EndLoc);
8749 /// \brief Called on well-formed 'final' clause.
8750 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8751 SourceLocation LParenLoc,
8752 SourceLocation EndLoc);
8753 /// \brief Called on well-formed 'num_threads' clause.
8754 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8755 SourceLocation StartLoc,
8756 SourceLocation LParenLoc,
8757 SourceLocation EndLoc);
8758 /// \brief Called on well-formed 'safelen' clause.
8759 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8760 SourceLocation StartLoc,
8761 SourceLocation LParenLoc,
8762 SourceLocation EndLoc);
8763 /// \brief Called on well-formed 'simdlen' clause.
8764 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8765 SourceLocation LParenLoc,
8766 SourceLocation EndLoc);
8767 /// \brief Called on well-formed 'collapse' clause.
8768 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8769 SourceLocation StartLoc,
8770 SourceLocation LParenLoc,
8771 SourceLocation EndLoc);
8772 /// \brief Called on well-formed 'ordered' clause.
8774 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8775 SourceLocation LParenLoc = SourceLocation(),
8776 Expr *NumForLoops = nullptr);
8777 /// \brief Called on well-formed 'grainsize' clause.
8778 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8779 SourceLocation LParenLoc,
8780 SourceLocation EndLoc);
8781 /// \brief Called on well-formed 'num_tasks' clause.
8782 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8783 SourceLocation LParenLoc,
8784 SourceLocation EndLoc);
8785 /// \brief Called on well-formed 'hint' clause.
8786 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8787 SourceLocation LParenLoc,
8788 SourceLocation EndLoc);
8790 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8792 SourceLocation ArgumentLoc,
8793 SourceLocation StartLoc,
8794 SourceLocation LParenLoc,
8795 SourceLocation EndLoc);
8796 /// \brief Called on well-formed 'default' clause.
8797 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8798 SourceLocation KindLoc,
8799 SourceLocation StartLoc,
8800 SourceLocation LParenLoc,
8801 SourceLocation EndLoc);
8802 /// \brief Called on well-formed 'proc_bind' clause.
8803 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8804 SourceLocation KindLoc,
8805 SourceLocation StartLoc,
8806 SourceLocation LParenLoc,
8807 SourceLocation EndLoc);
8809 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8810 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8811 SourceLocation StartLoc, SourceLocation LParenLoc,
8812 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8813 SourceLocation EndLoc);
8814 /// \brief Called on well-formed 'schedule' clause.
8815 OMPClause *ActOnOpenMPScheduleClause(
8816 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8817 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8818 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8819 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8821 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8822 SourceLocation EndLoc);
8823 /// \brief Called on well-formed 'nowait' clause.
8824 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8825 SourceLocation EndLoc);
8826 /// \brief Called on well-formed 'untied' clause.
8827 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8828 SourceLocation EndLoc);
8829 /// \brief Called on well-formed 'mergeable' clause.
8830 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8831 SourceLocation EndLoc);
8832 /// \brief Called on well-formed 'read' clause.
8833 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8834 SourceLocation EndLoc);
8835 /// \brief Called on well-formed 'write' clause.
8836 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8837 SourceLocation EndLoc);
8838 /// \brief Called on well-formed 'update' clause.
8839 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8840 SourceLocation EndLoc);
8841 /// \brief Called on well-formed 'capture' clause.
8842 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8843 SourceLocation EndLoc);
8844 /// \brief Called on well-formed 'seq_cst' clause.
8845 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8846 SourceLocation EndLoc);
8847 /// \brief Called on well-formed 'threads' clause.
8848 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8849 SourceLocation EndLoc);
8850 /// \brief Called on well-formed 'simd' clause.
8851 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8852 SourceLocation EndLoc);
8853 /// \brief Called on well-formed 'nogroup' clause.
8854 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8855 SourceLocation EndLoc);
8857 OMPClause *ActOnOpenMPVarListClause(
8858 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8859 SourceLocation StartLoc, SourceLocation LParenLoc,
8860 SourceLocation ColonLoc, SourceLocation EndLoc,
8861 CXXScopeSpec &ReductionIdScopeSpec,
8862 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8863 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8864 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8865 SourceLocation DepLinMapLoc);
8866 /// \brief Called on well-formed 'private' clause.
8867 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8868 SourceLocation StartLoc,
8869 SourceLocation LParenLoc,
8870 SourceLocation EndLoc);
8871 /// \brief Called on well-formed 'firstprivate' clause.
8872 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8873 SourceLocation StartLoc,
8874 SourceLocation LParenLoc,
8875 SourceLocation EndLoc);
8876 /// \brief Called on well-formed 'lastprivate' clause.
8877 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8878 SourceLocation StartLoc,
8879 SourceLocation LParenLoc,
8880 SourceLocation EndLoc);
8881 /// \brief Called on well-formed 'shared' clause.
8882 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8883 SourceLocation StartLoc,
8884 SourceLocation LParenLoc,
8885 SourceLocation EndLoc);
8886 /// \brief Called on well-formed 'reduction' clause.
8887 OMPClause *ActOnOpenMPReductionClause(
8888 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8889 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8890 CXXScopeSpec &ReductionIdScopeSpec,
8891 const DeclarationNameInfo &ReductionId,
8892 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8893 /// \brief Called on well-formed 'linear' clause.
8895 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8896 SourceLocation StartLoc, SourceLocation LParenLoc,
8897 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8898 SourceLocation ColonLoc, SourceLocation EndLoc);
8899 /// \brief Called on well-formed 'aligned' clause.
8900 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8902 SourceLocation StartLoc,
8903 SourceLocation LParenLoc,
8904 SourceLocation ColonLoc,
8905 SourceLocation EndLoc);
8906 /// \brief Called on well-formed 'copyin' clause.
8907 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8908 SourceLocation StartLoc,
8909 SourceLocation LParenLoc,
8910 SourceLocation EndLoc);
8911 /// \brief Called on well-formed 'copyprivate' clause.
8912 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8913 SourceLocation StartLoc,
8914 SourceLocation LParenLoc,
8915 SourceLocation EndLoc);
8916 /// \brief Called on well-formed 'flush' pseudo clause.
8917 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8918 SourceLocation StartLoc,
8919 SourceLocation LParenLoc,
8920 SourceLocation EndLoc);
8921 /// \brief Called on well-formed 'depend' clause.
8923 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8924 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8925 SourceLocation StartLoc, SourceLocation LParenLoc,
8926 SourceLocation EndLoc);
8927 /// \brief Called on well-formed 'device' clause.
8928 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8929 SourceLocation LParenLoc,
8930 SourceLocation EndLoc);
8931 /// \brief Called on well-formed 'map' clause.
8933 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8934 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8935 SourceLocation MapLoc, SourceLocation ColonLoc,
8936 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8937 SourceLocation LParenLoc, SourceLocation EndLoc);
8938 /// \brief Called on well-formed 'num_teams' clause.
8939 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8940 SourceLocation LParenLoc,
8941 SourceLocation EndLoc);
8942 /// \brief Called on well-formed 'thread_limit' clause.
8943 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8944 SourceLocation StartLoc,
8945 SourceLocation LParenLoc,
8946 SourceLocation EndLoc);
8947 /// \brief Called on well-formed 'priority' clause.
8948 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8949 SourceLocation LParenLoc,
8950 SourceLocation EndLoc);
8951 /// \brief Called on well-formed 'dist_schedule' clause.
8952 OMPClause *ActOnOpenMPDistScheduleClause(
8953 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8954 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8955 SourceLocation CommaLoc, SourceLocation EndLoc);
8956 /// \brief Called on well-formed 'defaultmap' clause.
8957 OMPClause *ActOnOpenMPDefaultmapClause(
8958 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8959 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8960 SourceLocation KindLoc, SourceLocation EndLoc);
8961 /// \brief Called on well-formed 'to' clause.
8962 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8963 SourceLocation StartLoc,
8964 SourceLocation LParenLoc,
8965 SourceLocation EndLoc);
8966 /// \brief Called on well-formed 'from' clause.
8967 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8968 SourceLocation StartLoc,
8969 SourceLocation LParenLoc,
8970 SourceLocation EndLoc);
8971 /// Called on well-formed 'use_device_ptr' clause.
8972 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8973 SourceLocation StartLoc,
8974 SourceLocation LParenLoc,
8975 SourceLocation EndLoc);
8976 /// Called on well-formed 'is_device_ptr' clause.
8977 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8978 SourceLocation StartLoc,
8979 SourceLocation LParenLoc,
8980 SourceLocation EndLoc);
8982 /// \brief The kind of conversion being performed.
8983 enum CheckedConversionKind {
8984 /// \brief An implicit conversion.
8985 CCK_ImplicitConversion,
8986 /// \brief A C-style cast.
8988 /// \brief A functional-style cast.
8990 /// \brief A cast other than a C-style cast.
8994 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8995 /// cast. If there is already an implicit cast, merge into the existing one.
8996 /// If isLvalue, the result of the cast is an lvalue.
8997 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8998 ExprValueKind VK = VK_RValue,
8999 const CXXCastPath *BasePath = nullptr,
9000 CheckedConversionKind CCK
9001 = CCK_ImplicitConversion);
9003 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9004 /// to the conversion from scalar type ScalarTy to the Boolean type.
9005 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9007 /// IgnoredValueConversions - Given that an expression's result is
9008 /// syntactically ignored, perform any conversions that are
9010 ExprResult IgnoredValueConversions(Expr *E);
9012 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9013 // functions and arrays to their respective pointers (C99 6.3.2.1).
9014 ExprResult UsualUnaryConversions(Expr *E);
9016 /// CallExprUnaryConversions - a special case of an unary conversion
9017 /// performed on a function designator of a call expression.
9018 ExprResult CallExprUnaryConversions(Expr *E);
9020 // DefaultFunctionArrayConversion - converts functions and arrays
9021 // to their respective pointers (C99 6.3.2.1).
9022 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9024 // DefaultFunctionArrayLvalueConversion - converts functions and
9025 // arrays to their respective pointers and performs the
9026 // lvalue-to-rvalue conversion.
9027 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9028 bool Diagnose = true);
9030 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9031 // the operand. This is DefaultFunctionArrayLvalueConversion,
9032 // except that it assumes the operand isn't of function or array
9034 ExprResult DefaultLvalueConversion(Expr *E);
9036 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9037 // do not have a prototype. Integer promotions are performed on each
9038 // argument, and arguments that have type float are promoted to double.
9039 ExprResult DefaultArgumentPromotion(Expr *E);
9041 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9042 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9043 /// we don't have xvalues there.
9044 ExprResult TemporaryMaterializationConversion(Expr *E);
9046 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9047 enum VariadicCallType {
9051 VariadicConstructor,
9052 VariadicDoesNotApply
9055 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9056 const FunctionProtoType *Proto,
9059 // Used for determining in which context a type is allowed to be passed to a
9069 // Determines which VarArgKind fits an expression.
9070 VarArgKind isValidVarArgType(const QualType &Ty);
9072 /// Check to see if the given expression is a valid argument to a variadic
9073 /// function, issuing a diagnostic if not.
9074 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9076 /// Check to see if a given expression could have '.c_str()' called on it.
9077 bool hasCStrMethod(const Expr *E);
9079 /// GatherArgumentsForCall - Collector argument expressions for various
9080 /// form of call prototypes.
9081 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9082 const FunctionProtoType *Proto,
9083 unsigned FirstParam, ArrayRef<Expr *> Args,
9084 SmallVectorImpl<Expr *> &AllArgs,
9085 VariadicCallType CallType = VariadicDoesNotApply,
9086 bool AllowExplicit = false,
9087 bool IsListInitialization = false);
9089 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9090 // will create a runtime trap if the resulting type is not a POD type.
9091 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9092 FunctionDecl *FDecl);
9094 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9095 // operands and then handles various conversions that are common to binary
9096 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9097 // routine returns the first non-arithmetic type found. The client is
9098 // responsible for emitting appropriate error diagnostics.
9099 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9100 bool IsCompAssign = false);
9102 /// AssignConvertType - All of the 'assignment' semantic checks return this
9103 /// enum to indicate whether the assignment was allowed. These checks are
9104 /// done for simple assignments, as well as initialization, return from
9105 /// function, argument passing, etc. The query is phrased in terms of a
9106 /// source and destination type.
9107 enum AssignConvertType {
9108 /// Compatible - the types are compatible according to the standard.
9111 /// PointerToInt - The assignment converts a pointer to an int, which we
9112 /// accept as an extension.
9115 /// IntToPointer - The assignment converts an int to a pointer, which we
9116 /// accept as an extension.
9119 /// FunctionVoidPointer - The assignment is between a function pointer and
9120 /// void*, which the standard doesn't allow, but we accept as an extension.
9121 FunctionVoidPointer,
9123 /// IncompatiblePointer - The assignment is between two pointers types that
9124 /// are not compatible, but we accept them as an extension.
9125 IncompatiblePointer,
9127 /// IncompatiblePointerSign - The assignment is between two pointers types
9128 /// which point to integers which have a different sign, but are otherwise
9129 /// identical. This is a subset of the above, but broken out because it's by
9130 /// far the most common case of incompatible pointers.
9131 IncompatiblePointerSign,
9133 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9134 /// c/v/r qualifiers, which we accept as an extension.
9135 CompatiblePointerDiscardsQualifiers,
9137 /// IncompatiblePointerDiscardsQualifiers - The assignment
9138 /// discards qualifiers that we don't permit to be discarded,
9139 /// like address spaces.
9140 IncompatiblePointerDiscardsQualifiers,
9142 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9143 /// nested pointer types, and the qualifiers other than the first two
9144 /// levels differ e.g. char ** -> const char **, but we accept them as an
9146 IncompatibleNestedPointerQualifiers,
9148 /// IncompatibleVectors - The assignment is between two vector types that
9149 /// have the same size, which we accept as an extension.
9150 IncompatibleVectors,
9152 /// IntToBlockPointer - The assignment converts an int to a block
9153 /// pointer. We disallow this.
9156 /// IncompatibleBlockPointer - The assignment is between two block
9157 /// pointers types that are not compatible.
9158 IncompatibleBlockPointer,
9160 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9161 /// id type and something else (that is incompatible with it). For example,
9162 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9163 IncompatibleObjCQualifiedId,
9165 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9166 /// object with __weak qualifier.
9167 IncompatibleObjCWeakRef,
9169 /// Incompatible - We reject this conversion outright, it is invalid to
9170 /// represent it in the AST.
9174 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9175 /// assignment conversion type specified by ConvTy. This returns true if the
9176 /// conversion was invalid or false if the conversion was accepted.
9177 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9179 QualType DstType, QualType SrcType,
9180 Expr *SrcExpr, AssignmentAction Action,
9181 bool *Complained = nullptr);
9183 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9184 /// enum. If AllowMask is true, then we also allow the complement of a valid
9185 /// value, to be used as a mask.
9186 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9187 bool AllowMask) const;
9189 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9190 /// integer not in the range of enum values.
9191 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9194 /// CheckAssignmentConstraints - Perform type checking for assignment,
9195 /// argument passing, variable initialization, and function return values.
9197 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9201 /// Check assignment constraints and optionally prepare for a conversion of
9202 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9204 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9207 bool ConvertRHS = true);
9209 /// Check assignment constraints for an assignment of RHS to LHSType.
9211 /// \param LHSType The destination type for the assignment.
9212 /// \param RHS The source expression for the assignment.
9213 /// \param Diagnose If \c true, diagnostics may be produced when checking
9214 /// for assignability. If a diagnostic is produced, \p RHS will be
9215 /// set to ExprError(). Note that this function may still return
9216 /// without producing a diagnostic, even for an invalid assignment.
9217 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9218 /// in an audited Core Foundation API and does not need to be checked
9219 /// for ARC retain issues.
9220 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9221 /// conversions necessary to perform the assignment. If \c false,
9222 /// \p Diagnose must also be \c false.
9223 AssignConvertType CheckSingleAssignmentConstraints(
9224 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9225 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9227 // \brief If the lhs type is a transparent union, check whether we
9228 // can initialize the transparent union with the given expression.
9229 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9232 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9234 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9236 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9237 AssignmentAction Action,
9238 bool AllowExplicit = false);
9239 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9240 AssignmentAction Action,
9242 ImplicitConversionSequence& ICS);
9243 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9244 const ImplicitConversionSequence& ICS,
9245 AssignmentAction Action,
9246 CheckedConversionKind CCK
9247 = CCK_ImplicitConversion);
9248 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9249 const StandardConversionSequence& SCS,
9250 AssignmentAction Action,
9251 CheckedConversionKind CCK);
9253 /// the following "Check" methods will return a valid/converted QualType
9254 /// or a null QualType (indicating an error diagnostic was issued).
9256 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9257 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9259 QualType CheckPointerToMemberOperands( // C++ 5.5
9260 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9261 SourceLocation OpLoc, bool isIndirect);
9262 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9263 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9265 QualType CheckRemainderOperands( // C99 6.5.5
9266 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9267 bool IsCompAssign = false);
9268 QualType CheckAdditionOperands( // C99 6.5.6
9269 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9270 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9271 QualType CheckSubtractionOperands( // C99 6.5.6
9272 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9273 QualType* CompLHSTy = nullptr);
9274 QualType CheckShiftOperands( // C99 6.5.7
9275 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9276 BinaryOperatorKind Opc, bool IsCompAssign = false);
9277 QualType CheckCompareOperands( // C99 6.5.8/9
9278 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9279 BinaryOperatorKind Opc, bool isRelational);
9280 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9281 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9282 BinaryOperatorKind Opc);
9283 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9284 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9285 BinaryOperatorKind Opc);
9286 // CheckAssignmentOperands is used for both simple and compound assignment.
9287 // For simple assignment, pass both expressions and a null converted type.
9288 // For compound assignment, pass both expressions and the converted type.
9289 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9290 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9292 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9293 UnaryOperatorKind Opcode, Expr *Op);
9294 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9295 BinaryOperatorKind Opcode,
9296 Expr *LHS, Expr *RHS);
9297 ExprResult checkPseudoObjectRValue(Expr *E);
9298 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9300 QualType CheckConditionalOperands( // C99 6.5.15
9301 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9302 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9303 QualType CXXCheckConditionalOperands( // C++ 5.16
9304 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9305 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9306 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9307 bool ConvertArgs = true);
9308 QualType FindCompositePointerType(SourceLocation Loc,
9309 ExprResult &E1, ExprResult &E2,
9310 bool ConvertArgs = true) {
9311 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9312 QualType Composite =
9313 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9319 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9320 SourceLocation QuestionLoc);
9322 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9323 SourceLocation QuestionLoc);
9325 void DiagnoseAlwaysNonNullPointer(Expr *E,
9326 Expr::NullPointerConstantKind NullType,
9327 bool IsEqual, SourceRange Range);
9329 /// type checking for vector binary operators.
9330 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9331 SourceLocation Loc, bool IsCompAssign,
9332 bool AllowBothBool, bool AllowBoolConversion);
9333 QualType GetSignedVectorType(QualType V);
9334 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9335 SourceLocation Loc, bool isRelational);
9336 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9337 SourceLocation Loc);
9339 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9340 bool isLaxVectorConversion(QualType srcType, QualType destType);
9342 /// type checking declaration initializers (C99 6.7.8)
9343 bool CheckForConstantInitializer(Expr *e, QualType t);
9345 // type checking C++ declaration initializers (C++ [dcl.init]).
9347 /// ReferenceCompareResult - Expresses the result of comparing two
9348 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9349 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9350 enum ReferenceCompareResult {
9351 /// Ref_Incompatible - The two types are incompatible, so direct
9352 /// reference binding is not possible.
9353 Ref_Incompatible = 0,
9354 /// Ref_Related - The two types are reference-related, which means
9355 /// that their unqualified forms (T1 and T2) are either the same
9356 /// or T1 is a base class of T2.
9358 /// Ref_Compatible - The two types are reference-compatible.
9362 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9363 QualType T1, QualType T2,
9364 bool &DerivedToBase,
9365 bool &ObjCConversion,
9366 bool &ObjCLifetimeConversion);
9368 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9369 Expr *CastExpr, CastKind &CastKind,
9370 ExprValueKind &VK, CXXCastPath &Path);
9372 /// \brief Force an expression with unknown-type to an expression of the
9374 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9376 /// \brief Type-check an expression that's being passed to an
9377 /// __unknown_anytype parameter.
9378 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9379 Expr *result, QualType ¶mType);
9381 // CheckVectorCast - check type constraints for vectors.
9382 // Since vectors are an extension, there are no C standard reference for this.
9383 // We allow casting between vectors and integer datatypes of the same size.
9384 // returns true if the cast is invalid
9385 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9388 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9389 /// implicit casts if necessary.
9390 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9392 // CheckExtVectorCast - check type constraints for extended vectors.
9393 // Since vectors are an extension, there are no C standard reference for this.
9394 // We allow casting between vectors and integer datatypes of the same size,
9395 // or vectors and the element type of that vector.
9396 // returns the cast expr
9397 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9400 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9401 SourceLocation LParenLoc,
9403 SourceLocation RParenLoc);
9405 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9407 /// \brief Checks for invalid conversions and casts between
9408 /// retainable pointers and other pointer kinds for ARC and Weak.
9409 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9410 QualType castType, Expr *&op,
9411 CheckedConversionKind CCK,
9412 bool Diagnose = true,
9413 bool DiagnoseCFAudited = false,
9414 BinaryOperatorKind Opc = BO_PtrMemD
9417 Expr *stripARCUnbridgedCast(Expr *e);
9418 void diagnoseARCUnbridgedCast(Expr *e);
9420 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9423 /// checkRetainCycles - Check whether an Objective-C message send
9424 /// might create an obvious retain cycle.
9425 void checkRetainCycles(ObjCMessageExpr *msg);
9426 void checkRetainCycles(Expr *receiver, Expr *argument);
9427 void checkRetainCycles(VarDecl *Var, Expr *Init);
9429 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9430 /// to weak/__unsafe_unretained type.
9431 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9433 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9434 /// to weak/__unsafe_unretained expression.
9435 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9437 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9438 /// \param Method - May be null.
9439 /// \param [out] ReturnType - The return type of the send.
9440 /// \return true iff there were any incompatible types.
9441 bool CheckMessageArgumentTypes(QualType ReceiverType,
9442 MultiExprArg Args, Selector Sel,
9443 ArrayRef<SourceLocation> SelectorLocs,
9444 ObjCMethodDecl *Method, bool isClassMessage,
9445 bool isSuperMessage,
9446 SourceLocation lbrac, SourceLocation rbrac,
9447 SourceRange RecRange,
9448 QualType &ReturnType, ExprValueKind &VK);
9450 /// \brief Determine the result of a message send expression based on
9451 /// the type of the receiver, the method expected to receive the message,
9452 /// and the form of the message send.
9453 QualType getMessageSendResultType(QualType ReceiverType,
9454 ObjCMethodDecl *Method,
9455 bool isClassMessage, bool isSuperMessage);
9457 /// \brief If the given expression involves a message send to a method
9458 /// with a related result type, emit a note describing what happened.
9459 void EmitRelatedResultTypeNote(const Expr *E);
9461 /// \brief Given that we had incompatible pointer types in a return
9462 /// statement, check whether we're in a method with a related result
9463 /// type, and if so, emit a note describing what happened.
9464 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9466 class ConditionResult {
9468 FullExprArg Condition;
9474 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9476 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9477 HasKnownValue(IsConstexpr && Condition.get() &&
9478 !Condition.get()->isValueDependent()),
9479 KnownValue(HasKnownValue &&
9480 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9481 explicit ConditionResult(bool Invalid)
9482 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9483 HasKnownValue(false), KnownValue(false) {}
9486 ConditionResult() : ConditionResult(false) {}
9487 bool isInvalid() const { return Invalid; }
9488 std::pair<VarDecl *, Expr *> get() const {
9489 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9492 llvm::Optional<bool> getKnownValue() const {
9498 static ConditionResult ConditionError() { return ConditionResult(true); }
9500 enum class ConditionKind {
9501 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9502 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9503 Switch ///< An integral condition for a 'switch' statement.
9506 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9507 Expr *SubExpr, ConditionKind CK);
9509 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9510 SourceLocation StmtLoc,
9513 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9515 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9516 SourceLocation StmtLoc,
9518 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9520 /// CheckBooleanCondition - Diagnose problems involving the use of
9521 /// the given expression as a boolean condition (e.g. in an if
9522 /// statement). Also performs the standard function and array
9523 /// decays, possibly changing the input variable.
9525 /// \param Loc - A location associated with the condition, e.g. the
9527 /// \return true iff there were any errors
9528 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9529 bool IsConstexpr = false);
9531 /// DiagnoseAssignmentAsCondition - Given that an expression is
9532 /// being used as a boolean condition, warn if it's an assignment.
9533 void DiagnoseAssignmentAsCondition(Expr *E);
9535 /// \brief Redundant parentheses over an equality comparison can indicate
9536 /// that the user intended an assignment used as condition.
9537 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9539 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9540 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9542 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9543 /// the specified width and sign. If an overflow occurs, detect it and emit
9544 /// the specified diagnostic.
9545 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9546 unsigned NewWidth, bool NewSign,
9547 SourceLocation Loc, unsigned DiagID);
9549 /// Checks that the Objective-C declaration is declared in the global scope.
9550 /// Emits an error and marks the declaration as invalid if it's not declared
9551 /// in the global scope.
9552 bool CheckObjCDeclScope(Decl *D);
9554 /// \brief Abstract base class used for diagnosing integer constant
9555 /// expression violations.
9556 class VerifyICEDiagnoser {
9560 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9562 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9563 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9564 virtual ~VerifyICEDiagnoser() { }
9567 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9568 /// and reports the appropriate diagnostics. Returns false on success.
9569 /// Can optionally return the value of the expression.
9570 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9571 VerifyICEDiagnoser &Diagnoser,
9572 bool AllowFold = true);
9573 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9575 bool AllowFold = true);
9576 ExprResult VerifyIntegerConstantExpression(Expr *E,
9577 llvm::APSInt *Result = nullptr);
9579 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9580 /// the correct width, and that the field type is valid.
9581 /// Returns false on success.
9582 /// Can optionally return whether the bit-field is of width 0
9583 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9584 QualType FieldTy, bool IsMsStruct,
9585 Expr *BitWidth, bool *ZeroWidth = nullptr);
9588 unsigned ForceCUDAHostDeviceDepth = 0;
9591 /// Increments our count of the number of times we've seen a pragma forcing
9592 /// functions to be __host__ __device__. So long as this count is greater
9593 /// than zero, all functions encountered will be __host__ __device__.
9594 void PushForceCUDAHostDevice();
9596 /// Decrements our count of the number of times we've seen a pragma forcing
9597 /// functions to be __host__ __device__. Returns false if the count is 0
9598 /// before incrementing, so you can emit an error.
9599 bool PopForceCUDAHostDevice();
9601 /// Diagnostics that are emitted only if we discover that the given function
9602 /// must be codegen'ed. Because handling these correctly adds overhead to
9603 /// compilation, this is currently only enabled for CUDA compilations.
9604 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9605 std::vector<PartialDiagnosticAt>>
9608 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9609 /// key in a hashtable, both the FD and location are hashed.
9610 struct FunctionDeclAndLoc {
9611 CanonicalDeclPtr<FunctionDecl> FD;
9615 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9616 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9617 /// same deferred diag twice.
9618 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9620 /// An inverse call graph, mapping known-emitted functions to one of their
9621 /// known-emitted callers (plus the location of the call).
9623 /// Functions that we can tell a priori must be emitted aren't added to this
9625 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9626 /* Caller = */ FunctionDeclAndLoc>
9627 CUDAKnownEmittedFns;
9629 /// A partial call graph maintained during CUDA compilation to support
9630 /// deferred diagnostics.
9632 /// Functions are only added here if, at the time they're considered, they are
9633 /// not known-emitted. As soon as we discover that a function is
9634 /// known-emitted, we remove it and everything it transitively calls from this
9635 /// set and add those functions to CUDAKnownEmittedFns.
9636 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9637 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9641 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9643 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9644 /// which are not allowed to appear inside __device__ functions and are
9645 /// allowed to appear in __host__ __device__ functions only if the host+device
9646 /// function is never codegen'ed.
9648 /// To handle this, we use the notion of "deferred diagnostics", where we
9649 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9651 /// This class lets you emit either a regular diagnostic, a deferred
9652 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9653 /// its constructor, thus simplifying the process of creating these "maybe
9654 /// deferred" diagnostics.
9655 class CUDADiagBuilder {
9658 /// Emit no diagnostics.
9660 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9662 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9663 /// emit a call stack showing how this function can be reached by an a
9664 /// priori known-emitted function.
9665 K_ImmediateWithCallStack,
9666 /// Create a deferred diagnostic, which is emitted only if the function
9667 /// it's attached to is codegen'ed. Also emit a call stack as with
9668 /// K_ImmediateWithCallStack.
9672 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9673 FunctionDecl *Fn, Sema &S);
9676 /// Convertible to bool: True if we immediately emitted an error, false if
9677 /// we didn't emit an error or we created a deferred error.
9681 /// if (CUDADiagBuilder(...) << foo << bar)
9682 /// return ExprError();
9684 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9685 /// want to use these instead of creating a CUDADiagBuilder yourself.
9686 operator bool() const { return ImmediateDiag.hasValue(); }
9688 template <typename T>
9689 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9691 if (Diag.ImmediateDiag.hasValue())
9692 *Diag.ImmediateDiag << Value;
9693 else if (Diag.PartialDiag.hasValue())
9694 *Diag.PartialDiag << Value;
9705 // Invariant: At most one of these Optionals has a value.
9706 // FIXME: Switch these to a Variant once that exists.
9707 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9708 llvm::Optional<PartialDiagnostic> PartialDiag;
9711 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9712 /// is "used as device code".
9714 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9715 /// - If CurContext is a __device__ or __global__ function, emits the
9716 /// diagnostics immediately.
9717 /// - If CurContext is a __host__ __device__ function and we are compiling for
9718 /// the device, creates a diagnostic which is emitted if and when we realize
9719 /// that the function will be codegen'ed.
9723 /// // Variable-length arrays are not allowed in CUDA device code.
9724 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9725 /// return ExprError();
9726 /// // Otherwise, continue parsing as normal.
9727 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9729 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9730 /// is "used as host code".
9732 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9733 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9735 enum CUDAFunctionTarget {
9743 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9746 /// Use this rather than examining the function's attributes yourself -- you
9747 /// will get it wrong. Returns CFT_Host if D is null.
9748 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9749 bool IgnoreImplicitHDAttr = false);
9750 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9752 /// Gets the CUDA target for the current context.
9753 CUDAFunctionTarget CurrentCUDATarget() {
9754 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9757 // CUDA function call preference. Must be ordered numerically from
9759 enum CUDAFunctionPreference {
9760 CFP_Never, // Invalid caller/callee combination.
9761 CFP_WrongSide, // Calls from host-device to host or device
9762 // function that do not match current compilation
9764 CFP_HostDevice, // Any calls to host/device functions.
9765 CFP_SameSide, // Calls from host-device to host or device
9766 // function matching current compilation mode.
9767 CFP_Native, // host-to-host or device-to-device calls.
9770 /// Identifies relative preference of a given Caller/Callee
9771 /// combination, based on their host/device attributes.
9772 /// \param Caller function which needs address of \p Callee.
9773 /// nullptr in case of global context.
9774 /// \param Callee target function
9776 /// \returns preference value for particular Caller/Callee combination.
9777 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9778 const FunctionDecl *Callee);
9780 /// Determines whether Caller may invoke Callee, based on their CUDA
9781 /// host/device attributes. Returns false if the call is not allowed.
9783 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9784 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9785 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9786 const FunctionDecl *Callee) {
9787 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9790 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9791 /// depending on FD and the current compilation settings.
9792 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9793 const LookupResult &Previous);
9796 /// Check whether we're allowed to call Callee from the current context.
9798 /// - If the call is never allowed in a semantically-correct program
9799 /// (CFP_Never), emits an error and returns false.
9801 /// - If the call is allowed in semantically-correct programs, but only if
9802 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9803 /// be emitted if and when the caller is codegen'ed, and returns true.
9805 /// Will only create deferred diagnostics for a given SourceLocation once,
9806 /// so you can safely call this multiple times without generating duplicate
9807 /// deferred errors.
9809 /// - Otherwise, returns true without emitting any diagnostics.
9810 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9812 /// Set __device__ or __host__ __device__ attributes on the given lambda
9813 /// operator() method.
9815 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9816 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9817 /// functions become __host__ __device__ themselves.
9818 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9820 /// Finds a function in \p Matches with highest calling priority
9821 /// from \p Caller context and erases all functions with lower
9822 /// calling priority.
9823 void EraseUnwantedCUDAMatches(
9824 const FunctionDecl *Caller,
9825 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9827 /// Given a implicit special member, infer its CUDA target from the
9828 /// calls it needs to make to underlying base/field special members.
9829 /// \param ClassDecl the class for which the member is being created.
9830 /// \param CSM the kind of special member.
9831 /// \param MemberDecl the special member itself.
9832 /// \param ConstRHS true if this is a copy operation with a const object on
9834 /// \param Diagnose true if this call should emit diagnostics.
9835 /// \return true if there was an error inferring.
9836 /// The result of this call is implicit CUDA target attribute(s) attached to
9837 /// the member declaration.
9838 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9839 CXXSpecialMember CSM,
9840 CXXMethodDecl *MemberDecl,
9844 /// \return true if \p CD can be considered empty according to CUDA
9845 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9846 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9847 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9849 /// Check whether NewFD is a valid overload for CUDA. Emits
9850 /// diagnostics and invalidates NewFD if not.
9851 void checkCUDATargetOverload(FunctionDecl *NewFD,
9852 const LookupResult &Previous);
9853 /// Copies target attributes from the template TD to the function FD.
9854 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9856 /// \name Code completion
9858 /// \brief Describes the context in which code completion occurs.
9859 enum ParserCompletionContext {
9860 /// \brief Code completion occurs at top-level or namespace context.
9862 /// \brief Code completion occurs within a class, struct, or union.
9864 /// \brief Code completion occurs within an Objective-C interface, protocol,
9867 /// \brief Code completion occurs within an Objective-C implementation or
9868 /// category implementation
9869 PCC_ObjCImplementation,
9870 /// \brief Code completion occurs within the list of instance variables
9871 /// in an Objective-C interface, protocol, category, or implementation.
9872 PCC_ObjCInstanceVariableList,
9873 /// \brief Code completion occurs following one or more template
9876 /// \brief Code completion occurs following one or more template
9877 /// headers within a class.
9879 /// \brief Code completion occurs within an expression.
9881 /// \brief Code completion occurs within a statement, which may
9882 /// also be an expression or a declaration.
9884 /// \brief Code completion occurs at the beginning of the
9885 /// initialization statement (or expression) in a for loop.
9887 /// \brief Code completion occurs within the condition of an if,
9888 /// while, switch, or for statement.
9890 /// \brief Code completion occurs within the body of a function on a
9891 /// recovery path, where we do not have a specific handle on our position
9893 PCC_RecoveryInFunction,
9894 /// \brief Code completion occurs where only a type is permitted.
9896 /// \brief Code completion occurs in a parenthesized expression, which
9897 /// might also be a type cast.
9898 PCC_ParenthesizedExpression,
9899 /// \brief Code completion occurs within a sequence of declaration
9900 /// specifiers within a function, method, or block.
9901 PCC_LocalDeclarationSpecifiers
9904 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9905 void CodeCompleteOrdinaryName(Scope *S,
9906 ParserCompletionContext CompletionContext);
9907 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9908 bool AllowNonIdentifiers,
9909 bool AllowNestedNameSpecifiers);
9911 struct CodeCompleteExpressionData;
9912 void CodeCompleteExpression(Scope *S,
9913 const CodeCompleteExpressionData &Data);
9914 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9915 SourceLocation OpLoc, bool IsArrow,
9916 bool IsBaseExprStatement);
9917 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9918 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9919 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9920 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9921 const VirtSpecifiers *VS = nullptr);
9922 void CodeCompleteBracketDeclarator(Scope *S);
9923 void CodeCompleteCase(Scope *S);
9924 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9925 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9926 ArrayRef<Expr *> Args);
9927 void CodeCompleteInitializer(Scope *S, Decl *D);
9928 void CodeCompleteReturn(Scope *S);
9929 void CodeCompleteAfterIf(Scope *S);
9930 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9932 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9933 bool EnteringContext);
9934 void CodeCompleteUsing(Scope *S);
9935 void CodeCompleteUsingDirective(Scope *S);
9936 void CodeCompleteNamespaceDecl(Scope *S);
9937 void CodeCompleteNamespaceAliasDecl(Scope *S);
9938 void CodeCompleteOperatorName(Scope *S);
9939 void CodeCompleteConstructorInitializer(
9941 ArrayRef<CXXCtorInitializer *> Initializers);
9943 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9944 bool AfterAmpersand);
9946 void CodeCompleteObjCAtDirective(Scope *S);
9947 void CodeCompleteObjCAtVisibility(Scope *S);
9948 void CodeCompleteObjCAtStatement(Scope *S);
9949 void CodeCompleteObjCAtExpression(Scope *S);
9950 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9951 void CodeCompleteObjCPropertyGetter(Scope *S);
9952 void CodeCompleteObjCPropertySetter(Scope *S);
9953 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9955 void CodeCompleteObjCMessageReceiver(Scope *S);
9956 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9957 ArrayRef<IdentifierInfo *> SelIdents,
9958 bool AtArgumentExpression);
9959 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9960 ArrayRef<IdentifierInfo *> SelIdents,
9961 bool AtArgumentExpression,
9962 bool IsSuper = false);
9963 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9964 ArrayRef<IdentifierInfo *> SelIdents,
9965 bool AtArgumentExpression,
9966 ObjCInterfaceDecl *Super = nullptr);
9967 void CodeCompleteObjCForCollection(Scope *S,
9968 DeclGroupPtrTy IterationVar);
9969 void CodeCompleteObjCSelector(Scope *S,
9970 ArrayRef<IdentifierInfo *> SelIdents);
9971 void CodeCompleteObjCProtocolReferences(
9972 ArrayRef<IdentifierLocPair> Protocols);
9973 void CodeCompleteObjCProtocolDecl(Scope *S);
9974 void CodeCompleteObjCInterfaceDecl(Scope *S);
9975 void CodeCompleteObjCSuperclass(Scope *S,
9976 IdentifierInfo *ClassName,
9977 SourceLocation ClassNameLoc);
9978 void CodeCompleteObjCImplementationDecl(Scope *S);
9979 void CodeCompleteObjCInterfaceCategory(Scope *S,
9980 IdentifierInfo *ClassName,
9981 SourceLocation ClassNameLoc);
9982 void CodeCompleteObjCImplementationCategory(Scope *S,
9983 IdentifierInfo *ClassName,
9984 SourceLocation ClassNameLoc);
9985 void CodeCompleteObjCPropertyDefinition(Scope *S);
9986 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9987 IdentifierInfo *PropertyName);
9988 void CodeCompleteObjCMethodDecl(Scope *S,
9989 bool IsInstanceMethod,
9990 ParsedType ReturnType);
9991 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9992 bool IsInstanceMethod,
9993 bool AtParameterName,
9994 ParsedType ReturnType,
9995 ArrayRef<IdentifierInfo *> SelIdents);
9996 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
9997 SourceLocation ClassNameLoc,
9998 bool IsBaseExprStatement);
9999 void CodeCompletePreprocessorDirective(bool InConditional);
10000 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10001 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10002 void CodeCompletePreprocessorExpression();
10003 void CodeCompletePreprocessorMacroArgument(Scope *S,
10004 IdentifierInfo *Macro,
10005 MacroInfo *MacroInfo,
10006 unsigned Argument);
10007 void CodeCompleteNaturalLanguage();
10008 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10009 CodeCompletionTUInfo &CCTUInfo,
10010 SmallVectorImpl<CodeCompletionResult> &Results);
10013 //===--------------------------------------------------------------------===//
10014 // Extra semantic analysis beyond the C type system
10017 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10018 unsigned ByteNo) const;
10021 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10022 const ArraySubscriptExpr *ASE=nullptr,
10023 bool AllowOnePastEnd=true, bool IndexNegated=false);
10024 void CheckArrayAccess(const Expr *E);
10025 // Used to grab the relevant information from a FormatAttr and a
10026 // FunctionDeclaration.
10027 struct FormatStringInfo {
10028 unsigned FormatIdx;
10029 unsigned FirstDataArg;
10033 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10034 FormatStringInfo *FSI);
10035 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10036 const FunctionProtoType *Proto);
10037 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10038 ArrayRef<const Expr *> Args);
10039 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10040 const FunctionProtoType *Proto);
10041 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10042 void CheckConstructorCall(FunctionDecl *FDecl,
10043 ArrayRef<const Expr *> Args,
10044 const FunctionProtoType *Proto,
10045 SourceLocation Loc);
10047 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10048 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10049 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10050 VariadicCallType CallType);
10052 bool CheckObjCString(Expr *Arg);
10053 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10055 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10056 unsigned BuiltinID, CallExpr *TheCall);
10058 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10059 unsigned MaxWidth);
10060 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10061 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10063 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10064 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10065 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10066 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10067 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10068 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10069 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10071 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10072 bool SemaBuiltinVAStartARM(CallExpr *Call);
10073 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10074 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10075 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10078 // Used by C++ template instantiation.
10079 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10080 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10081 SourceLocation BuiltinLoc,
10082 SourceLocation RParenLoc);
10085 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10086 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10087 bool SemaBuiltinAssume(CallExpr *TheCall);
10088 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10089 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10090 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10091 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10092 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10093 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10094 AtomicExpr::AtomicOp Op);
10095 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10096 llvm::APSInt &Result);
10097 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10098 int Low, int High);
10099 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10100 unsigned Multiple);
10101 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10102 int ArgNum, unsigned ExpectedFieldNum,
10105 enum FormatStringType {
10112 FST_FreeBSDKPrintf,
10117 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10119 bool FormatStringHasSArg(const StringLiteral *FExpr);
10121 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10124 bool CheckFormatArguments(const FormatAttr *Format,
10125 ArrayRef<const Expr *> Args,
10127 VariadicCallType CallType,
10128 SourceLocation Loc, SourceRange Range,
10129 llvm::SmallBitVector &CheckedVarArgs);
10130 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10131 bool HasVAListArg, unsigned format_idx,
10132 unsigned firstDataArg, FormatStringType Type,
10133 VariadicCallType CallType,
10134 SourceLocation Loc, SourceRange range,
10135 llvm::SmallBitVector &CheckedVarArgs);
10137 void CheckAbsoluteValueFunction(const CallExpr *Call,
10138 const FunctionDecl *FDecl);
10140 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10142 void CheckMemaccessArguments(const CallExpr *Call,
10144 IdentifierInfo *FnName);
10146 void CheckStrlcpycatArguments(const CallExpr *Call,
10147 IdentifierInfo *FnName);
10149 void CheckStrncatArguments(const CallExpr *Call,
10150 IdentifierInfo *FnName);
10152 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10153 SourceLocation ReturnLoc,
10154 bool isObjCMethod = false,
10155 const AttrVec *Attrs = nullptr,
10156 const FunctionDecl *FD = nullptr);
10158 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10159 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10160 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10161 void CheckUnsequencedOperations(Expr *E);
10163 /// \brief Perform semantic checks on a completed expression. This will either
10164 /// be a full-expression or a default argument expression.
10165 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10166 bool IsConstexpr = false);
10168 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10171 /// Check if there is a field shadowing.
10172 void CheckShadowInheritedFields(const SourceLocation &Loc,
10173 DeclarationName FieldName,
10174 const CXXRecordDecl *RD);
10176 /// \brief Check if the given expression contains 'break' or 'continue'
10177 /// statement that produces control flow different from GCC.
10178 void CheckBreakContinueBinding(Expr *E);
10180 /// \brief Check whether receiver is mutable ObjC container which
10181 /// attempts to add itself into the container
10182 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10184 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10185 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10186 bool DeleteWasArrayForm);
10188 /// \brief Register a magic integral constant to be used as a type tag.
10189 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10190 uint64_t MagicValue, QualType Type,
10191 bool LayoutCompatible, bool MustBeNull);
10193 struct TypeTagData {
10196 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10197 Type(Type), LayoutCompatible(LayoutCompatible),
10198 MustBeNull(MustBeNull)
10203 /// If true, \c Type should be compared with other expression's types for
10204 /// layout-compatibility.
10205 unsigned LayoutCompatible : 1;
10206 unsigned MustBeNull : 1;
10209 /// A pair of ArgumentKind identifier and magic value. This uniquely
10210 /// identifies the magic value.
10211 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10214 /// \brief A map from magic value to type information.
10215 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10216 TypeTagForDatatypeMagicValues;
10218 /// \brief Peform checks on a call of a function with argument_with_type_tag
10219 /// or pointer_with_type_tag attributes.
10220 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10221 const Expr * const *ExprArgs);
10223 /// \brief Check if we are taking the address of a packed field
10224 /// as this may be a problem if the pointer value is dereferenced.
10225 void CheckAddressOfPackedMember(Expr *rhs);
10227 /// \brief The parser's current scope.
10229 /// The parser maintains this state here.
10232 mutable IdentifierInfo *Ident_super;
10233 mutable IdentifierInfo *Ident___float128;
10235 /// Nullability type specifiers.
10236 IdentifierInfo *Ident__Nonnull = nullptr;
10237 IdentifierInfo *Ident__Nullable = nullptr;
10238 IdentifierInfo *Ident__Null_unspecified = nullptr;
10240 IdentifierInfo *Ident_NSError = nullptr;
10243 friend class Parser;
10244 friend class InitializationSequence;
10245 friend class ASTReader;
10246 friend class ASTDeclReader;
10247 friend class ASTWriter;
10250 /// Retrieve the keyword associated
10251 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10253 /// The struct behind the CFErrorRef pointer.
10254 RecordDecl *CFError = nullptr;
10256 /// Retrieve the identifier "NSError".
10257 IdentifierInfo *getNSErrorIdent();
10259 /// \brief Retrieve the parser's current scope.
10261 /// This routine must only be used when it is certain that semantic analysis
10262 /// and the parser are in precisely the same context, which is not the case
10263 /// when, e.g., we are performing any kind of template instantiation.
10264 /// Therefore, the only safe places to use this scope are in the parser
10265 /// itself and in routines directly invoked from the parser and *never* from
10266 /// template substitution or instantiation.
10267 Scope *getCurScope() const { return CurScope; }
10269 void incrementMSManglingNumber() const {
10270 return CurScope->incrementMSManglingNumber();
10273 IdentifierInfo *getSuperIdentifier() const;
10274 IdentifierInfo *getFloat128Identifier() const;
10276 Decl *getObjCDeclContext() const;
10278 DeclContext *getCurLexicalContext() const {
10279 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10282 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10284 /// \param D The declaration to check. Note that this may be altered to point
10285 /// to another declaration that \c D gets it's availability from. i.e., we
10286 /// walk the list of typedefs to find an availability attribute.
10288 /// \param Message If non-null, this will be populated with the message from
10289 /// the availability attribute that is selected.
10290 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10291 std::string *Message);
10293 const DeclContext *getCurObjCLexicalContext() const {
10294 const DeclContext *DC = getCurLexicalContext();
10295 // A category implicitly has the attribute of the interface.
10296 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10297 DC = CatD->getClassInterface();
10301 /// \brief To be used for checking whether the arguments being passed to
10302 /// function exceeds the number of parameters expected for it.
10303 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10304 bool PartialOverloading = false) {
10305 // We check whether we're just after a comma in code-completion.
10306 if (NumArgs > 0 && PartialOverloading)
10307 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10308 return NumArgs > NumParams;
10311 // Emitting members of dllexported classes is delayed until the class
10312 // (including field initializers) is fully parsed.
10313 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10316 /// \brief Helper class that collects misaligned member designations and
10317 /// their location info for delayed diagnostics.
10318 struct MisalignedMember {
10322 CharUnits Alignment;
10324 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10325 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10326 CharUnits Alignment)
10327 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10328 explicit MisalignedMember(Expr *E)
10329 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10331 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10333 /// \brief Small set of gathered accesses to potentially misaligned members
10334 /// due to the packed attribute.
10335 SmallVector<MisalignedMember, 4> MisalignedMembers;
10337 /// \brief Adds an expression to the set of gathered misaligned members.
10338 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10339 CharUnits Alignment);
10342 /// \brief Diagnoses the current set of gathered accesses. This typically
10343 /// happens at full expression level. The set is cleared after emitting the
10345 void DiagnoseMisalignedMembers();
10347 /// \brief This function checks if the expression is in the sef of potentially
10348 /// misaligned members and it is converted to some pointer type T with lower
10349 /// or equal alignment requirements. If so it removes it. This is used when
10350 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10352 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10354 /// \brief This function calls Action when it determines that E designates a
10355 /// misaligned member due to the packed attribute. This is used to emit
10356 /// local diagnostics like in reference binding.
10357 void RefersToMemberWithReducedAlignment(
10359 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10363 /// \brief RAII object that enters a new expression evaluation context.
10364 class EnterExpressionEvaluationContext {
10366 bool Entered = true;
10370 EnterExpressionEvaluationContext(Sema &Actions,
10371 Sema::ExpressionEvaluationContext NewContext,
10372 Decl *LambdaContextDecl = nullptr,
10373 bool IsDecltype = false,
10374 bool ShouldEnter = true)
10375 : Actions(Actions), Entered(ShouldEnter) {
10377 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10380 EnterExpressionEvaluationContext(Sema &Actions,
10381 Sema::ExpressionEvaluationContext NewContext,
10382 Sema::ReuseLambdaContextDecl_t,
10383 bool IsDecltype = false)
10384 : Actions(Actions) {
10385 Actions.PushExpressionEvaluationContext(NewContext,
10386 Sema::ReuseLambdaContextDecl,
10390 enum InitListTag { InitList };
10391 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10392 bool ShouldEnter = true)
10393 : Actions(Actions), Entered(false) {
10394 // In C++11 onwards, narrowing checks are performed on the contents of
10395 // braced-init-lists, even when they occur within unevaluated operands.
10396 // Therefore we still need to instantiate constexpr functions used in such
10398 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10399 Actions.getLangOpts().CPlusPlus11) {
10400 Actions.PushExpressionEvaluationContext(
10401 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10406 ~EnterExpressionEvaluationContext() {
10408 Actions.PopExpressionEvaluationContext();
10412 DeductionFailureInfo
10413 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10414 sema::TemplateDeductionInfo &Info);
10416 /// \brief Contains a late templated function.
10417 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10418 struct LateParsedTemplate {
10420 /// \brief The template function declaration to be late parsed.
10424 } // end namespace clang
10427 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10429 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10430 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10431 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10433 static FunctionDeclAndLoc getEmptyKey() {
10434 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10437 static FunctionDeclAndLoc getTombstoneKey() {
10438 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10441 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10442 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10443 FDL.Loc.getRawEncoding());
10446 static bool isEqual(const FunctionDeclAndLoc &LHS,
10447 const FunctionDeclAndLoc &RHS) {
10448 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10451 } // namespace llvm