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 /// Stack of types that correspond to the parameter entities that are
1078 /// currently being copy-initialized. Can be empty.
1079 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1081 void ReadMethodPool(Selector Sel);
1082 void updateOutOfDateSelector(Selector Sel);
1084 /// Private Helper predicate to check for 'self'.
1085 bool isSelfExpr(Expr *RExpr);
1086 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1088 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1089 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1090 /// should not be used elsewhere.
1091 void EmitCurrentDiagnostic(unsigned DiagID);
1093 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1095 class FPContractStateRAII {
1097 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1098 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1102 FPOptions OldFPFeaturesState;
1105 void addImplicitTypedef(StringRef Name, QualType T);
1108 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1109 TranslationUnitKind TUKind = TU_Complete,
1110 CodeCompleteConsumer *CompletionConsumer = nullptr);
1113 /// \brief Perform initialization that occurs after the parser has been
1114 /// initialized but before it parses anything.
1117 const LangOptions &getLangOpts() const { return LangOpts; }
1118 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1119 FPOptions &getFPOptions() { return FPFeatures; }
1121 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1122 SourceManager &getSourceManager() const { return SourceMgr; }
1123 Preprocessor &getPreprocessor() const { return PP; }
1124 ASTContext &getASTContext() const { return Context; }
1125 ASTConsumer &getASTConsumer() const { return Consumer; }
1126 ASTMutationListener *getASTMutationListener() const;
1127 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1129 ///\brief Registers an external source. If an external source already exists,
1130 /// creates a multiplex external source and appends to it.
1132 ///\param[in] E - A non-null external sema source.
1134 void addExternalSource(ExternalSemaSource *E);
1136 void PrintStats() const;
1138 /// \brief Helper class that creates diagnostics with optional
1139 /// template instantiation stacks.
1141 /// This class provides a wrapper around the basic DiagnosticBuilder
1142 /// class that emits diagnostics. SemaDiagnosticBuilder is
1143 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1144 /// does) and, if the diagnostic comes from inside a template
1145 /// instantiation, printing the template instantiation stack as
1147 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1152 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1153 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1155 // This is a cunning lie. DiagnosticBuilder actually performs move
1156 // construction in its copy constructor (but due to varied uses, it's not
1157 // possible to conveniently express this as actual move construction). So
1158 // the default copy ctor here is fine, because the base class disables the
1159 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1160 // in that case anwyay.
1161 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1163 ~SemaDiagnosticBuilder() {
1164 // If we aren't active, there is nothing to do.
1165 if (!isActive()) return;
1167 // Otherwise, we need to emit the diagnostic. First flush the underlying
1168 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1169 // won't emit the diagnostic in its own destructor.
1171 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1172 // do its own needless checks to see if the diagnostic needs to be
1173 // emitted. However, because we take care to ensure that the builder
1174 // objects never escape, a sufficiently smart compiler will be able to
1175 // eliminate that code.
1179 // Dispatch to Sema to emit the diagnostic.
1180 SemaRef.EmitCurrentDiagnostic(DiagID);
1183 /// Teach operator<< to produce an object of the correct type.
1184 template<typename T>
1185 friend const SemaDiagnosticBuilder &operator<<(
1186 const SemaDiagnosticBuilder &Diag, const T &Value) {
1187 const DiagnosticBuilder &BaseDiag = Diag;
1193 /// \brief Emit a diagnostic.
1194 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1195 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1196 return SemaDiagnosticBuilder(DB, *this, DiagID);
1199 /// \brief Emit a partial diagnostic.
1200 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1202 /// \brief Build a partial diagnostic.
1203 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1205 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1207 /// \brief Get a string to suggest for zero-initialization of a type.
1209 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1210 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1212 /// \brief Calls \c Lexer::getLocForEndOfToken()
1213 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1215 /// \brief Retrieve the module loader associated with the preprocessor.
1216 ModuleLoader &getModuleLoader() const;
1218 void emitAndClearUnusedLocalTypedefWarnings();
1220 void ActOnEndOfTranslationUnit();
1222 void CheckDelegatingCtorCycles();
1224 Scope *getScopeForContext(DeclContext *Ctx);
1226 void PushFunctionScope();
1227 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1228 sema::LambdaScopeInfo *PushLambdaScope();
1230 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1231 /// is during Parsing. Currently it is used to pass on the depth
1232 /// when parsing generic lambda 'auto' parameters.
1233 void RecordParsingTemplateParameterDepth(unsigned Depth);
1235 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1237 CapturedRegionKind K);
1239 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1240 const Decl *D = nullptr,
1241 const BlockExpr *blkExpr = nullptr);
1243 sema::FunctionScopeInfo *getCurFunction() const {
1244 return FunctionScopes.back();
1247 sema::FunctionScopeInfo *getEnclosingFunction() const {
1248 if (FunctionScopes.empty())
1251 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1252 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1254 return FunctionScopes[e];
1259 template <typename ExprT>
1260 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1261 if (!isUnevaluatedContext())
1262 getCurFunction()->recordUseOfWeak(E, IsRead);
1265 void PushCompoundScope();
1266 void PopCompoundScope();
1268 sema::CompoundScopeInfo &getCurCompoundScope() const;
1270 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1272 /// \brief Retrieve the current block, if any.
1273 sema::BlockScopeInfo *getCurBlock();
1275 /// Retrieve the current lambda scope info, if any.
1276 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1277 /// lambda scope info ignoring all inner capturing scopes that are not
1279 sema::LambdaScopeInfo *
1280 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1282 /// \brief Retrieve the current generic lambda info, if any.
1283 sema::LambdaScopeInfo *getCurGenericLambda();
1285 /// \brief Retrieve the current captured region, if any.
1286 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1288 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1289 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1291 void ActOnComment(SourceRange Comment);
1293 //===--------------------------------------------------------------------===//
1294 // Type Analysis / Processing: SemaType.cpp.
1297 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1298 const DeclSpec *DS = nullptr);
1299 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1300 const DeclSpec *DS = nullptr);
1301 QualType BuildPointerType(QualType T,
1302 SourceLocation Loc, DeclarationName Entity);
1303 QualType BuildReferenceType(QualType T, bool LValueRef,
1304 SourceLocation Loc, DeclarationName Entity);
1305 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1306 Expr *ArraySize, unsigned Quals,
1307 SourceRange Brackets, DeclarationName Entity);
1308 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1309 SourceLocation AttrLoc);
1311 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1313 /// \brief Build a function type.
1315 /// This routine checks the function type according to C++ rules and
1316 /// under the assumption that the result type and parameter types have
1317 /// just been instantiated from a template. It therefore duplicates
1318 /// some of the behavior of GetTypeForDeclarator, but in a much
1319 /// simpler form that is only suitable for this narrow use case.
1321 /// \param T The return type of the function.
1323 /// \param ParamTypes The parameter types of the function. This array
1324 /// will be modified to account for adjustments to the types of the
1325 /// function parameters.
1327 /// \param Loc The location of the entity whose type involves this
1328 /// function type or, if there is no such entity, the location of the
1329 /// type that will have function type.
1331 /// \param Entity The name of the entity that involves the function
1334 /// \param EPI Extra information about the function type. Usually this will
1335 /// be taken from an existing function with the same prototype.
1337 /// \returns A suitable function type, if there are no errors. The
1338 /// unqualified type will always be a FunctionProtoType.
1339 /// Otherwise, returns a NULL type.
1340 QualType BuildFunctionType(QualType T,
1341 MutableArrayRef<QualType> ParamTypes,
1342 SourceLocation Loc, DeclarationName Entity,
1343 const FunctionProtoType::ExtProtoInfo &EPI);
1345 QualType BuildMemberPointerType(QualType T, QualType Class,
1347 DeclarationName Entity);
1348 QualType BuildBlockPointerType(QualType T,
1349 SourceLocation Loc, DeclarationName Entity);
1350 QualType BuildParenType(QualType T);
1351 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1352 QualType BuildReadPipeType(QualType T,
1353 SourceLocation Loc);
1354 QualType BuildWritePipeType(QualType T,
1355 SourceLocation Loc);
1357 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1358 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1359 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1360 TypeSourceInfo *ReturnTypeInfo);
1362 /// \brief Package the given type and TSI into a ParsedType.
1363 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1364 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1365 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1366 static QualType GetTypeFromParser(ParsedType Ty,
1367 TypeSourceInfo **TInfo = nullptr);
1368 CanThrowResult canThrow(const Expr *E);
1369 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1370 const FunctionProtoType *FPT);
1371 void UpdateExceptionSpec(FunctionDecl *FD,
1372 const FunctionProtoType::ExceptionSpecInfo &ESI);
1373 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1374 bool CheckDistantExceptionSpec(QualType T);
1375 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1376 bool CheckEquivalentExceptionSpec(
1377 const FunctionProtoType *Old, SourceLocation OldLoc,
1378 const FunctionProtoType *New, SourceLocation NewLoc);
1379 bool CheckEquivalentExceptionSpec(
1380 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1381 const FunctionProtoType *Old, SourceLocation OldLoc,
1382 const FunctionProtoType *New, SourceLocation NewLoc);
1383 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1384 const PartialDiagnostic &NestedDiagID,
1385 const PartialDiagnostic &NoteID,
1386 const FunctionProtoType *Superset,
1387 SourceLocation SuperLoc,
1388 const FunctionProtoType *Subset,
1389 SourceLocation SubLoc);
1390 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1391 const PartialDiagnostic &NoteID,
1392 const FunctionProtoType *Target,
1393 SourceLocation TargetLoc,
1394 const FunctionProtoType *Source,
1395 SourceLocation SourceLoc);
1397 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1399 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1400 /// in an Objective-C message declaration. Return the appropriate type.
1401 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1403 /// \brief Abstract class used to diagnose incomplete types.
1404 struct TypeDiagnoser {
1407 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1408 virtual ~TypeDiagnoser() {}
1411 static int getPrintable(int I) { return I; }
1412 static unsigned getPrintable(unsigned I) { return I; }
1413 static bool getPrintable(bool B) { return B; }
1414 static const char * getPrintable(const char *S) { return S; }
1415 static StringRef getPrintable(StringRef S) { return S; }
1416 static const std::string &getPrintable(const std::string &S) { return S; }
1417 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1420 static DeclarationName getPrintable(DeclarationName N) { return N; }
1421 static QualType getPrintable(QualType T) { return T; }
1422 static SourceRange getPrintable(SourceRange R) { return R; }
1423 static SourceRange getPrintable(SourceLocation L) { return L; }
1424 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1425 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1427 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1429 std::tuple<const Ts &...> Args;
1431 template <std::size_t... Is>
1432 void emit(const SemaDiagnosticBuilder &DB,
1433 llvm::index_sequence<Is...>) const {
1434 // Apply all tuple elements to the builder in order.
1435 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1440 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1441 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1442 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1445 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1446 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1447 emit(DB, llvm::index_sequence_for<Ts...>());
1453 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1454 TypeDiagnoser *Diagnoser);
1456 struct ModuleScope {
1457 clang::Module *Module;
1458 VisibleModuleSet OuterVisibleModules;
1460 /// The modules we're currently parsing.
1461 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1463 /// Get the module whose scope we are currently within.
1464 Module *getCurrentModule() const {
1465 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1468 VisibleModuleSet VisibleModules;
1471 /// \brief Get the module owning an entity.
1472 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1474 /// \brief Make a merged definition of an existing hidden definition \p ND
1475 /// visible at the specified location.
1476 void makeMergedDefinitionVisible(NamedDecl *ND);
1478 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1480 /// Determine whether a declaration is visible to name lookup.
1481 bool isVisible(const NamedDecl *D) {
1482 return !D->isHidden() || isVisibleSlow(D);
1485 /// Determine whether any declaration of an entity is visible.
1487 hasVisibleDeclaration(const NamedDecl *D,
1488 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1489 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1491 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1492 llvm::SmallVectorImpl<Module *> *Modules);
1494 bool hasVisibleMergedDefinition(NamedDecl *Def);
1496 /// Determine if \p D has a visible definition. If not, suggest a declaration
1497 /// that should be made visible to expose the definition.
1498 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1499 bool OnlyNeedComplete = false);
1500 bool hasVisibleDefinition(const NamedDecl *D) {
1502 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1505 /// Determine if the template parameter \p D has a visible default argument.
1507 hasVisibleDefaultArgument(const NamedDecl *D,
1508 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1510 /// Determine if there is a visible declaration of \p D that is a member
1511 /// specialization declaration (as opposed to an instantiated declaration).
1512 bool hasVisibleMemberSpecialization(
1513 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1515 /// Determine if \p A and \p B are equivalent internal linkage declarations
1516 /// from different modules, and thus an ambiguity error can be downgraded to
1517 /// an extension warning.
1518 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1519 const NamedDecl *B);
1520 void diagnoseEquivalentInternalLinkageDeclarations(
1521 SourceLocation Loc, const NamedDecl *D,
1522 ArrayRef<const NamedDecl *> Equiv);
1524 bool isCompleteType(SourceLocation Loc, QualType T) {
1525 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1527 bool RequireCompleteType(SourceLocation Loc, QualType T,
1528 TypeDiagnoser &Diagnoser);
1529 bool RequireCompleteType(SourceLocation Loc, QualType T,
1532 template <typename... Ts>
1533 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1534 const Ts &...Args) {
1535 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1536 return RequireCompleteType(Loc, T, Diagnoser);
1539 void completeExprArrayBound(Expr *E);
1540 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1541 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1543 template <typename... Ts>
1544 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1545 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1546 return RequireCompleteExprType(E, Diagnoser);
1549 bool RequireLiteralType(SourceLocation Loc, QualType T,
1550 TypeDiagnoser &Diagnoser);
1551 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1553 template <typename... Ts>
1554 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1555 const Ts &...Args) {
1556 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1557 return RequireLiteralType(Loc, T, Diagnoser);
1560 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1561 const CXXScopeSpec &SS, QualType T);
1563 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1564 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1565 /// context, such as when building a type for decltype(auto).
1566 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1567 bool AsUnevaluated = true);
1568 QualType BuildUnaryTransformType(QualType BaseType,
1569 UnaryTransformType::UTTKind UKind,
1570 SourceLocation Loc);
1572 //===--------------------------------------------------------------------===//
1573 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1576 struct SkipBodyInfo {
1577 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1579 NamedDecl *Previous;
1582 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1584 void DiagnoseUseOfUnimplementedSelectors();
1586 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1588 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1589 Scope *S, CXXScopeSpec *SS = nullptr,
1590 bool isClassName = false, bool HasTrailingDot = false,
1591 ParsedType ObjectType = nullptr,
1592 bool IsCtorOrDtorName = false,
1593 bool WantNontrivialTypeSourceInfo = false,
1594 bool IsClassTemplateDeductionContext = true,
1595 IdentifierInfo **CorrectedII = nullptr);
1596 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1597 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1598 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1599 SourceLocation IILoc,
1602 ParsedType &SuggestedType,
1603 bool IsTemplateName = false);
1605 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1606 /// type name has failed in a dependent context. In these situations, we
1607 /// automatically form a DependentTypeName that will retry lookup in a related
1608 /// scope during instantiation.
1609 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1610 SourceLocation NameLoc,
1611 bool IsTemplateTypeArg);
1613 /// \brief Describes the result of the name lookup and resolution performed
1614 /// by \c ClassifyName().
1615 enum NameClassificationKind {
1621 NC_NestedNameSpecifier,
1627 class NameClassification {
1628 NameClassificationKind Kind;
1630 TemplateName Template;
1632 const IdentifierInfo *Keyword;
1634 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1637 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1639 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1641 NameClassification(const IdentifierInfo *Keyword)
1642 : Kind(NC_Keyword), Keyword(Keyword) { }
1644 static NameClassification Error() {
1645 return NameClassification(NC_Error);
1648 static NameClassification Unknown() {
1649 return NameClassification(NC_Unknown);
1652 static NameClassification NestedNameSpecifier() {
1653 return NameClassification(NC_NestedNameSpecifier);
1656 static NameClassification TypeTemplate(TemplateName Name) {
1657 NameClassification Result(NC_TypeTemplate);
1658 Result.Template = Name;
1662 static NameClassification VarTemplate(TemplateName Name) {
1663 NameClassification Result(NC_VarTemplate);
1664 Result.Template = Name;
1668 static NameClassification FunctionTemplate(TemplateName Name) {
1669 NameClassification Result(NC_FunctionTemplate);
1670 Result.Template = Name;
1674 NameClassificationKind getKind() const { return Kind; }
1676 ParsedType getType() const {
1677 assert(Kind == NC_Type);
1681 ExprResult getExpression() const {
1682 assert(Kind == NC_Expression);
1686 TemplateName getTemplateName() const {
1687 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1688 Kind == NC_VarTemplate);
1692 TemplateNameKind getTemplateNameKind() const {
1694 case NC_TypeTemplate:
1695 return TNK_Type_template;
1696 case NC_FunctionTemplate:
1697 return TNK_Function_template;
1698 case NC_VarTemplate:
1699 return TNK_Var_template;
1701 llvm_unreachable("unsupported name classification.");
1706 /// \brief Perform name lookup on the given name, classifying it based on
1707 /// the results of name lookup and the following token.
1709 /// This routine is used by the parser to resolve identifiers and help direct
1710 /// parsing. When the identifier cannot be found, this routine will attempt
1711 /// to correct the typo and classify based on the resulting name.
1713 /// \param S The scope in which we're performing name lookup.
1715 /// \param SS The nested-name-specifier that precedes the name.
1717 /// \param Name The identifier. If typo correction finds an alternative name,
1718 /// this pointer parameter will be updated accordingly.
1720 /// \param NameLoc The location of the identifier.
1722 /// \param NextToken The token following the identifier. Used to help
1723 /// disambiguate the name.
1725 /// \param IsAddressOfOperand True if this name is the operand of a unary
1726 /// address of ('&') expression, assuming it is classified as an
1729 /// \param CCC The correction callback, if typo correction is desired.
1731 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1732 SourceLocation NameLoc, const Token &NextToken,
1733 bool IsAddressOfOperand,
1734 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1736 /// Describes the detailed kind of a template name. Used in diagnostics.
1737 enum class TemplateNameKindForDiagnostics {
1742 TemplateTemplateParam,
1745 TemplateNameKindForDiagnostics
1746 getTemplateNameKindForDiagnostics(TemplateName Name);
1748 /// Determine whether it's plausible that E was intended to be a
1750 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1751 if (!getLangOpts().CPlusPlus || E.isInvalid())
1753 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1754 return !DRE->hasExplicitTemplateArgs();
1755 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1756 return !ME->hasExplicitTemplateArgs();
1757 // Any additional cases recognized here should also be handled by
1758 // diagnoseExprIntendedAsTemplateName.
1761 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1762 SourceLocation Less,
1763 SourceLocation Greater);
1765 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1767 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1768 MultiTemplateParamsArg TemplateParameterLists);
1769 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1770 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1771 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1772 DeclarationName Name,
1773 SourceLocation Loc);
1775 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1776 SourceLocation FallbackLoc,
1777 SourceLocation ConstQualLoc = SourceLocation(),
1778 SourceLocation VolatileQualLoc = SourceLocation(),
1779 SourceLocation RestrictQualLoc = SourceLocation(),
1780 SourceLocation AtomicQualLoc = SourceLocation(),
1781 SourceLocation UnalignedQualLoc = SourceLocation());
1783 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1784 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1785 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1786 const LookupResult &R);
1787 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1788 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1789 const LookupResult &R);
1790 void CheckShadow(Scope *S, VarDecl *D);
1792 /// Warn if 'E', which is an expression that is about to be modified, refers
1793 /// to a shadowing declaration.
1794 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1796 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1799 /// Map of current shadowing declarations to shadowed declarations. Warn if
1800 /// it looks like the user is trying to modify the shadowing declaration.
1801 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1804 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1805 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1806 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1807 TypedefNameDecl *NewTD);
1808 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1809 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1810 TypeSourceInfo *TInfo,
1811 LookupResult &Previous);
1812 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1813 LookupResult &Previous, bool &Redeclaration);
1814 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1815 TypeSourceInfo *TInfo,
1816 LookupResult &Previous,
1817 MultiTemplateParamsArg TemplateParamLists,
1819 ArrayRef<BindingDecl *> Bindings = None);
1821 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1822 MultiTemplateParamsArg TemplateParamLists);
1823 // Returns true if the variable declaration is a redeclaration
1824 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1825 void CheckVariableDeclarationType(VarDecl *NewVD);
1826 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1828 void CheckCompleteVariableDeclaration(VarDecl *VD);
1829 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1830 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1832 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1833 TypeSourceInfo *TInfo,
1834 LookupResult &Previous,
1835 MultiTemplateParamsArg TemplateParamLists,
1837 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1839 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1840 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1842 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1843 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1844 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1845 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1846 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1847 // Returns true if the function declaration is a redeclaration
1848 bool CheckFunctionDeclaration(Scope *S,
1849 FunctionDecl *NewFD, LookupResult &Previous,
1850 bool IsMemberSpecialization);
1851 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1852 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1853 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1854 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1855 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1858 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1859 SourceLocation NameLoc, IdentifierInfo *Name,
1860 QualType T, TypeSourceInfo *TSInfo,
1862 void ActOnParamDefaultArgument(Decl *param,
1863 SourceLocation EqualLoc,
1865 void ActOnParamUnparsedDefaultArgument(Decl *param,
1866 SourceLocation EqualLoc,
1867 SourceLocation ArgLoc);
1868 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1869 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1870 SourceLocation EqualLoc);
1872 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1873 void ActOnUninitializedDecl(Decl *dcl);
1874 void ActOnInitializerError(Decl *Dcl);
1876 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1877 void ActOnCXXForRangeDecl(Decl *D);
1878 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1879 IdentifierInfo *Ident,
1880 ParsedAttributes &Attrs,
1881 SourceLocation AttrEnd);
1882 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1883 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1884 void FinalizeDeclaration(Decl *D);
1885 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1886 ArrayRef<Decl *> Group);
1887 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1889 /// Should be called on all declarations that might have attached
1890 /// documentation comments.
1891 void ActOnDocumentableDecl(Decl *D);
1892 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1894 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1895 SourceLocation LocAfterDecls);
1896 void CheckForFunctionRedefinition(
1897 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1898 SkipBodyInfo *SkipBody = nullptr);
1899 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1900 MultiTemplateParamsArg TemplateParamLists,
1901 SkipBodyInfo *SkipBody = nullptr);
1902 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1903 SkipBodyInfo *SkipBody = nullptr);
1904 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1905 bool isObjCMethodDecl(Decl *D) {
1906 return D && isa<ObjCMethodDecl>(D);
1909 /// \brief Determine whether we can delay parsing the body of a function or
1910 /// function template until it is used, assuming we don't care about emitting
1911 /// code for that function.
1913 /// This will be \c false if we may need the body of the function in the
1914 /// middle of parsing an expression (where it's impractical to switch to
1915 /// parsing a different function), for instance, if it's constexpr in C++11
1916 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1917 bool canDelayFunctionBody(const Declarator &D);
1919 /// \brief Determine whether we can skip parsing the body of a function
1920 /// definition, assuming we don't care about analyzing its body or emitting
1921 /// code for that function.
1923 /// This will be \c false only if we may need the body of the function in
1924 /// order to parse the rest of the program (for instance, if it is
1925 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1926 bool canSkipFunctionBody(Decl *D);
1928 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1929 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1930 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1931 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1932 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1934 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1935 /// attribute for which parsing is delayed.
1936 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1938 /// \brief Diagnose any unused parameters in the given sequence of
1939 /// ParmVarDecl pointers.
1940 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1942 /// \brief Diagnose whether the size of parameters or return value of a
1943 /// function or obj-c method definition is pass-by-value and larger than a
1944 /// specified threshold.
1946 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1947 QualType ReturnTy, NamedDecl *D);
1949 void DiagnoseInvalidJumps(Stmt *Body);
1950 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1951 SourceLocation AsmLoc,
1952 SourceLocation RParenLoc);
1954 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1955 Decl *ActOnEmptyDeclaration(Scope *S,
1956 AttributeList *AttrList,
1957 SourceLocation SemiLoc);
1959 enum class ModuleDeclKind {
1960 Module, ///< 'module X;'
1961 Partition, ///< 'module partition X;'
1962 Implementation, ///< 'module implementation X;'
1965 /// The parser has processed a module-declaration that begins the definition
1966 /// of a module interface or implementation.
1967 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
1968 SourceLocation ModuleLoc, ModuleDeclKind MDK,
1971 /// \brief The parser has processed a module import declaration.
1973 /// \param AtLoc The location of the '@' symbol, if any.
1975 /// \param ImportLoc The location of the 'import' keyword.
1977 /// \param Path The module access path.
1978 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1981 /// \brief The parser has processed a module import translated from a
1982 /// #include or similar preprocessing directive.
1983 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1984 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1986 /// \brief The parsed has entered a submodule.
1987 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1988 /// \brief The parser has left a submodule.
1989 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1991 /// \brief Create an implicit import of the given module at the given
1992 /// source location, for error recovery, if possible.
1994 /// This routine is typically used when an entity found by name lookup
1995 /// is actually hidden within a module that we know about but the user
1996 /// has forgotten to import.
1997 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2000 /// Kinds of missing import. Note, the values of these enumerators correspond
2001 /// to %select values in diagnostics.
2002 enum class MissingImportKind {
2006 ExplicitSpecialization,
2007 PartialSpecialization
2010 /// \brief Diagnose that the specified declaration needs to be visible but
2011 /// isn't, and suggest a module import that would resolve the problem.
2012 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2013 MissingImportKind MIK, bool Recover = true);
2014 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2015 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2016 MissingImportKind MIK, bool Recover);
2018 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2019 SourceLocation LBraceLoc);
2020 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2021 SourceLocation RBraceLoc);
2023 /// \brief We've found a use of a templated declaration that would trigger an
2024 /// implicit instantiation. Check that any relevant explicit specializations
2025 /// and partial specializations are visible, and diagnose if not.
2026 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2028 /// \brief We've found a use of a template specialization that would select a
2029 /// partial specialization. Check that the partial specialization is visible,
2030 /// and diagnose if not.
2031 void checkPartialSpecializationVisibility(SourceLocation Loc,
2034 /// \brief Retrieve a suitable printing policy.
2035 PrintingPolicy getPrintingPolicy() const {
2036 return getPrintingPolicy(Context, PP);
2039 /// \brief Retrieve a suitable printing policy.
2040 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2041 const Preprocessor &PP);
2044 void ActOnPopScope(SourceLocation Loc, Scope *S);
2045 void ActOnTranslationUnitScope(Scope *S);
2047 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2048 RecordDecl *&AnonRecord);
2049 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2050 MultiTemplateParamsArg TemplateParams,
2051 bool IsExplicitInstantiation,
2052 RecordDecl *&AnonRecord);
2054 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2057 const PrintingPolicy &Policy);
2059 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2060 RecordDecl *Record);
2062 /// Common ways to introduce type names without a tag for use in diagnostics.
2063 /// Keep in sync with err_tag_reference_non_tag.
2072 NTK_TypeAliasTemplate,
2073 NTK_TemplateTemplateArgument,
2076 /// Given a non-tag type declaration, returns an enum useful for indicating
2077 /// what kind of non-tag type this is.
2078 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2080 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2081 TagTypeKind NewTag, bool isDefinition,
2082 SourceLocation NewTagLoc,
2083 const IdentifierInfo *Name);
2086 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2087 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2088 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2089 TUK_Friend // Friend declaration: 'friend struct foo;'
2092 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2093 SourceLocation KWLoc, CXXScopeSpec &SS,
2094 IdentifierInfo *Name, SourceLocation NameLoc,
2095 AttributeList *Attr, AccessSpecifier AS,
2096 SourceLocation ModulePrivateLoc,
2097 MultiTemplateParamsArg TemplateParameterLists,
2098 bool &OwnedDecl, bool &IsDependent,
2099 SourceLocation ScopedEnumKWLoc,
2100 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2101 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2103 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2104 unsigned TagSpec, SourceLocation TagLoc,
2106 IdentifierInfo *Name, SourceLocation NameLoc,
2107 AttributeList *Attr,
2108 MultiTemplateParamsArg TempParamLists);
2110 TypeResult ActOnDependentTag(Scope *S,
2113 const CXXScopeSpec &SS,
2114 IdentifierInfo *Name,
2115 SourceLocation TagLoc,
2116 SourceLocation NameLoc);
2118 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2119 IdentifierInfo *ClassName,
2120 SmallVectorImpl<Decl *> &Decls);
2121 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2122 Declarator &D, Expr *BitfieldWidth);
2124 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2125 Declarator &D, Expr *BitfieldWidth,
2126 InClassInitStyle InitStyle,
2127 AccessSpecifier AS);
2128 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2129 SourceLocation DeclStart,
2130 Declarator &D, Expr *BitfieldWidth,
2131 InClassInitStyle InitStyle,
2133 AttributeList *MSPropertyAttr);
2135 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2136 TypeSourceInfo *TInfo,
2137 RecordDecl *Record, SourceLocation Loc,
2138 bool Mutable, Expr *BitfieldWidth,
2139 InClassInitStyle InitStyle,
2140 SourceLocation TSSL,
2141 AccessSpecifier AS, NamedDecl *PrevDecl,
2142 Declarator *D = nullptr);
2144 bool CheckNontrivialField(FieldDecl *FD);
2145 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2146 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2147 bool Diagnose = false);
2148 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2149 void ActOnLastBitfield(SourceLocation DeclStart,
2150 SmallVectorImpl<Decl *> &AllIvarDecls);
2151 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2152 Declarator &D, Expr *BitfieldWidth,
2153 tok::ObjCKeywordKind visibility);
2155 // This is used for both record definitions and ObjC interface declarations.
2156 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2157 ArrayRef<Decl *> Fields,
2158 SourceLocation LBrac, SourceLocation RBrac,
2159 AttributeList *AttrList);
2161 /// ActOnTagStartDefinition - Invoked when we have entered the
2162 /// scope of a tag's definition (e.g., for an enumeration, class,
2163 /// struct, or union).
2164 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2166 typedef void *SkippedDefinitionContext;
2168 /// \brief Invoked when we enter a tag definition that we're skipping.
2169 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2171 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2173 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2174 /// C++ record definition's base-specifiers clause and are starting its
2175 /// member declarations.
2176 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2177 SourceLocation FinalLoc,
2178 bool IsFinalSpelledSealed,
2179 SourceLocation LBraceLoc);
2181 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2182 /// the definition of a tag (enumeration, class, struct, or union).
2183 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2184 SourceRange BraceRange);
2186 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2188 void ActOnObjCContainerFinishDefinition();
2190 /// \brief Invoked when we must temporarily exit the objective-c container
2191 /// scope for parsing/looking-up C constructs.
2193 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2194 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2195 void ActOnObjCReenterContainerContext(DeclContext *DC);
2197 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2198 /// error parsing the definition of a tag.
2199 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2201 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2202 EnumConstantDecl *LastEnumConst,
2203 SourceLocation IdLoc,
2206 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2207 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2208 QualType EnumUnderlyingTy,
2209 bool EnumUnderlyingIsImplicit,
2210 const EnumDecl *Prev);
2212 /// Determine whether the body of an anonymous enumeration should be skipped.
2213 /// \param II The name of the first enumerator.
2214 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2215 SourceLocation IILoc);
2217 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2218 SourceLocation IdLoc, IdentifierInfo *Id,
2219 AttributeList *Attrs,
2220 SourceLocation EqualLoc, Expr *Val);
2221 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2223 ArrayRef<Decl *> Elements,
2224 Scope *S, AttributeList *Attr);
2226 DeclContext *getContainingDC(DeclContext *DC);
2228 /// Set the current declaration context until it gets popped.
2229 void PushDeclContext(Scope *S, DeclContext *DC);
2230 void PopDeclContext();
2232 /// EnterDeclaratorContext - Used when we must lookup names in the context
2233 /// of a declarator's nested name specifier.
2234 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2235 void ExitDeclaratorContext(Scope *S);
2237 /// Push the parameters of D, which must be a function, into scope.
2238 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2239 void ActOnExitFunctionContext();
2241 DeclContext *getFunctionLevelDeclContext();
2243 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2244 /// to the function decl for the function being parsed. If we're currently
2245 /// in a 'block', this returns the containing context.
2246 FunctionDecl *getCurFunctionDecl();
2248 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2249 /// the method decl for the method being parsed. If we're currently
2250 /// in a 'block', this returns the containing context.
2251 ObjCMethodDecl *getCurMethodDecl();
2253 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2254 /// or C function we're in, otherwise return null. If we're currently
2255 /// in a 'block', this returns the containing context.
2256 NamedDecl *getCurFunctionOrMethodDecl();
2258 /// Add this decl to the scope shadowed decl chains.
2259 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2261 /// \brief Make the given externally-produced declaration visible at the
2262 /// top level scope.
2264 /// \param D The externally-produced declaration to push.
2266 /// \param Name The name of the externally-produced declaration.
2267 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2269 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2270 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2271 /// true if 'D' belongs to the given declaration context.
2273 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2274 /// enclosing namespace set of the context, rather than contained
2275 /// directly within it.
2276 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2277 bool AllowInlineNamespace = false);
2279 /// Finds the scope corresponding to the given decl context, if it
2280 /// happens to be an enclosing scope. Otherwise return NULL.
2281 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2283 /// Subroutines of ActOnDeclarator().
2284 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2285 TypeSourceInfo *TInfo);
2286 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2288 /// \brief Describes the kind of merge to perform for availability
2289 /// attributes (including "deprecated", "unavailable", and "availability").
2290 enum AvailabilityMergeKind {
2291 /// \brief Don't merge availability attributes at all.
2293 /// \brief Merge availability attributes for a redeclaration, which requires
2296 /// \brief Merge availability attributes for an override, which requires
2297 /// an exact match or a weakening of constraints.
2299 /// \brief Merge availability attributes for an implementation of
2300 /// a protocol requirement.
2301 AMK_ProtocolImplementation,
2304 /// Attribute merging methods. Return true if a new attribute was added.
2305 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2306 IdentifierInfo *Platform,
2308 VersionTuple Introduced,
2309 VersionTuple Deprecated,
2310 VersionTuple Obsoleted,
2313 bool IsStrict, StringRef Replacement,
2314 AvailabilityMergeKind AMK,
2315 unsigned AttrSpellingListIndex);
2316 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2317 TypeVisibilityAttr::VisibilityType Vis,
2318 unsigned AttrSpellingListIndex);
2319 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2320 VisibilityAttr::VisibilityType Vis,
2321 unsigned AttrSpellingListIndex);
2322 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2323 unsigned AttrSpellingListIndex, StringRef Uuid);
2324 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2325 unsigned AttrSpellingListIndex);
2326 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2327 unsigned AttrSpellingListIndex);
2329 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2330 unsigned AttrSpellingListIndex,
2331 MSInheritanceAttr::Spelling SemanticSpelling);
2332 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2333 IdentifierInfo *Format, int FormatIdx,
2334 int FirstArg, unsigned AttrSpellingListIndex);
2335 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2336 unsigned AttrSpellingListIndex);
2337 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2338 IdentifierInfo *Ident,
2339 unsigned AttrSpellingListIndex);
2340 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2341 unsigned AttrSpellingListIndex);
2342 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2343 unsigned AttrSpellingListIndex);
2344 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2345 IdentifierInfo *Ident,
2346 unsigned AttrSpellingListIndex);
2347 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2348 unsigned AttrSpellingListIndex);
2350 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2351 AvailabilityMergeKind AMK = AMK_Redeclaration);
2352 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2353 LookupResult &OldDecls);
2354 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2355 bool MergeTypeWithOld);
2356 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2357 Scope *S, bool MergeTypeWithOld);
2358 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2359 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2360 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2361 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2362 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2363 void notePreviousDefinition(SourceLocation Old, SourceLocation New);
2364 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2366 // AssignmentAction - This is used by all the assignment diagnostic functions
2367 // to represent what is actually causing the operation
2368 enum AssignmentAction {
2376 AA_Passing_CFAudited
2379 /// C++ Overloading.
2381 /// This is a legitimate overload: the existing declarations are
2382 /// functions or function templates with different signatures.
2385 /// This is not an overload because the signature exactly matches
2386 /// an existing declaration.
2389 /// This is not an overload because the lookup results contain a
2393 OverloadKind CheckOverload(Scope *S,
2395 const LookupResult &OldDecls,
2396 NamedDecl *&OldDecl,
2397 bool IsForUsingDecl);
2398 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2399 bool ConsiderCudaAttrs = true);
2401 /// \brief Checks availability of the function depending on the current
2402 /// function context.Inside an unavailable function,unavailability is ignored.
2404 /// \returns true if \p FD is unavailable and current context is inside
2405 /// an available function, false otherwise.
2406 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2408 ImplicitConversionSequence
2409 TryImplicitConversion(Expr *From, QualType ToType,
2410 bool SuppressUserConversions,
2412 bool InOverloadResolution,
2414 bool AllowObjCWritebackConversion);
2416 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2417 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2418 bool IsComplexPromotion(QualType FromType, QualType ToType);
2419 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2420 bool InOverloadResolution,
2421 QualType& ConvertedType, bool &IncompatibleObjC);
2422 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2423 QualType& ConvertedType, bool &IncompatibleObjC);
2424 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2425 QualType &ConvertedType);
2426 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2427 QualType& ConvertedType);
2428 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2429 const FunctionProtoType *NewType,
2430 unsigned *ArgPos = nullptr);
2431 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2432 QualType FromType, QualType ToType);
2434 void maybeExtendBlockObject(ExprResult &E);
2435 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2436 bool CheckPointerConversion(Expr *From, QualType ToType,
2438 CXXCastPath& BasePath,
2439 bool IgnoreBaseAccess,
2440 bool Diagnose = true);
2441 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2442 bool InOverloadResolution,
2443 QualType &ConvertedType);
2444 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2446 CXXCastPath &BasePath,
2447 bool IgnoreBaseAccess);
2448 bool IsQualificationConversion(QualType FromType, QualType ToType,
2449 bool CStyle, bool &ObjCLifetimeConversion);
2450 bool IsFunctionConversion(QualType FromType, QualType ToType,
2451 QualType &ResultTy);
2452 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2453 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2455 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2456 const VarDecl *NRVOCandidate,
2457 QualType ResultType,
2459 bool AllowNRVO = true);
2461 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2463 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2464 SourceLocation EqualLoc,
2466 bool TopLevelOfInitList = false,
2467 bool AllowExplicit = false);
2468 ExprResult PerformObjectArgumentInitialization(Expr *From,
2469 NestedNameSpecifier *Qualifier,
2470 NamedDecl *FoundDecl,
2471 CXXMethodDecl *Method);
2473 ExprResult PerformContextuallyConvertToBool(Expr *From);
2474 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2476 /// Contexts in which a converted constant expression is required.
2478 CCEK_CaseValue, ///< Expression in a case label.
2479 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2480 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2481 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2482 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2484 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2485 llvm::APSInt &Value, CCEKind CCE);
2486 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2487 APValue &Value, CCEKind CCE);
2489 /// \brief Abstract base class used to perform a contextual implicit
2490 /// conversion from an expression to any type passing a filter.
2491 class ContextualImplicitConverter {
2494 bool SuppressConversion;
2496 ContextualImplicitConverter(bool Suppress = false,
2497 bool SuppressConversion = false)
2498 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2500 /// \brief Determine whether the specified type is a valid destination type
2501 /// for this conversion.
2502 virtual bool match(QualType T) = 0;
2504 /// \brief Emits a diagnostic complaining that the expression does not have
2505 /// integral or enumeration type.
2506 virtual SemaDiagnosticBuilder
2507 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2509 /// \brief Emits a diagnostic when the expression has incomplete class type.
2510 virtual SemaDiagnosticBuilder
2511 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2513 /// \brief Emits a diagnostic when the only matching conversion function
2515 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2516 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2518 /// \brief Emits a note for the explicit conversion function.
2519 virtual SemaDiagnosticBuilder
2520 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2522 /// \brief Emits a diagnostic when there are multiple possible conversion
2524 virtual SemaDiagnosticBuilder
2525 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2527 /// \brief Emits a note for one of the candidate conversions.
2528 virtual SemaDiagnosticBuilder
2529 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2531 /// \brief Emits a diagnostic when we picked a conversion function
2532 /// (for cases when we are not allowed to pick a conversion function).
2533 virtual SemaDiagnosticBuilder diagnoseConversion(
2534 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2536 virtual ~ContextualImplicitConverter() {}
2539 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2540 bool AllowScopedEnumerations;
2543 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2544 bool Suppress, bool SuppressConversion)
2545 : ContextualImplicitConverter(Suppress, SuppressConversion),
2546 AllowScopedEnumerations(AllowScopedEnumerations) {}
2548 /// Match an integral or (possibly scoped) enumeration type.
2549 bool match(QualType T) override;
2551 SemaDiagnosticBuilder
2552 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2553 return diagnoseNotInt(S, Loc, T);
2556 /// \brief Emits a diagnostic complaining that the expression does not have
2557 /// integral or enumeration type.
2558 virtual SemaDiagnosticBuilder
2559 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2562 /// Perform a contextual implicit conversion.
2563 ExprResult PerformContextualImplicitConversion(
2564 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2567 enum ObjCSubscriptKind {
2572 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2574 // Note that LK_String is intentionally after the other literals, as
2575 // this is used for diagnostics logic.
2576 enum ObjCLiteralKind {
2585 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2587 ExprResult PerformObjectMemberConversion(Expr *From,
2588 NestedNameSpecifier *Qualifier,
2589 NamedDecl *FoundDecl,
2592 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2593 // TODO: make this is a typesafe union.
2594 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2595 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2597 void AddOverloadCandidate(FunctionDecl *Function,
2598 DeclAccessPair FoundDecl,
2599 ArrayRef<Expr *> Args,
2600 OverloadCandidateSet &CandidateSet,
2601 bool SuppressUserConversions = false,
2602 bool PartialOverloading = false,
2603 bool AllowExplicit = false,
2604 ConversionSequenceList EarlyConversions = None);
2605 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2606 ArrayRef<Expr *> Args,
2607 OverloadCandidateSet &CandidateSet,
2608 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2609 bool SuppressUserConversions = false,
2610 bool PartialOverloading = false);
2611 void AddMethodCandidate(DeclAccessPair FoundDecl,
2612 QualType ObjectType,
2613 Expr::Classification ObjectClassification,
2614 ArrayRef<Expr *> Args,
2615 OverloadCandidateSet& CandidateSet,
2616 bool SuppressUserConversion = false);
2617 void AddMethodCandidate(CXXMethodDecl *Method,
2618 DeclAccessPair FoundDecl,
2619 CXXRecordDecl *ActingContext, QualType ObjectType,
2620 Expr::Classification ObjectClassification,
2621 ArrayRef<Expr *> Args,
2622 OverloadCandidateSet& CandidateSet,
2623 bool SuppressUserConversions = false,
2624 bool PartialOverloading = false,
2625 ConversionSequenceList EarlyConversions = None);
2626 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2627 DeclAccessPair FoundDecl,
2628 CXXRecordDecl *ActingContext,
2629 TemplateArgumentListInfo *ExplicitTemplateArgs,
2630 QualType ObjectType,
2631 Expr::Classification ObjectClassification,
2632 ArrayRef<Expr *> Args,
2633 OverloadCandidateSet& CandidateSet,
2634 bool SuppressUserConversions = false,
2635 bool PartialOverloading = false);
2636 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2637 DeclAccessPair FoundDecl,
2638 TemplateArgumentListInfo *ExplicitTemplateArgs,
2639 ArrayRef<Expr *> Args,
2640 OverloadCandidateSet& CandidateSet,
2641 bool SuppressUserConversions = false,
2642 bool PartialOverloading = false);
2643 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2644 ArrayRef<QualType> ParamTypes,
2645 ArrayRef<Expr *> Args,
2646 OverloadCandidateSet &CandidateSet,
2647 ConversionSequenceList &Conversions,
2648 bool SuppressUserConversions,
2649 CXXRecordDecl *ActingContext = nullptr,
2650 QualType ObjectType = QualType(),
2651 Expr::Classification
2652 ObjectClassification = {});
2653 void AddConversionCandidate(CXXConversionDecl *Conversion,
2654 DeclAccessPair FoundDecl,
2655 CXXRecordDecl *ActingContext,
2656 Expr *From, QualType ToType,
2657 OverloadCandidateSet& CandidateSet,
2658 bool AllowObjCConversionOnExplicit);
2659 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2660 DeclAccessPair FoundDecl,
2661 CXXRecordDecl *ActingContext,
2662 Expr *From, QualType ToType,
2663 OverloadCandidateSet &CandidateSet,
2664 bool AllowObjCConversionOnExplicit);
2665 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2666 DeclAccessPair FoundDecl,
2667 CXXRecordDecl *ActingContext,
2668 const FunctionProtoType *Proto,
2669 Expr *Object, ArrayRef<Expr *> Args,
2670 OverloadCandidateSet& CandidateSet);
2671 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2672 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2673 OverloadCandidateSet& CandidateSet,
2674 SourceRange OpRange = SourceRange());
2675 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2676 ArrayRef<Expr *> Args,
2677 OverloadCandidateSet& CandidateSet,
2678 bool IsAssignmentOperator = false,
2679 unsigned NumContextualBoolArguments = 0);
2680 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2681 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2682 OverloadCandidateSet& CandidateSet);
2683 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2685 ArrayRef<Expr *> Args,
2686 TemplateArgumentListInfo *ExplicitTemplateArgs,
2687 OverloadCandidateSet& CandidateSet,
2688 bool PartialOverloading = false);
2690 // Emit as a 'note' the specific overload candidate
2691 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2692 QualType DestType = QualType(),
2693 bool TakingAddress = false);
2695 // Emit as a series of 'note's all template and non-templates identified by
2696 // the expression Expr
2697 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2698 bool TakingAddress = false);
2700 /// Check the enable_if expressions on the given function. Returns the first
2701 /// failing attribute, or NULL if they were all successful.
2702 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2703 bool MissingImplicitThis = false);
2705 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2706 /// non-ArgDependent DiagnoseIfAttrs.
2708 /// Argument-dependent diagnose_if attributes should be checked each time a
2709 /// function is used as a direct callee of a function call.
2711 /// Returns true if any errors were emitted.
2712 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2713 const Expr *ThisArg,
2714 ArrayRef<const Expr *> Args,
2715 SourceLocation Loc);
2717 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2718 /// ArgDependent DiagnoseIfAttrs.
2720 /// Argument-independent diagnose_if attributes should be checked on every use
2723 /// Returns true if any errors were emitted.
2724 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2725 SourceLocation Loc);
2727 /// Returns whether the given function's address can be taken or not,
2728 /// optionally emitting a diagnostic if the address can't be taken.
2730 /// Returns false if taking the address of the function is illegal.
2731 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2732 bool Complain = false,
2733 SourceLocation Loc = SourceLocation());
2735 // [PossiblyAFunctionType] --> [Return]
2736 // NonFunctionType --> NonFunctionType
2738 // R (*)(A) --> R (A)
2739 // R (&)(A) --> R (A)
2740 // R (S::*)(A) --> R (A)
2741 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2744 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2745 QualType TargetType,
2747 DeclAccessPair &Found,
2748 bool *pHadMultipleCandidates = nullptr);
2751 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2752 DeclAccessPair &FoundResult);
2754 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2755 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2758 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2759 bool Complain = false,
2760 DeclAccessPair *Found = nullptr);
2762 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2763 ExprResult &SrcExpr,
2764 bool DoFunctionPointerConverion = false,
2765 bool Complain = false,
2766 SourceRange OpRangeForComplaining = SourceRange(),
2767 QualType DestTypeForComplaining = QualType(),
2768 unsigned DiagIDForComplaining = 0);
2771 Expr *FixOverloadedFunctionReference(Expr *E,
2772 DeclAccessPair FoundDecl,
2774 ExprResult FixOverloadedFunctionReference(ExprResult,
2775 DeclAccessPair FoundDecl,
2778 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2779 ArrayRef<Expr *> Args,
2780 OverloadCandidateSet &CandidateSet,
2781 bool PartialOverloading = false);
2783 // An enum used to represent the different possible results of building a
2784 // range-based for loop.
2785 enum ForRangeStatus {
2787 FRS_NoViableFunction,
2788 FRS_DiagnosticIssued
2791 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2792 SourceLocation RangeLoc,
2793 const DeclarationNameInfo &NameInfo,
2794 LookupResult &MemberLookup,
2795 OverloadCandidateSet *CandidateSet,
2796 Expr *Range, ExprResult *CallExpr);
2798 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2799 UnresolvedLookupExpr *ULE,
2800 SourceLocation LParenLoc,
2802 SourceLocation RParenLoc,
2804 bool AllowTypoCorrection=true,
2805 bool CalleesAddressIsTaken=false);
2807 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2808 MultiExprArg Args, SourceLocation RParenLoc,
2809 OverloadCandidateSet *CandidateSet,
2810 ExprResult *Result);
2812 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2813 UnaryOperatorKind Opc,
2814 const UnresolvedSetImpl &Fns,
2817 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2818 BinaryOperatorKind Opc,
2819 const UnresolvedSetImpl &Fns,
2820 Expr *LHS, Expr *RHS);
2822 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2823 SourceLocation RLoc,
2824 Expr *Base,Expr *Idx);
2827 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2828 SourceLocation LParenLoc,
2830 SourceLocation RParenLoc);
2832 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2834 SourceLocation RParenLoc);
2836 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2837 SourceLocation OpLoc,
2838 bool *NoArrowOperatorFound = nullptr);
2840 /// CheckCallReturnType - Checks that a call expression's return type is
2841 /// complete. Returns true on failure. The location passed in is the location
2842 /// that best represents the call.
2843 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2844 CallExpr *CE, FunctionDecl *FD);
2846 /// Helpers for dealing with blocks and functions.
2847 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2848 bool CheckParameterNames);
2849 void CheckCXXDefaultArguments(FunctionDecl *FD);
2850 void CheckExtraCXXDefaultArguments(Declarator &D);
2851 Scope *getNonFieldDeclScope(Scope *S);
2853 /// \name Name lookup
2855 /// These routines provide name lookup that is used during semantic
2856 /// analysis to resolve the various kinds of names (identifiers,
2857 /// overloaded operator names, constructor names, etc.) into zero or
2858 /// more declarations within a particular scope. The major entry
2859 /// points are LookupName, which performs unqualified name lookup,
2860 /// and LookupQualifiedName, which performs qualified name lookup.
2862 /// All name lookup is performed based on some specific criteria,
2863 /// which specify what names will be visible to name lookup and how
2864 /// far name lookup should work. These criteria are important both
2865 /// for capturing language semantics (certain lookups will ignore
2866 /// certain names, for example) and for performance, since name
2867 /// lookup is often a bottleneck in the compilation of C++. Name
2868 /// lookup criteria is specified via the LookupCriteria enumeration.
2870 /// The results of name lookup can vary based on the kind of name
2871 /// lookup performed, the current language, and the translation
2872 /// unit. In C, for example, name lookup will either return nothing
2873 /// (no entity found) or a single declaration. In C++, name lookup
2874 /// can additionally refer to a set of overloaded functions or
2875 /// result in an ambiguity. All of the possible results of name
2876 /// lookup are captured by the LookupResult class, which provides
2877 /// the ability to distinguish among them.
2880 /// @brief Describes the kind of name lookup to perform.
2881 enum LookupNameKind {
2882 /// Ordinary name lookup, which finds ordinary names (functions,
2883 /// variables, typedefs, etc.) in C and most kinds of names
2884 /// (functions, variables, members, types, etc.) in C++.
2885 LookupOrdinaryName = 0,
2886 /// Tag name lookup, which finds the names of enums, classes,
2887 /// structs, and unions.
2889 /// Label name lookup.
2891 /// Member name lookup, which finds the names of
2892 /// class/struct/union members.
2894 /// Look up of an operator name (e.g., operator+) for use with
2895 /// operator overloading. This lookup is similar to ordinary name
2896 /// lookup, but will ignore any declarations that are class members.
2898 /// Look up of a name that precedes the '::' scope resolution
2899 /// operator in C++. This lookup completely ignores operator, object,
2900 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2901 LookupNestedNameSpecifierName,
2902 /// Look up a namespace name within a C++ using directive or
2903 /// namespace alias definition, ignoring non-namespace names (C++
2904 /// [basic.lookup.udir]p1).
2905 LookupNamespaceName,
2906 /// Look up all declarations in a scope with the given name,
2907 /// including resolved using declarations. This is appropriate
2908 /// for checking redeclarations for a using declaration.
2909 LookupUsingDeclName,
2910 /// Look up an ordinary name that is going to be redeclared as a
2911 /// name with linkage. This lookup ignores any declarations that
2912 /// are outside of the current scope unless they have linkage. See
2913 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2914 LookupRedeclarationWithLinkage,
2915 /// Look up a friend of a local class. This lookup does not look
2916 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2917 LookupLocalFriendName,
2918 /// Look up the name of an Objective-C protocol.
2919 LookupObjCProtocolName,
2920 /// Look up implicit 'self' parameter of an objective-c method.
2921 LookupObjCImplicitSelfParam,
2922 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2923 LookupOMPReductionName,
2924 /// \brief Look up any declaration with any name.
2928 /// \brief Specifies whether (or how) name lookup is being performed for a
2929 /// redeclaration (vs. a reference).
2930 enum RedeclarationKind {
2931 /// \brief The lookup is a reference to this name that is not for the
2932 /// purpose of redeclaring the name.
2933 NotForRedeclaration = 0,
2934 /// \brief The lookup results will be used for redeclaration of a name,
2935 /// if an entity by that name already exists.
2939 /// \brief The possible outcomes of name lookup for a literal operator.
2940 enum LiteralOperatorLookupResult {
2941 /// \brief The lookup resulted in an error.
2943 /// \brief The lookup found a single 'cooked' literal operator, which
2944 /// expects a normal literal to be built and passed to it.
2946 /// \brief The lookup found a single 'raw' literal operator, which expects
2947 /// a string literal containing the spelling of the literal token.
2949 /// \brief The lookup found an overload set of literal operator templates,
2950 /// which expect the characters of the spelling of the literal token to be
2951 /// passed as a non-type template argument pack.
2953 /// \brief The lookup found an overload set of literal operator templates,
2954 /// which expect the character type and characters of the spelling of the
2955 /// string literal token to be passed as template arguments.
2959 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2960 CXXSpecialMember SM,
2967 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2968 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2969 TypoRecoveryCallback;
2972 bool CppLookupName(LookupResult &R, Scope *S);
2974 struct TypoExprState {
2975 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2976 TypoDiagnosticGenerator DiagHandler;
2977 TypoRecoveryCallback RecoveryHandler;
2979 TypoExprState(TypoExprState &&other) noexcept;
2980 TypoExprState &operator=(TypoExprState &&other) noexcept;
2983 /// \brief The set of unhandled TypoExprs and their associated state.
2984 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2986 /// \brief Creates a new TypoExpr AST node.
2987 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2988 TypoDiagnosticGenerator TDG,
2989 TypoRecoveryCallback TRC);
2991 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2993 // The boolean value will be true to indicate that the namespace was loaded
2994 // from an AST/PCH file, or false otherwise.
2995 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2997 /// \brief Whether we have already loaded known namespaces from an extenal
2999 bool LoadedExternalKnownNamespaces;
3001 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3002 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3003 /// should be skipped entirely.
3004 std::unique_ptr<TypoCorrectionConsumer>
3005 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3006 Sema::LookupNameKind LookupKind, Scope *S,
3008 std::unique_ptr<CorrectionCandidateCallback> CCC,
3009 DeclContext *MemberContext, bool EnteringContext,
3010 const ObjCObjectPointerType *OPT,
3011 bool ErrorRecovery);
3014 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3016 /// \brief Clears the state of the given TypoExpr.
3017 void clearDelayedTypo(TypoExpr *TE);
3019 /// \brief Look up a name, looking for a single declaration. Return
3020 /// null if the results were absent, ambiguous, or overloaded.
3022 /// It is preferable to use the elaborated form and explicitly handle
3023 /// ambiguity and overloaded.
3024 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3026 LookupNameKind NameKind,
3027 RedeclarationKind Redecl
3028 = NotForRedeclaration);
3029 bool LookupName(LookupResult &R, Scope *S,
3030 bool AllowBuiltinCreation = false);
3031 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3032 bool InUnqualifiedLookup = false);
3033 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3035 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3036 bool AllowBuiltinCreation = false,
3037 bool EnteringContext = false);
3038 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3039 RedeclarationKind Redecl
3040 = NotForRedeclaration);
3041 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3043 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3044 QualType T1, QualType T2,
3045 UnresolvedSetImpl &Functions);
3047 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3048 SourceLocation GnuLabelLoc = SourceLocation());
3050 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3051 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3052 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3054 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3055 bool RValueThis, unsigned ThisQuals);
3056 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3058 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3059 bool RValueThis, unsigned ThisQuals);
3060 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3062 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3063 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3064 ArrayRef<QualType> ArgTys,
3067 bool AllowStringTemplate);
3068 bool isKnownName(StringRef name);
3070 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3071 ArrayRef<Expr *> Args, ADLResult &Functions);
3073 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3074 VisibleDeclConsumer &Consumer,
3075 bool IncludeGlobalScope = true);
3076 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3077 VisibleDeclConsumer &Consumer,
3078 bool IncludeGlobalScope = true,
3079 bool IncludeDependentBases = false);
3081 enum CorrectTypoKind {
3082 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3083 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3086 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3087 Sema::LookupNameKind LookupKind,
3088 Scope *S, CXXScopeSpec *SS,
3089 std::unique_ptr<CorrectionCandidateCallback> CCC,
3090 CorrectTypoKind Mode,
3091 DeclContext *MemberContext = nullptr,
3092 bool EnteringContext = false,
3093 const ObjCObjectPointerType *OPT = nullptr,
3094 bool RecordFailure = true);
3096 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3097 Sema::LookupNameKind LookupKind, Scope *S,
3099 std::unique_ptr<CorrectionCandidateCallback> CCC,
3100 TypoDiagnosticGenerator TDG,
3101 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3102 DeclContext *MemberContext = nullptr,
3103 bool EnteringContext = false,
3104 const ObjCObjectPointerType *OPT = nullptr);
3106 /// \brief Process any TypoExprs in the given Expr and its children,
3107 /// generating diagnostics as appropriate and returning a new Expr if there
3108 /// were typos that were all successfully corrected and ExprError if one or
3109 /// more typos could not be corrected.
3111 /// \param E The Expr to check for TypoExprs.
3113 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3116 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3117 /// it is an acceptable/usable result from a single combination of typo
3118 /// corrections. As long as the filter returns ExprError, different
3119 /// combinations of corrections will be tried until all are exhausted.
3121 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3122 llvm::function_ref<ExprResult(Expr *)> Filter =
3123 [](Expr *E) -> ExprResult { return E; });
3126 CorrectDelayedTyposInExpr(Expr *E,
3127 llvm::function_ref<ExprResult(Expr *)> Filter) {
3128 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3132 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3133 llvm::function_ref<ExprResult(Expr *)> Filter =
3134 [](Expr *E) -> ExprResult { return E; }) {
3135 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3139 CorrectDelayedTyposInExpr(ExprResult ER,
3140 llvm::function_ref<ExprResult(Expr *)> Filter) {
3141 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3144 void diagnoseTypo(const TypoCorrection &Correction,
3145 const PartialDiagnostic &TypoDiag,
3146 bool ErrorRecovery = true);
3148 void diagnoseTypo(const TypoCorrection &Correction,
3149 const PartialDiagnostic &TypoDiag,
3150 const PartialDiagnostic &PrevNote,
3151 bool ErrorRecovery = true);
3153 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3155 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3156 ArrayRef<Expr *> Args,
3157 AssociatedNamespaceSet &AssociatedNamespaces,
3158 AssociatedClassSet &AssociatedClasses);
3160 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3161 bool ConsiderLinkage, bool AllowInlineNamespace);
3163 void DiagnoseAmbiguousLookup(LookupResult &Result);
3166 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3167 SourceLocation IdLoc,
3168 bool TypoCorrection = false);
3169 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3170 Scope *S, bool ForRedeclaration,
3171 SourceLocation Loc);
3172 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3174 void AddKnownFunctionAttributes(FunctionDecl *FD);
3176 // More parsing and symbol table subroutines.
3178 void ProcessPragmaWeak(Scope *S, Decl *D);
3179 // Decl attributes - this routine is the top level dispatcher.
3180 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3181 // Helper for delayed proccessing of attributes.
3182 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3183 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3184 bool IncludeCXX11Attributes = true);
3185 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3186 const AttributeList *AttrList);
3188 void checkUnusedDeclAttributes(Declarator &D);
3190 /// Determine if type T is a valid subject for a nonnull and similar
3191 /// attributes. By default, we look through references (the behavior used by
3192 /// nonnull), but if the second parameter is true, then we treat a reference
3194 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3196 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3197 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3198 const FunctionDecl *FD = nullptr);
3199 bool CheckNoReturnAttr(const AttributeList &attr);
3200 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3201 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3202 unsigned ArgNum, StringRef &Str,
3203 SourceLocation *ArgLocation = nullptr);
3204 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3205 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3206 bool checkMSInheritanceAttrOnDefinition(
3207 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3208 MSInheritanceAttr::Spelling SemanticSpelling);
3210 void CheckAlignasUnderalignment(Decl *D);
3212 /// Adjust the calling convention of a method to be the ABI default if it
3213 /// wasn't specified explicitly. This handles method types formed from
3214 /// function type typedefs and typename template arguments.
3215 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3216 SourceLocation Loc);
3218 // Check if there is an explicit attribute, but only look through parens.
3219 // The intent is to look for an attribute on the current declarator, but not
3220 // one that came from a typedef.
3221 bool hasExplicitCallingConv(QualType &T);
3223 /// Get the outermost AttributedType node that sets a calling convention.
3224 /// Valid types should not have multiple attributes with different CCs.
3225 const AttributedType *getCallingConvAttributedType(QualType T) const;
3227 /// Check whether a nullability type specifier can be added to the given
3230 /// \param type The type to which the nullability specifier will be
3231 /// added. On success, this type will be updated appropriately.
3233 /// \param nullability The nullability specifier to add.
3235 /// \param nullabilityLoc The location of the nullability specifier.
3237 /// \param isContextSensitive Whether this nullability specifier was
3238 /// written as a context-sensitive keyword (in an Objective-C
3239 /// method) or an Objective-C property attribute, rather than as an
3240 /// underscored type specifier.
3242 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3243 /// array type (e.g., because it will decay to a pointer).
3245 /// \returns true if nullability cannot be applied, false otherwise.
3246 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3247 SourceLocation nullabilityLoc,
3248 bool isContextSensitive,
3249 bool allowArrayTypes);
3251 /// \brief Stmt attributes - this routine is the top level dispatcher.
3252 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3255 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3256 ObjCMethodDecl *MethodDecl,
3257 bool IsProtocolMethodDecl);
3259 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3260 ObjCMethodDecl *Overridden,
3261 bool IsProtocolMethodDecl);
3263 /// WarnExactTypedMethods - This routine issues a warning if method
3264 /// implementation declaration matches exactly that of its declaration.
3265 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3266 ObjCMethodDecl *MethodDecl,
3267 bool IsProtocolMethodDecl);
3269 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3271 /// CheckImplementationIvars - This routine checks if the instance variables
3272 /// listed in the implelementation match those listed in the interface.
3273 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3274 ObjCIvarDecl **Fields, unsigned nIvars,
3275 SourceLocation Loc);
3277 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3278 /// remains unimplemented in the class or category \@implementation.
3279 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3280 ObjCContainerDecl* IDecl,
3281 bool IncompleteImpl = false);
3283 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3284 /// which must be implemented by this implementation.
3285 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3286 ObjCContainerDecl *CDecl,
3287 bool SynthesizeProperties);
3289 /// Diagnose any null-resettable synthesized setters.
3290 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3292 /// DefaultSynthesizeProperties - This routine default synthesizes all
3293 /// properties which must be synthesized in the class's \@implementation.
3294 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3295 ObjCInterfaceDecl *IDecl);
3296 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3298 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3299 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3300 /// declared in class 'IFace'.
3301 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3302 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3304 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3305 /// backs the property is not used in the property's accessor.
3306 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3307 const ObjCImplementationDecl *ImplD);
3309 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3310 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3311 /// It also returns ivar's property on success.
3312 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3313 const ObjCPropertyDecl *&PDecl) const;
3315 /// Called by ActOnProperty to handle \@property declarations in
3316 /// class extensions.
3317 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3318 SourceLocation AtLoc,
3319 SourceLocation LParenLoc,
3320 FieldDeclarator &FD,
3322 SourceLocation GetterNameLoc,
3324 SourceLocation SetterNameLoc,
3325 const bool isReadWrite,
3326 unsigned &Attributes,
3327 const unsigned AttributesAsWritten,
3329 TypeSourceInfo *TSI,
3330 tok::ObjCKeywordKind MethodImplKind);
3332 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3333 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3334 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3335 ObjCContainerDecl *CDecl,
3336 SourceLocation AtLoc,
3337 SourceLocation LParenLoc,
3338 FieldDeclarator &FD,
3340 SourceLocation GetterNameLoc,
3342 SourceLocation SetterNameLoc,
3343 const bool isReadWrite,
3344 const unsigned Attributes,
3345 const unsigned AttributesAsWritten,
3347 TypeSourceInfo *TSI,
3348 tok::ObjCKeywordKind MethodImplKind,
3349 DeclContext *lexicalDC = nullptr);
3351 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3352 /// warning) when atomic property has one but not the other user-declared
3353 /// setter or getter.
3354 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3355 ObjCInterfaceDecl* IDecl);
3357 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3359 void DiagnoseMissingDesignatedInitOverrides(
3360 const ObjCImplementationDecl *ImplD,
3361 const ObjCInterfaceDecl *IFD);
3363 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3365 enum MethodMatchStrategy {
3370 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3371 /// true, or false, accordingly.
3372 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3373 const ObjCMethodDecl *PrevMethod,
3374 MethodMatchStrategy strategy = MMS_strict);
3376 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3377 /// or protocol against those declared in their implementations.
3378 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3379 const SelectorSet &ClsMap,
3380 SelectorSet &InsMapSeen,
3381 SelectorSet &ClsMapSeen,
3382 ObjCImplDecl* IMPDecl,
3383 ObjCContainerDecl* IDecl,
3384 bool &IncompleteImpl,
3385 bool ImmediateClass,
3386 bool WarnCategoryMethodImpl=false);
3388 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3389 /// category matches with those implemented in its primary class and
3390 /// warns each time an exact match is found.
3391 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3393 /// \brief Add the given method to the list of globally-known methods.
3394 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3397 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3398 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3399 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3401 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3402 /// optionally warns if there are multiple signatures.
3403 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3404 bool receiverIdOrClass,
3408 /// \brief - Returns instance or factory methods in global method pool for
3409 /// given selector. It checks the desired kind first, if none is found, and
3410 /// parameter checkTheOther is set, it then checks the other kind. If no such
3411 /// method or only one method is found, function returns false; otherwise, it
3414 CollectMultipleMethodsInGlobalPool(Selector Sel,
3415 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3416 bool InstanceFirst, bool CheckTheOther,
3417 const ObjCObjectType *TypeBound = nullptr);
3420 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3421 SourceRange R, bool receiverIdOrClass,
3422 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3425 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3426 Selector Sel, SourceRange R,
3427 bool receiverIdOrClass);
3430 /// \brief - Returns a selector which best matches given argument list or
3431 /// nullptr if none could be found
3432 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3434 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3437 /// \brief Record the typo correction failure and return an empty correction.
3438 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3439 bool RecordFailure = true) {
3441 TypoCorrectionFailures[Typo].insert(TypoLoc);
3442 return TypoCorrection();
3446 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3447 /// unit are added to a global pool. This allows us to efficiently associate
3448 /// a selector with a method declaraation for purposes of typechecking
3449 /// messages sent to "id" (where the class of the object is unknown).
3450 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3451 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3454 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3455 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3456 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3459 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3461 void AddAnyMethodToGlobalPool(Decl *D);
3463 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3464 /// there are multiple signatures.
3465 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3466 bool receiverIdOrClass=false) {
3467 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3471 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3472 /// there are multiple signatures.
3473 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3474 bool receiverIdOrClass=false) {
3475 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3479 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3480 QualType ObjectType=QualType());
3481 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3483 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3485 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3487 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3488 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3490 //===--------------------------------------------------------------------===//
3491 // Statement Parsing Callbacks: SemaStmt.cpp.
3495 FullExprArg() : E(nullptr) { }
3496 FullExprArg(Sema &actions) : E(nullptr) { }
3498 ExprResult release() {
3502 Expr *get() const { return E; }
3504 Expr *operator->() {
3509 // FIXME: No need to make the entire Sema class a friend when it's just
3510 // Sema::MakeFullExpr that needs access to the constructor below.
3513 explicit FullExprArg(Expr *expr) : E(expr) {}
3518 FullExprArg MakeFullExpr(Expr *Arg) {
3519 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3521 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3522 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3524 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3526 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3527 /*DiscardedValue*/ true);
3528 return FullExprArg(FE.get());
3531 StmtResult ActOnExprStmt(ExprResult Arg);
3532 StmtResult ActOnExprStmtError();
3534 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3535 bool HasLeadingEmptyMacro = false);
3537 void ActOnStartOfCompoundStmt();
3538 void ActOnFinishOfCompoundStmt();
3539 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3540 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3542 /// \brief A RAII object to enter scope of a compound statement.
3543 class CompoundScopeRAII {
3545 CompoundScopeRAII(Sema &S): S(S) {
3546 S.ActOnStartOfCompoundStmt();
3549 ~CompoundScopeRAII() {
3550 S.ActOnFinishOfCompoundStmt();
3557 /// An RAII helper that pops function a function scope on exit.
3558 struct FunctionScopeRAII {
3561 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3562 ~FunctionScopeRAII() {
3564 S.PopFunctionScopeInfo();
3566 void disable() { Active = false; }
3569 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3570 SourceLocation StartLoc,
3571 SourceLocation EndLoc);
3572 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3573 StmtResult ActOnForEachLValueExpr(Expr *E);
3574 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3575 SourceLocation DotDotDotLoc, Expr *RHSVal,
3576 SourceLocation ColonLoc);
3577 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3579 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3580 SourceLocation ColonLoc,
3581 Stmt *SubStmt, Scope *CurScope);
3582 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3583 SourceLocation ColonLoc, Stmt *SubStmt);
3585 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3586 ArrayRef<const Attr*> Attrs,
3589 class ConditionResult;
3590 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3592 ConditionResult Cond, Stmt *ThenVal,
3593 SourceLocation ElseLoc, Stmt *ElseVal);
3594 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3596 ConditionResult Cond, Stmt *ThenVal,
3597 SourceLocation ElseLoc, Stmt *ElseVal);
3598 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3600 ConditionResult Cond);
3601 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3602 Stmt *Switch, Stmt *Body);
3603 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3605 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3606 SourceLocation WhileLoc, SourceLocation CondLParen,
3607 Expr *Cond, SourceLocation CondRParen);
3609 StmtResult ActOnForStmt(SourceLocation ForLoc,
3610 SourceLocation LParenLoc,
3612 ConditionResult Second,
3614 SourceLocation RParenLoc,
3616 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3618 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3619 Stmt *First, Expr *collection,
3620 SourceLocation RParenLoc);
3621 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3623 enum BuildForRangeKind {
3624 /// Initial building of a for-range statement.
3626 /// Instantiation or recovery rebuild of a for-range statement. Don't
3627 /// attempt any typo-correction.
3629 /// Determining whether a for-range statement could be built. Avoid any
3630 /// unnecessary or irreversible actions.
3634 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3635 SourceLocation CoawaitLoc,
3637 SourceLocation ColonLoc, Expr *Collection,
3638 SourceLocation RParenLoc,
3639 BuildForRangeKind Kind);
3640 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3641 SourceLocation CoawaitLoc,
3642 SourceLocation ColonLoc,
3643 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3644 Expr *Cond, Expr *Inc,
3646 SourceLocation RParenLoc,
3647 BuildForRangeKind Kind);
3648 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3650 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3651 SourceLocation LabelLoc,
3652 LabelDecl *TheDecl);
3653 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3654 SourceLocation StarLoc,
3656 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3657 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3659 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3660 CapturedRegionKind Kind, unsigned NumParams);
3661 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3662 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3663 CapturedRegionKind Kind,
3664 ArrayRef<CapturedParamNameType> Params);
3665 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3666 void ActOnCapturedRegionError();
3667 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3669 unsigned NumParams);
3670 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3671 bool AllowParamOrMoveConstructible);
3672 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3673 bool AllowParamOrMoveConstructible);
3675 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3677 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3678 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3680 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3681 bool IsVolatile, unsigned NumOutputs,
3682 unsigned NumInputs, IdentifierInfo **Names,
3683 MultiExprArg Constraints, MultiExprArg Exprs,
3684 Expr *AsmString, MultiExprArg Clobbers,
3685 SourceLocation RParenLoc);
3687 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3688 SourceLocation TemplateKWLoc,
3690 llvm::InlineAsmIdentifierInfo &Info,
3691 bool IsUnevaluatedContext);
3692 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3693 unsigned &Offset, SourceLocation AsmLoc);
3694 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3695 llvm::InlineAsmIdentifierInfo &Info,
3696 SourceLocation AsmLoc);
3697 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3698 ArrayRef<Token> AsmToks,
3699 StringRef AsmString,
3700 unsigned NumOutputs, unsigned NumInputs,
3701 ArrayRef<StringRef> Constraints,
3702 ArrayRef<StringRef> Clobbers,
3703 ArrayRef<Expr*> Exprs,
3704 SourceLocation EndLoc);
3705 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3706 SourceLocation Location,
3709 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3710 SourceLocation StartLoc,
3711 SourceLocation IdLoc, IdentifierInfo *Id,
3712 bool Invalid = false);
3714 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3716 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3717 Decl *Parm, Stmt *Body);
3719 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3721 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3722 MultiStmtArg Catch, Stmt *Finally);
3724 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3725 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3727 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3729 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3733 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3735 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3736 SourceLocation StartLoc,
3737 SourceLocation IdLoc,
3738 IdentifierInfo *Id);
3740 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3742 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3743 Decl *ExDecl, Stmt *HandlerBlock);
3744 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3745 ArrayRef<Stmt *> Handlers);
3747 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3748 SourceLocation TryLoc, Stmt *TryBlock,
3750 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3753 void ActOnStartSEHFinallyBlock();
3754 void ActOnAbortSEHFinallyBlock();
3755 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3756 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3758 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3760 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3762 /// \brief If it's a file scoped decl that must warn if not used, keep track
3764 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3766 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3767 /// whose result is unused, warn.
3768 void DiagnoseUnusedExprResult(const Stmt *S);
3769 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3770 void DiagnoseUnusedDecl(const NamedDecl *ND);
3772 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3773 /// statement as a \p Body, and it is located on the same line.
3775 /// This helps prevent bugs due to typos, such as:
3778 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3782 /// Warn if a for/while loop statement \p S, which is followed by
3783 /// \p PossibleBody, has a suspicious null statement as a body.
3784 void DiagnoseEmptyLoopBody(const Stmt *S,
3785 const Stmt *PossibleBody);
3787 /// Warn if a value is moved to itself.
3788 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3789 SourceLocation OpLoc);
3791 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3793 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3794 SourceLocation Loc);
3796 /// Warn when implicitly casting 0 to nullptr.
3797 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3799 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3800 return DelayedDiagnostics.push(pool);
3802 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3804 typedef ProcessingContextState ParsingClassState;
3805 ParsingClassState PushParsingClass() {
3806 return DelayedDiagnostics.pushUndelayed();
3808 void PopParsingClass(ParsingClassState state) {
3809 DelayedDiagnostics.popUndelayed(state);
3812 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3814 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3815 StringRef Message, SourceLocation Loc,
3816 const ObjCInterfaceDecl *UnknownObjCClass,
3817 const ObjCPropertyDecl *ObjCProperty,
3818 bool ObjCPropertyAccess);
3820 bool makeUnavailableInSystemHeader(SourceLocation loc,
3821 UnavailableAttr::ImplicitReason reason);
3823 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3824 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3826 //===--------------------------------------------------------------------===//
3827 // Expression Parsing Callbacks: SemaExpr.cpp.
3829 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3830 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3831 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3832 bool ObjCPropertyAccess=false);
3833 void NoteDeletedFunction(FunctionDecl *FD);
3834 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3835 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3836 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3837 ObjCMethodDecl *Getter,
3838 SourceLocation Loc);
3839 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3840 ArrayRef<Expr *> Args);
3842 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3843 Decl *LambdaContextDecl = nullptr,
3844 bool IsDecltype = false);
3845 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3846 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3847 ReuseLambdaContextDecl_t,
3848 bool IsDecltype = false);
3849 void PopExpressionEvaluationContext();
3851 void DiscardCleanupsInEvaluationContext();
3853 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3854 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3856 ExprResult ActOnConstantExpression(ExprResult Res);
3858 // Functions for marking a declaration referenced. These functions also
3859 // contain the relevant logic for marking if a reference to a function or
3860 // variable is an odr-use (in the C++11 sense). There are separate variants
3861 // for expressions referring to a decl; these exist because odr-use marking
3862 // needs to be delayed for some constant variables when we build one of the
3863 // named expressions.
3865 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3866 // should usually be true. This only needs to be set to false if the lack of
3867 // odr-use cannot be determined from the current context (for instance,
3868 // because the name denotes a virtual function and was written without an
3869 // explicit nested-name-specifier).
3870 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3871 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3872 bool MightBeOdrUse = true);
3873 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3874 void MarkDeclRefReferenced(DeclRefExpr *E);
3875 void MarkMemberReferenced(MemberExpr *E);
3877 void UpdateMarkingForLValueToRValue(Expr *E);
3878 void CleanupVarDeclMarking();
3880 enum TryCaptureKind {
3881 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3884 /// \brief Try to capture the given variable.
3886 /// \param Var The variable to capture.
3888 /// \param Loc The location at which the capture occurs.
3890 /// \param Kind The kind of capture, which may be implicit (for either a
3891 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3893 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3894 /// an explicit lambda capture.
3896 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3897 /// captures or diagnose errors. If false, this routine merely check whether
3898 /// the capture can occur without performing the capture itself or complaining
3899 /// if the variable cannot be captured.
3901 /// \param CaptureType Will be set to the type of the field used to capture
3902 /// this variable in the innermost block or lambda. Only valid when the
3903 /// variable can be captured.
3905 /// \param DeclRefType Will be set to the type of a reference to the capture
3906 /// from within the current scope. Only valid when the variable can be
3909 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3910 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3911 /// This is useful when enclosing lambdas must speculatively capture
3912 /// variables that may or may not be used in certain specializations of
3913 /// a nested generic lambda.
3915 /// \returns true if an error occurred (i.e., the variable cannot be
3916 /// captured) and false if the capture succeeded.
3917 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3918 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3919 QualType &CaptureType,
3920 QualType &DeclRefType,
3921 const unsigned *const FunctionScopeIndexToStopAt);
3923 /// \brief Try to capture the given variable.
3924 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3925 TryCaptureKind Kind = TryCapture_Implicit,
3926 SourceLocation EllipsisLoc = SourceLocation());
3928 /// \brief Checks if the variable must be captured.
3929 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3931 /// \brief Given a variable, determine the type that a reference to that
3932 /// variable will have in the given scope.
3933 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3935 /// Mark all of the declarations referenced within a particular AST node as
3936 /// referenced. Used when template instantiation instantiates a non-dependent
3937 /// type -- entities referenced by the type are now referenced.
3938 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3939 void MarkDeclarationsReferencedInExpr(Expr *E,
3940 bool SkipLocalVariables = false);
3942 /// \brief Try to recover by turning the given expression into a
3943 /// call. Returns true if recovery was attempted or an error was
3944 /// emitted; this may also leave the ExprResult invalid.
3945 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3946 bool ForceComplain = false,
3947 bool (*IsPlausibleResult)(QualType) = nullptr);
3949 /// \brief Figure out if an expression could be turned into a call.
3950 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3951 UnresolvedSetImpl &NonTemplateOverloads);
3953 /// \brief Conditionally issue a diagnostic based on the current
3954 /// evaluation context.
3956 /// \param Statement If Statement is non-null, delay reporting the
3957 /// diagnostic until the function body is parsed, and then do a basic
3958 /// reachability analysis to determine if the statement is reachable.
3959 /// If it is unreachable, the diagnostic will not be emitted.
3960 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3961 const PartialDiagnostic &PD);
3963 // Primary Expressions.
3964 SourceRange getExprRange(Expr *E) const;
3966 ExprResult ActOnIdExpression(
3967 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3968 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3969 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3970 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3972 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3973 TemplateArgumentListInfo &Buffer,
3974 DeclarationNameInfo &NameInfo,
3975 const TemplateArgumentListInfo *&TemplateArgs);
3978 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3979 std::unique_ptr<CorrectionCandidateCallback> CCC,
3980 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3981 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3983 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3985 bool AllowBuiltinCreation=false);
3987 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3988 SourceLocation TemplateKWLoc,
3989 const DeclarationNameInfo &NameInfo,
3990 bool isAddressOfOperand,
3991 const TemplateArgumentListInfo *TemplateArgs);
3993 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3996 const CXXScopeSpec *SS = nullptr);
3998 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3999 const DeclarationNameInfo &NameInfo,
4000 const CXXScopeSpec *SS = nullptr,
4001 NamedDecl *FoundD = nullptr,
4002 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4004 BuildAnonymousStructUnionMemberReference(
4005 const CXXScopeSpec &SS,
4006 SourceLocation nameLoc,
4007 IndirectFieldDecl *indirectField,
4008 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4009 Expr *baseObjectExpr = nullptr,
4010 SourceLocation opLoc = SourceLocation());
4012 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4013 SourceLocation TemplateKWLoc,
4015 const TemplateArgumentListInfo *TemplateArgs,
4017 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4018 SourceLocation TemplateKWLoc,
4020 const TemplateArgumentListInfo *TemplateArgs,
4021 bool IsDefiniteInstance,
4023 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4024 const LookupResult &R,
4025 bool HasTrailingLParen);
4028 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4029 const DeclarationNameInfo &NameInfo,
4030 bool IsAddressOfOperand, const Scope *S,
4031 TypeSourceInfo **RecoveryTSI = nullptr);
4033 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4034 SourceLocation TemplateKWLoc,
4035 const DeclarationNameInfo &NameInfo,
4036 const TemplateArgumentListInfo *TemplateArgs);
4038 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4041 bool AcceptInvalidDecl = false);
4042 ExprResult BuildDeclarationNameExpr(
4043 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4044 NamedDecl *FoundD = nullptr,
4045 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4046 bool AcceptInvalidDecl = false);
4048 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4049 DeclarationNameInfo &SuffixInfo,
4050 ArrayRef<Expr *> Args,
4051 SourceLocation LitEndLoc,
4052 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4054 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4055 PredefinedExpr::IdentType IT);
4056 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4057 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4059 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4061 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4062 ExprResult ActOnCharacterConstant(const Token &Tok,
4063 Scope *UDLScope = nullptr);
4064 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4065 ExprResult ActOnParenListExpr(SourceLocation L,
4069 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4070 /// fragments (e.g. "foo" "bar" L"baz").
4071 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4072 Scope *UDLScope = nullptr);
4074 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4075 SourceLocation DefaultLoc,
4076 SourceLocation RParenLoc,
4077 Expr *ControllingExpr,
4078 ArrayRef<ParsedType> ArgTypes,
4079 ArrayRef<Expr *> ArgExprs);
4080 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4081 SourceLocation DefaultLoc,
4082 SourceLocation RParenLoc,
4083 Expr *ControllingExpr,
4084 ArrayRef<TypeSourceInfo *> Types,
4085 ArrayRef<Expr *> Exprs);
4087 // Binary/Unary Operators. 'Tok' is the token for the operator.
4088 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4090 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4091 UnaryOperatorKind Opc, Expr *Input);
4092 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4093 tok::TokenKind Op, Expr *Input);
4095 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4097 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4098 SourceLocation OpLoc,
4099 UnaryExprOrTypeTrait ExprKind,
4101 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4102 UnaryExprOrTypeTrait ExprKind);
4104 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4105 UnaryExprOrTypeTrait ExprKind,
4106 bool IsType, void *TyOrEx,
4107 SourceRange ArgRange);
4109 ExprResult CheckPlaceholderExpr(Expr *E);
4110 bool CheckVecStepExpr(Expr *E);
4112 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4113 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4114 SourceRange ExprRange,
4115 UnaryExprOrTypeTrait ExprKind);
4116 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4117 SourceLocation OpLoc,
4118 IdentifierInfo &Name,
4119 SourceLocation NameLoc,
4120 SourceLocation RParenLoc);
4121 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4122 tok::TokenKind Kind, Expr *Input);
4124 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4125 Expr *Idx, SourceLocation RLoc);
4126 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4127 Expr *Idx, SourceLocation RLoc);
4128 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4129 Expr *LowerBound, SourceLocation ColonLoc,
4130 Expr *Length, SourceLocation RBLoc);
4132 // This struct is for use by ActOnMemberAccess to allow
4133 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4134 // changing the access operator from a '.' to a '->' (to see if that is the
4135 // change needed to fix an error about an unknown member, e.g. when the class
4136 // defines a custom operator->).
4137 struct ActOnMemberAccessExtraArgs {
4143 ExprResult BuildMemberReferenceExpr(
4144 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4145 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4146 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4147 const TemplateArgumentListInfo *TemplateArgs,
4149 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4152 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4153 bool IsArrow, const CXXScopeSpec &SS,
4154 SourceLocation TemplateKWLoc,
4155 NamedDecl *FirstQualifierInScope, LookupResult &R,
4156 const TemplateArgumentListInfo *TemplateArgs,
4158 bool SuppressQualifierCheck = false,
4159 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4161 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4162 SourceLocation OpLoc,
4163 const CXXScopeSpec &SS, FieldDecl *Field,
4164 DeclAccessPair FoundDecl,
4165 const DeclarationNameInfo &MemberNameInfo);
4167 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4169 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4170 const CXXScopeSpec &SS,
4171 const LookupResult &R);
4173 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4174 bool IsArrow, SourceLocation OpLoc,
4175 const CXXScopeSpec &SS,
4176 SourceLocation TemplateKWLoc,
4177 NamedDecl *FirstQualifierInScope,
4178 const DeclarationNameInfo &NameInfo,
4179 const TemplateArgumentListInfo *TemplateArgs);
4181 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4182 SourceLocation OpLoc,
4183 tok::TokenKind OpKind,
4185 SourceLocation TemplateKWLoc,
4186 UnqualifiedId &Member,
4189 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4190 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4191 FunctionDecl *FDecl,
4192 const FunctionProtoType *Proto,
4193 ArrayRef<Expr *> Args,
4194 SourceLocation RParenLoc,
4195 bool ExecConfig = false);
4196 void CheckStaticArrayArgument(SourceLocation CallLoc,
4198 const Expr *ArgExpr);
4200 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4201 /// This provides the location of the left/right parens and a list of comma
4203 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4204 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4205 Expr *ExecConfig = nullptr,
4206 bool IsExecConfig = false);
4207 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4208 SourceLocation LParenLoc,
4209 ArrayRef<Expr *> Arg,
4210 SourceLocation RParenLoc,
4211 Expr *Config = nullptr,
4212 bool IsExecConfig = false);
4214 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4215 MultiExprArg ExecConfig,
4216 SourceLocation GGGLoc);
4218 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4219 Declarator &D, ParsedType &Ty,
4220 SourceLocation RParenLoc, Expr *CastExpr);
4221 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4223 SourceLocation RParenLoc,
4225 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4227 /// \brief Build an altivec or OpenCL literal.
4228 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4229 SourceLocation RParenLoc, Expr *E,
4230 TypeSourceInfo *TInfo);
4232 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4234 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4236 SourceLocation RParenLoc,
4239 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4240 TypeSourceInfo *TInfo,
4241 SourceLocation RParenLoc,
4244 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4245 MultiExprArg InitArgList,
4246 SourceLocation RBraceLoc);
4248 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4254 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4257 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4258 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4259 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4260 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4261 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4262 Expr *LHSExpr, Expr *RHSExpr);
4264 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4266 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4267 /// in the case of a the GNU conditional expr extension.
4268 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4269 SourceLocation ColonLoc,
4270 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4272 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4273 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4274 LabelDecl *TheDecl);
4276 void ActOnStartStmtExpr();
4277 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4278 SourceLocation RPLoc); // "({..})"
4279 void ActOnStmtExprError();
4281 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4282 struct OffsetOfComponent {
4283 SourceLocation LocStart, LocEnd;
4284 bool isBrackets; // true if [expr], false if .ident
4286 IdentifierInfo *IdentInfo;
4291 /// __builtin_offsetof(type, a.b[123][456].c)
4292 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4293 TypeSourceInfo *TInfo,
4294 ArrayRef<OffsetOfComponent> Components,
4295 SourceLocation RParenLoc);
4296 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4297 SourceLocation BuiltinLoc,
4298 SourceLocation TypeLoc,
4299 ParsedType ParsedArgTy,
4300 ArrayRef<OffsetOfComponent> Components,
4301 SourceLocation RParenLoc);
4303 // __builtin_choose_expr(constExpr, expr1, expr2)
4304 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4305 Expr *CondExpr, Expr *LHSExpr,
4306 Expr *RHSExpr, SourceLocation RPLoc);
4308 // __builtin_va_arg(expr, type)
4309 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4310 SourceLocation RPLoc);
4311 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4312 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4315 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4317 bool CheckCaseExpression(Expr *E);
4319 /// \brief Describes the result of an "if-exists" condition check.
4320 enum IfExistsResult {
4321 /// \brief The symbol exists.
4324 /// \brief The symbol does not exist.
4327 /// \brief The name is a dependent name, so the results will differ
4328 /// from one instantiation to the next.
4331 /// \brief An error occurred.
4336 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4337 const DeclarationNameInfo &TargetNameInfo);
4340 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4341 bool IsIfExists, CXXScopeSpec &SS,
4342 UnqualifiedId &Name);
4344 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4346 NestedNameSpecifierLoc QualifierLoc,
4347 DeclarationNameInfo NameInfo,
4349 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4351 CXXScopeSpec &SS, UnqualifiedId &Name,
4354 //===------------------------- "Block" Extension ------------------------===//
4356 /// ActOnBlockStart - This callback is invoked when a block literal is
4358 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4360 /// ActOnBlockArguments - This callback allows processing of block arguments.
4361 /// If there are no arguments, this is still invoked.
4362 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4365 /// ActOnBlockError - If there is an error parsing a block, this callback
4366 /// is invoked to pop the information about the block from the action impl.
4367 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4369 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4370 /// literal was successfully completed. ^(int x){...}
4371 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4374 //===---------------------------- Clang Extensions ----------------------===//
4376 /// __builtin_convertvector(...)
4377 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4378 SourceLocation BuiltinLoc,
4379 SourceLocation RParenLoc);
4381 //===---------------------------- OpenCL Features -----------------------===//
4383 /// __builtin_astype(...)
4384 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4385 SourceLocation BuiltinLoc,
4386 SourceLocation RParenLoc);
4388 //===---------------------------- C++ Features --------------------------===//
4390 // Act on C++ namespaces
4391 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4392 SourceLocation NamespaceLoc,
4393 SourceLocation IdentLoc,
4394 IdentifierInfo *Ident,
4395 SourceLocation LBrace,
4396 AttributeList *AttrList,
4397 UsingDirectiveDecl * &UsingDecl);
4398 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4400 NamespaceDecl *getStdNamespace() const;
4401 NamespaceDecl *getOrCreateStdNamespace();
4403 NamespaceDecl *lookupStdExperimentalNamespace();
4405 CXXRecordDecl *getStdBadAlloc() const;
4406 EnumDecl *getStdAlignValT() const;
4408 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4409 /// it is and Element is not NULL, assigns the element type to Element.
4410 bool isStdInitializerList(QualType Ty, QualType *Element);
4412 /// \brief Looks for the std::initializer_list template and instantiates it
4413 /// with Element, or emits an error if it's not found.
4415 /// \returns The instantiated template, or null on error.
4416 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4418 /// \brief Determine whether Ctor is an initializer-list constructor, as
4419 /// defined in [dcl.init.list]p2.
4420 bool isInitListConstructor(const FunctionDecl *Ctor);
4422 Decl *ActOnUsingDirective(Scope *CurScope,
4423 SourceLocation UsingLoc,
4424 SourceLocation NamespcLoc,
4426 SourceLocation IdentLoc,
4427 IdentifierInfo *NamespcName,
4428 AttributeList *AttrList);
4430 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4432 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4433 SourceLocation NamespaceLoc,
4434 SourceLocation AliasLoc,
4435 IdentifierInfo *Alias,
4437 SourceLocation IdentLoc,
4438 IdentifierInfo *Ident);
4440 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4441 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4442 const LookupResult &PreviousDecls,
4443 UsingShadowDecl *&PrevShadow);
4444 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4446 UsingShadowDecl *PrevDecl);
4448 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4449 bool HasTypenameKeyword,
4450 const CXXScopeSpec &SS,
4451 SourceLocation NameLoc,
4452 const LookupResult &Previous);
4453 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4455 const CXXScopeSpec &SS,
4456 const DeclarationNameInfo &NameInfo,
4457 SourceLocation NameLoc);
4459 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4460 SourceLocation UsingLoc,
4461 bool HasTypenameKeyword,
4462 SourceLocation TypenameLoc,
4464 DeclarationNameInfo NameInfo,
4465 SourceLocation EllipsisLoc,
4466 AttributeList *AttrList,
4467 bool IsInstantiation);
4468 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4469 ArrayRef<NamedDecl *> Expansions);
4471 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4473 /// Given a derived-class using shadow declaration for a constructor and the
4474 /// correspnding base class constructor, find or create the implicit
4475 /// synthesized derived class constructor to use for this initialization.
4476 CXXConstructorDecl *
4477 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4478 ConstructorUsingShadowDecl *DerivedShadow);
4480 Decl *ActOnUsingDeclaration(Scope *CurScope,
4482 SourceLocation UsingLoc,
4483 SourceLocation TypenameLoc,
4485 UnqualifiedId &Name,
4486 SourceLocation EllipsisLoc,
4487 AttributeList *AttrList);
4488 Decl *ActOnAliasDeclaration(Scope *CurScope,
4490 MultiTemplateParamsArg TemplateParams,
4491 SourceLocation UsingLoc,
4492 UnqualifiedId &Name,
4493 AttributeList *AttrList,
4495 Decl *DeclFromDeclSpec);
4497 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4498 /// including handling of its default argument expressions.
4500 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4502 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4503 NamedDecl *FoundDecl,
4504 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4505 bool HadMultipleCandidates, bool IsListInitialization,
4506 bool IsStdInitListInitialization,
4507 bool RequiresZeroInit, unsigned ConstructKind,
4508 SourceRange ParenRange);
4510 /// Build a CXXConstructExpr whose constructor has already been resolved if
4511 /// it denotes an inherited constructor.
4513 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4514 CXXConstructorDecl *Constructor, bool Elidable,
4516 bool HadMultipleCandidates, bool IsListInitialization,
4517 bool IsStdInitListInitialization,
4518 bool RequiresZeroInit, unsigned ConstructKind,
4519 SourceRange ParenRange);
4521 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4522 // the constructor can be elidable?
4524 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4525 NamedDecl *FoundDecl,
4526 CXXConstructorDecl *Constructor, bool Elidable,
4527 MultiExprArg Exprs, bool HadMultipleCandidates,
4528 bool IsListInitialization,
4529 bool IsStdInitListInitialization, bool RequiresZeroInit,
4530 unsigned ConstructKind, SourceRange ParenRange);
4532 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4535 /// Instantiate or parse a C++ default argument expression as necessary.
4536 /// Return true on error.
4537 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4538 ParmVarDecl *Param);
4540 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4541 /// the default expr if needed.
4542 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4544 ParmVarDecl *Param);
4546 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4547 /// constructed variable.
4548 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4550 /// \brief Helper class that collects exception specifications for
4551 /// implicitly-declared special member functions.
4552 class ImplicitExceptionSpecification {
4553 // Pointer to allow copying
4555 // We order exception specifications thus:
4556 // noexcept is the most restrictive, but is only used in C++11.
4557 // throw() comes next.
4558 // Then a throw(collected exceptions)
4559 // Finally no specification, which is expressed as noexcept(false).
4560 // throw(...) is used instead if any called function uses it.
4561 ExceptionSpecificationType ComputedEST;
4562 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4563 SmallVector<QualType, 4> Exceptions;
4565 void ClearExceptions() {
4566 ExceptionsSeen.clear();
4571 explicit ImplicitExceptionSpecification(Sema &Self)
4572 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4573 if (!Self.getLangOpts().CPlusPlus11)
4574 ComputedEST = EST_DynamicNone;
4577 /// \brief Get the computed exception specification type.
4578 ExceptionSpecificationType getExceptionSpecType() const {
4579 assert(ComputedEST != EST_ComputedNoexcept &&
4580 "noexcept(expr) should not be a possible result");
4584 /// \brief The number of exceptions in the exception specification.
4585 unsigned size() const { return Exceptions.size(); }
4587 /// \brief The set of exceptions in the exception specification.
4588 const QualType *data() const { return Exceptions.data(); }
4590 /// \brief Integrate another called method into the collected data.
4591 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4593 /// \brief Integrate an invoked expression into the collected data.
4594 void CalledExpr(Expr *E);
4596 /// \brief Overwrite an EPI's exception specification with this
4597 /// computed exception specification.
4598 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4599 FunctionProtoType::ExceptionSpecInfo ESI;
4600 ESI.Type = getExceptionSpecType();
4601 if (ESI.Type == EST_Dynamic) {
4602 ESI.Exceptions = Exceptions;
4603 } else if (ESI.Type == EST_None) {
4604 /// C++11 [except.spec]p14:
4605 /// The exception-specification is noexcept(false) if the set of
4606 /// potential exceptions of the special member function contains "any"
4607 ESI.Type = EST_ComputedNoexcept;
4608 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4609 tok::kw_false).get();
4615 /// \brief Determine what sort of exception specification a defaulted
4616 /// copy constructor of a class will have.
4617 ImplicitExceptionSpecification
4618 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4621 /// \brief Determine what sort of exception specification a defaulted
4622 /// default constructor of a class will have, and whether the parameter
4624 ImplicitExceptionSpecification
4625 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4627 /// \brief Determine what sort of exception specification a defautled
4628 /// copy assignment operator of a class will have, and whether the
4629 /// parameter will be const.
4630 ImplicitExceptionSpecification
4631 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4633 /// \brief Determine what sort of exception specification a defaulted move
4634 /// constructor of a class will have.
4635 ImplicitExceptionSpecification
4636 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4638 /// \brief Determine what sort of exception specification a defaulted move
4639 /// assignment operator of a class will have.
4640 ImplicitExceptionSpecification
4641 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4643 /// \brief Determine what sort of exception specification a defaulted
4644 /// destructor of a class will have.
4645 ImplicitExceptionSpecification
4646 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4648 /// \brief Determine what sort of exception specification an inheriting
4649 /// constructor of a class will have.
4650 ImplicitExceptionSpecification
4651 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4652 CXXConstructorDecl *CD);
4654 /// \brief Evaluate the implicit exception specification for a defaulted
4655 /// special member function.
4656 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4658 /// \brief Check the given exception-specification and update the
4659 /// exception specification information with the results.
4660 void checkExceptionSpecification(bool IsTopLevel,
4661 ExceptionSpecificationType EST,
4662 ArrayRef<ParsedType> DynamicExceptions,
4663 ArrayRef<SourceRange> DynamicExceptionRanges,
4665 SmallVectorImpl<QualType> &Exceptions,
4666 FunctionProtoType::ExceptionSpecInfo &ESI);
4668 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4669 /// parse an exception specification to work around a libstdc++ bug.
4670 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4672 /// \brief Add an exception-specification to the given member function
4673 /// (or member function template). The exception-specification was parsed
4674 /// after the method itself was declared.
4675 void actOnDelayedExceptionSpecification(Decl *Method,
4676 ExceptionSpecificationType EST,
4677 SourceRange SpecificationRange,
4678 ArrayRef<ParsedType> DynamicExceptions,
4679 ArrayRef<SourceRange> DynamicExceptionRanges,
4680 Expr *NoexceptExpr);
4682 class InheritedConstructorInfo;
4684 /// \brief Determine if a special member function should have a deleted
4685 /// definition when it is defaulted.
4686 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4687 InheritedConstructorInfo *ICI = nullptr,
4688 bool Diagnose = false);
4690 /// \brief Declare the implicit default constructor for the given class.
4692 /// \param ClassDecl The class declaration into which the implicit
4693 /// default constructor will be added.
4695 /// \returns The implicitly-declared default constructor.
4696 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4697 CXXRecordDecl *ClassDecl);
4699 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4700 /// defining this constructor as the default constructor.
4701 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4702 CXXConstructorDecl *Constructor);
4704 /// \brief Declare the implicit destructor for the given class.
4706 /// \param ClassDecl The class declaration into which the implicit
4707 /// destructor will be added.
4709 /// \returns The implicitly-declared destructor.
4710 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4712 /// DefineImplicitDestructor - Checks for feasibility of
4713 /// defining this destructor as the default destructor.
4714 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4715 CXXDestructorDecl *Destructor);
4717 /// \brief Build an exception spec for destructors that don't have one.
4719 /// C++11 says that user-defined destructors with no exception spec get one
4720 /// that looks as if the destructor was implicitly declared.
4721 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4722 CXXDestructorDecl *Destructor);
4724 /// \brief Define the specified inheriting constructor.
4725 void DefineInheritingConstructor(SourceLocation UseLoc,
4726 CXXConstructorDecl *Constructor);
4728 /// \brief Declare the implicit copy constructor for the given class.
4730 /// \param ClassDecl The class declaration into which the implicit
4731 /// copy constructor will be added.
4733 /// \returns The implicitly-declared copy constructor.
4734 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4736 /// DefineImplicitCopyConstructor - Checks for feasibility of
4737 /// defining this constructor as the copy constructor.
4738 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4739 CXXConstructorDecl *Constructor);
4741 /// \brief Declare the implicit move constructor for the given class.
4743 /// \param ClassDecl The Class declaration into which the implicit
4744 /// move constructor will be added.
4746 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4748 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4750 /// DefineImplicitMoveConstructor - Checks for feasibility of
4751 /// defining this constructor as the move constructor.
4752 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4753 CXXConstructorDecl *Constructor);
4755 /// \brief Declare the implicit copy assignment operator for the given class.
4757 /// \param ClassDecl The class declaration into which the implicit
4758 /// copy assignment operator will be added.
4760 /// \returns The implicitly-declared copy assignment operator.
4761 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4763 /// \brief Defines an implicitly-declared copy assignment operator.
4764 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4765 CXXMethodDecl *MethodDecl);
4767 /// \brief Declare the implicit move assignment operator for the given class.
4769 /// \param ClassDecl The Class declaration into which the implicit
4770 /// move assignment operator will be added.
4772 /// \returns The implicitly-declared move assignment operator, or NULL if it
4773 /// wasn't declared.
4774 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4776 /// \brief Defines an implicitly-declared move assignment operator.
4777 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4778 CXXMethodDecl *MethodDecl);
4780 /// \brief Force the declaration of any implicitly-declared members of this
4782 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4784 /// \brief Check a completed declaration of an implicit special member.
4785 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4787 /// \brief Determine whether the given function is an implicitly-deleted
4788 /// special member function.
4789 bool isImplicitlyDeleted(FunctionDecl *FD);
4791 /// \brief Check whether 'this' shows up in the type of a static member
4792 /// function after the (naturally empty) cv-qualifier-seq would be.
4794 /// \returns true if an error occurred.
4795 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4797 /// \brief Whether this' shows up in the exception specification of a static
4798 /// member function.
4799 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4801 /// \brief Check whether 'this' shows up in the attributes of the given
4802 /// static member function.
4804 /// \returns true if an error occurred.
4805 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4807 /// MaybeBindToTemporary - If the passed in expression has a record type with
4808 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4809 /// it simply returns the passed in expression.
4810 ExprResult MaybeBindToTemporary(Expr *E);
4812 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4813 MultiExprArg ArgsPtr,
4815 SmallVectorImpl<Expr*> &ConvertedArgs,
4816 bool AllowExplicit = false,
4817 bool IsListInitialization = false);
4819 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4820 SourceLocation NameLoc,
4821 IdentifierInfo &Name);
4823 ParsedType getDestructorName(SourceLocation TildeLoc,
4824 IdentifierInfo &II, SourceLocation NameLoc,
4825 Scope *S, CXXScopeSpec &SS,
4826 ParsedType ObjectType,
4827 bool EnteringContext);
4829 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4830 ParsedType ObjectType);
4832 // Checks that reinterpret casts don't have undefined behavior.
4833 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4834 bool IsDereference, SourceRange Range);
4836 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4837 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4838 tok::TokenKind Kind,
4839 SourceLocation LAngleBracketLoc,
4841 SourceLocation RAngleBracketLoc,
4842 SourceLocation LParenLoc,
4844 SourceLocation RParenLoc);
4846 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4847 tok::TokenKind Kind,
4850 SourceRange AngleBrackets,
4851 SourceRange Parens);
4853 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4854 SourceLocation TypeidLoc,
4855 TypeSourceInfo *Operand,
4856 SourceLocation RParenLoc);
4857 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4858 SourceLocation TypeidLoc,
4860 SourceLocation RParenLoc);
4862 /// ActOnCXXTypeid - Parse typeid( something ).
4863 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4864 SourceLocation LParenLoc, bool isType,
4866 SourceLocation RParenLoc);
4868 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4869 SourceLocation TypeidLoc,
4870 TypeSourceInfo *Operand,
4871 SourceLocation RParenLoc);
4872 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4873 SourceLocation TypeidLoc,
4875 SourceLocation RParenLoc);
4877 /// ActOnCXXUuidof - Parse __uuidof( something ).
4878 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4879 SourceLocation LParenLoc, bool isType,
4881 SourceLocation RParenLoc);
4883 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4884 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4885 tok::TokenKind Operator,
4886 SourceLocation EllipsisLoc, Expr *RHS,
4887 SourceLocation RParenLoc);
4888 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4889 BinaryOperatorKind Operator,
4890 SourceLocation EllipsisLoc, Expr *RHS,
4891 SourceLocation RParenLoc);
4892 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4893 BinaryOperatorKind Operator);
4895 //// ActOnCXXThis - Parse 'this' pointer.
4896 ExprResult ActOnCXXThis(SourceLocation loc);
4898 /// \brief Try to retrieve the type of the 'this' pointer.
4900 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4901 QualType getCurrentThisType();
4903 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4904 /// current context not being a non-static member function. In such cases,
4905 /// this provides the type used for 'this'.
4906 QualType CXXThisTypeOverride;
4908 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4909 /// to be used, with the given qualifiers on the current class type.
4910 class CXXThisScopeRAII {
4912 QualType OldCXXThisTypeOverride;
4916 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4917 /// using the given declaration (which is either a class template or a
4918 /// class) along with the given qualifiers.
4919 /// along with the qualifiers placed on '*this'.
4920 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4921 bool Enabled = true);
4923 ~CXXThisScopeRAII();
4926 /// \brief Make sure the value of 'this' is actually available in the current
4927 /// context, if it is a potentially evaluated context.
4929 /// \param Loc The location at which the capture of 'this' occurs.
4931 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4934 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4935 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4936 /// This is useful when enclosing lambdas must speculatively capture
4937 /// 'this' that may or may not be used in certain specializations of
4938 /// a nested generic lambda (depending on whether the name resolves to
4939 /// a non-static member function or a static function).
4940 /// \return returns 'true' if failed, 'false' if success.
4941 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4942 bool BuildAndDiagnose = true,
4943 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4944 bool ByCopy = false);
4946 /// \brief Determine whether the given type is the type of *this that is used
4947 /// outside of the body of a member function for a type that is currently
4949 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4951 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4952 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4955 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4956 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4959 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4960 SourceLocation AtLoc, SourceLocation RParen);
4962 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4963 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4965 //// ActOnCXXThrow - Parse throw expressions.
4966 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4967 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4968 bool IsThrownVarInScope);
4969 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4971 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4972 /// Can be interpreted either as function-style casting ("int(x)")
4973 /// or class type construction ("ClassType(x,y,z)")
4974 /// or creation of a value-initialized type ("int()").
4975 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4976 SourceLocation LParenLoc,
4978 SourceLocation RParenLoc);
4980 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4981 SourceLocation LParenLoc,
4983 SourceLocation RParenLoc);
4985 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4986 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4987 SourceLocation PlacementLParen,
4988 MultiExprArg PlacementArgs,
4989 SourceLocation PlacementRParen,
4990 SourceRange TypeIdParens, Declarator &D,
4992 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4993 SourceLocation PlacementLParen,
4994 MultiExprArg PlacementArgs,
4995 SourceLocation PlacementRParen,
4996 SourceRange TypeIdParens,
4998 TypeSourceInfo *AllocTypeInfo,
5000 SourceRange DirectInitRange,
5003 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5005 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5006 bool UseGlobal, QualType AllocType, bool IsArray,
5007 bool &PassAlignment, MultiExprArg PlaceArgs,
5008 FunctionDecl *&OperatorNew,
5009 FunctionDecl *&OperatorDelete);
5010 void DeclareGlobalNewDelete();
5011 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5012 ArrayRef<QualType> Params);
5014 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5015 DeclarationName Name, FunctionDecl* &Operator,
5016 bool Diagnose = true);
5017 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5018 bool CanProvideSize,
5020 DeclarationName Name);
5021 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5024 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5025 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5026 bool UseGlobal, bool ArrayForm,
5028 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5029 bool IsDelete, bool CallCanBeVirtual,
5030 bool WarnOnNonAbstractTypes,
5031 SourceLocation DtorLoc);
5033 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5034 Expr *Operand, SourceLocation RParen);
5035 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5036 SourceLocation RParen);
5038 /// \brief Parsed one of the type trait support pseudo-functions.
5039 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5040 ArrayRef<ParsedType> Args,
5041 SourceLocation RParenLoc);
5042 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5043 ArrayRef<TypeSourceInfo *> Args,
5044 SourceLocation RParenLoc);
5046 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5047 /// pseudo-functions.
5048 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5049 SourceLocation KWLoc,
5052 SourceLocation RParen);
5054 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5055 SourceLocation KWLoc,
5056 TypeSourceInfo *TSInfo,
5058 SourceLocation RParen);
5060 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5061 /// pseudo-functions.
5062 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5063 SourceLocation KWLoc,
5065 SourceLocation RParen);
5067 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5068 SourceLocation KWLoc,
5070 SourceLocation RParen);
5072 ExprResult ActOnStartCXXMemberReference(Scope *S,
5074 SourceLocation OpLoc,
5075 tok::TokenKind OpKind,
5076 ParsedType &ObjectType,
5077 bool &MayBePseudoDestructor);
5079 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5080 SourceLocation OpLoc,
5081 tok::TokenKind OpKind,
5082 const CXXScopeSpec &SS,
5083 TypeSourceInfo *ScopeType,
5084 SourceLocation CCLoc,
5085 SourceLocation TildeLoc,
5086 PseudoDestructorTypeStorage DestroyedType);
5088 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5089 SourceLocation OpLoc,
5090 tok::TokenKind OpKind,
5092 UnqualifiedId &FirstTypeName,
5093 SourceLocation CCLoc,
5094 SourceLocation TildeLoc,
5095 UnqualifiedId &SecondTypeName);
5097 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5098 SourceLocation OpLoc,
5099 tok::TokenKind OpKind,
5100 SourceLocation TildeLoc,
5101 const DeclSpec& DS);
5103 /// MaybeCreateExprWithCleanups - If the current full-expression
5104 /// requires any cleanups, surround it with a ExprWithCleanups node.
5105 /// Otherwise, just returns the passed-in expression.
5106 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5107 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5108 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5110 MaterializeTemporaryExpr *
5111 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5112 bool BoundToLvalueReference);
5114 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5115 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5116 : SourceLocation());
5118 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5119 bool DiscardedValue = false,
5120 bool IsConstexpr = false,
5121 bool IsLambdaInitCaptureInitializer = false);
5122 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5124 // Marks SS invalid if it represents an incomplete type.
5125 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5127 DeclContext *computeDeclContext(QualType T);
5128 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5129 bool EnteringContext = false);
5130 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5131 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5133 /// \brief The parser has parsed a global nested-name-specifier '::'.
5135 /// \param CCLoc The location of the '::'.
5137 /// \param SS The nested-name-specifier, which will be updated in-place
5138 /// to reflect the parsed nested-name-specifier.
5140 /// \returns true if an error occurred, false otherwise.
5141 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5143 /// \brief The parser has parsed a '__super' nested-name-specifier.
5145 /// \param SuperLoc The location of the '__super' keyword.
5147 /// \param ColonColonLoc The location of the '::'.
5149 /// \param SS The nested-name-specifier, which will be updated in-place
5150 /// to reflect the parsed nested-name-specifier.
5152 /// \returns true if an error occurred, false otherwise.
5153 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5154 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5156 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5157 bool *CanCorrect = nullptr);
5158 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5160 /// \brief Keeps information about an identifier in a nested-name-spec.
5162 struct NestedNameSpecInfo {
5163 /// \brief The type of the object, if we're parsing nested-name-specifier in
5164 /// a member access expression.
5165 ParsedType ObjectType;
5167 /// \brief The identifier preceding the '::'.
5168 IdentifierInfo *Identifier;
5170 /// \brief The location of the identifier.
5171 SourceLocation IdentifierLoc;
5173 /// \brief The location of the '::'.
5174 SourceLocation CCLoc;
5176 /// \brief Creates info object for the most typical case.
5177 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5178 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5179 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5180 CCLoc(ColonColonLoc) {
5183 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5184 SourceLocation ColonColonLoc, QualType ObjectType)
5185 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5186 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5190 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5191 NestedNameSpecInfo &IdInfo);
5193 bool BuildCXXNestedNameSpecifier(Scope *S,
5194 NestedNameSpecInfo &IdInfo,
5195 bool EnteringContext,
5197 NamedDecl *ScopeLookupResult,
5198 bool ErrorRecoveryLookup,
5199 bool *IsCorrectedToColon = nullptr,
5200 bool OnlyNamespace = false);
5202 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5204 /// \param S The scope in which this nested-name-specifier occurs.
5206 /// \param IdInfo Parser information about an identifier in the
5207 /// nested-name-spec.
5209 /// \param EnteringContext Whether we're entering the context nominated by
5210 /// this nested-name-specifier.
5212 /// \param SS The nested-name-specifier, which is both an input
5213 /// parameter (the nested-name-specifier before this type) and an
5214 /// output parameter (containing the full nested-name-specifier,
5215 /// including this new type).
5217 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5218 /// error recovery. In this case do not emit error message.
5220 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5221 /// are allowed. The bool value pointed by this parameter is set to 'true'
5222 /// if the identifier is treated as if it was followed by ':', not '::'.
5224 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5226 /// \returns true if an error occurred, false otherwise.
5227 bool ActOnCXXNestedNameSpecifier(Scope *S,
5228 NestedNameSpecInfo &IdInfo,
5229 bool EnteringContext,
5231 bool ErrorRecoveryLookup = false,
5232 bool *IsCorrectedToColon = nullptr,
5233 bool OnlyNamespace = false);
5235 ExprResult ActOnDecltypeExpression(Expr *E);
5237 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5239 SourceLocation ColonColonLoc);
5241 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5242 NestedNameSpecInfo &IdInfo,
5243 bool EnteringContext);
5245 /// \brief The parser has parsed a nested-name-specifier
5246 /// 'template[opt] template-name < template-args >::'.
5248 /// \param S The scope in which this nested-name-specifier occurs.
5250 /// \param SS The nested-name-specifier, which is both an input
5251 /// parameter (the nested-name-specifier before this type) and an
5252 /// output parameter (containing the full nested-name-specifier,
5253 /// including this new type).
5255 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5256 /// \param TemplateName the template name.
5257 /// \param TemplateNameLoc The location of the template name.
5258 /// \param LAngleLoc The location of the opening angle bracket ('<').
5259 /// \param TemplateArgs The template arguments.
5260 /// \param RAngleLoc The location of the closing angle bracket ('>').
5261 /// \param CCLoc The location of the '::'.
5263 /// \param EnteringContext Whether we're entering the context of the
5264 /// nested-name-specifier.
5267 /// \returns true if an error occurred, false otherwise.
5268 bool ActOnCXXNestedNameSpecifier(Scope *S,
5270 SourceLocation TemplateKWLoc,
5271 TemplateTy TemplateName,
5272 SourceLocation TemplateNameLoc,
5273 SourceLocation LAngleLoc,
5274 ASTTemplateArgsPtr TemplateArgs,
5275 SourceLocation RAngleLoc,
5276 SourceLocation CCLoc,
5277 bool EnteringContext);
5279 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5280 /// that the parser can use later to reconstruct the given
5281 /// nested-name-specifier.
5283 /// \param SS A nested-name-specifier.
5285 /// \returns A pointer containing all of the information in the
5286 /// nested-name-specifier \p SS.
5287 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5289 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5290 /// the nested-name-specifier structure.
5292 /// \param Annotation The annotation pointer, produced by
5293 /// \c SaveNestedNameSpecifierAnnotation().
5295 /// \param AnnotationRange The source range corresponding to the annotation.
5297 /// \param SS The nested-name-specifier that will be updated with the contents
5298 /// of the annotation pointer.
5299 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5300 SourceRange AnnotationRange,
5303 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5305 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5306 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5307 /// After this method is called, according to [C++ 3.4.3p3], names should be
5308 /// looked up in the declarator-id's scope, until the declarator is parsed and
5309 /// ActOnCXXExitDeclaratorScope is called.
5310 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5311 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5313 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5314 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5315 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5316 /// Used to indicate that names should revert to being looked up in the
5318 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5320 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5321 /// initializer for the declaration 'Dcl'.
5322 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5323 /// static data member of class X, names should be looked up in the scope of
5325 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5327 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5328 /// initializer for the declaration 'Dcl'.
5329 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5331 /// \brief Create a new lambda closure type.
5332 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5333 TypeSourceInfo *Info,
5334 bool KnownDependent,
5335 LambdaCaptureDefault CaptureDefault);
5337 /// \brief Start the definition of a lambda expression.
5338 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5339 SourceRange IntroducerRange,
5340 TypeSourceInfo *MethodType,
5341 SourceLocation EndLoc,
5342 ArrayRef<ParmVarDecl *> Params,
5343 bool IsConstexprSpecified);
5345 /// \brief Endow the lambda scope info with the relevant properties.
5346 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5347 CXXMethodDecl *CallOperator,
5348 SourceRange IntroducerRange,
5349 LambdaCaptureDefault CaptureDefault,
5350 SourceLocation CaptureDefaultLoc,
5351 bool ExplicitParams,
5352 bool ExplicitResultType,
5355 /// \brief Perform initialization analysis of the init-capture and perform
5356 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5357 /// not being used to initialize a reference.
5358 ParsedType actOnLambdaInitCaptureInitialization(
5359 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5360 LambdaCaptureInitKind InitKind, Expr *&Init) {
5361 return ParsedType::make(buildLambdaInitCaptureInitialization(
5362 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5364 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5366 bool DirectInit, Expr *&Init);
5368 /// \brief Create a dummy variable within the declcontext of the lambda's
5369 /// call operator, for name lookup purposes for a lambda init capture.
5371 /// CodeGen handles emission of lambda captures, ignoring these dummy
5372 /// variables appropriately.
5373 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5374 QualType InitCaptureType,
5376 unsigned InitStyle, Expr *Init);
5378 /// \brief Build the implicit field for an init-capture.
5379 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5381 /// \brief Note that we have finished the explicit captures for the
5383 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5385 /// \brief Introduce the lambda parameters into scope.
5386 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5388 /// \brief Deduce a block or lambda's return type based on the return
5389 /// statements present in the body.
5390 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5392 /// ActOnStartOfLambdaDefinition - This is called just before we start
5393 /// parsing the body of a lambda; it analyzes the explicit captures and
5394 /// arguments, and sets up various data-structures for the body of the
5396 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5397 Declarator &ParamInfo, Scope *CurScope);
5399 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5400 /// is invoked to pop the information about the lambda.
5401 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5402 bool IsInstantiation = false);
5404 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5405 /// was successfully completed.
5406 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5409 /// \brief Does copying/destroying the captured variable have side effects?
5410 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5412 /// \brief Diagnose if an explicit lambda capture is unused.
5413 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5415 /// \brief Complete a lambda-expression having processed and attached the
5417 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5418 sema::LambdaScopeInfo *LSI);
5420 /// \brief Define the "body" of the conversion from a lambda object to a
5421 /// function pointer.
5423 /// This routine doesn't actually define a sensible body; rather, it fills
5424 /// in the initialization expression needed to copy the lambda object into
5425 /// the block, and IR generation actually generates the real body of the
5426 /// block pointer conversion.
5427 void DefineImplicitLambdaToFunctionPointerConversion(
5428 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5430 /// \brief Define the "body" of the conversion from a lambda object to a
5433 /// This routine doesn't actually define a sensible body; rather, it fills
5434 /// in the initialization expression needed to copy the lambda object into
5435 /// the block, and IR generation actually generates the real body of the
5436 /// block pointer conversion.
5437 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5438 CXXConversionDecl *Conv);
5440 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5441 SourceLocation ConvLocation,
5442 CXXConversionDecl *Conv,
5445 // ParseObjCStringLiteral - Parse Objective-C string literals.
5446 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5447 ArrayRef<Expr *> Strings);
5449 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5451 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5452 /// numeric literal expression. Type of the expression will be "NSNumber *"
5453 /// or "id" if NSNumber is unavailable.
5454 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5455 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5457 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5459 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5460 /// '@' prefixed parenthesized expression. The type of the expression will
5461 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5462 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5463 /// "const char *" or C structure with attribute 'objc_boxable'.
5464 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5466 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5468 ObjCMethodDecl *getterMethod,
5469 ObjCMethodDecl *setterMethod);
5471 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5472 MutableArrayRef<ObjCDictionaryElement> Elements);
5474 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5475 TypeSourceInfo *EncodedTypeInfo,
5476 SourceLocation RParenLoc);
5477 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5478 CXXConversionDecl *Method,
5479 bool HadMultipleCandidates);
5481 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5482 SourceLocation EncodeLoc,
5483 SourceLocation LParenLoc,
5485 SourceLocation RParenLoc);
5487 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5488 ExprResult ParseObjCSelectorExpression(Selector Sel,
5489 SourceLocation AtLoc,
5490 SourceLocation SelLoc,
5491 SourceLocation LParenLoc,
5492 SourceLocation RParenLoc,
5493 bool WarnMultipleSelectors);
5495 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5496 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5497 SourceLocation AtLoc,
5498 SourceLocation ProtoLoc,
5499 SourceLocation LParenLoc,
5500 SourceLocation ProtoIdLoc,
5501 SourceLocation RParenLoc);
5503 //===--------------------------------------------------------------------===//
5506 Decl *ActOnStartLinkageSpecification(Scope *S,
5507 SourceLocation ExternLoc,
5509 SourceLocation LBraceLoc);
5510 Decl *ActOnFinishLinkageSpecification(Scope *S,
5512 SourceLocation RBraceLoc);
5515 //===--------------------------------------------------------------------===//
5518 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5519 const CXXScopeSpec *SS = nullptr);
5520 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5522 bool ActOnAccessSpecifier(AccessSpecifier Access,
5523 SourceLocation ASLoc,
5524 SourceLocation ColonLoc,
5525 AttributeList *Attrs = nullptr);
5527 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5529 MultiTemplateParamsArg TemplateParameterLists,
5530 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5531 InClassInitStyle InitStyle);
5533 void ActOnStartCXXInClassMemberInitializer();
5534 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5535 SourceLocation EqualLoc,
5538 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5541 IdentifierInfo *MemberOrBase,
5542 ParsedType TemplateTypeTy,
5544 SourceLocation IdLoc,
5545 SourceLocation LParenLoc,
5546 ArrayRef<Expr *> Args,
5547 SourceLocation RParenLoc,
5548 SourceLocation EllipsisLoc);
5550 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5553 IdentifierInfo *MemberOrBase,
5554 ParsedType TemplateTypeTy,
5556 SourceLocation IdLoc,
5558 SourceLocation EllipsisLoc);
5560 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5563 IdentifierInfo *MemberOrBase,
5564 ParsedType TemplateTypeTy,
5566 SourceLocation IdLoc,
5568 SourceLocation EllipsisLoc);
5570 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5572 SourceLocation IdLoc);
5574 MemInitResult BuildBaseInitializer(QualType BaseType,
5575 TypeSourceInfo *BaseTInfo,
5577 CXXRecordDecl *ClassDecl,
5578 SourceLocation EllipsisLoc);
5580 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5582 CXXRecordDecl *ClassDecl);
5584 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5585 CXXCtorInitializer *Initializer);
5587 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5588 ArrayRef<CXXCtorInitializer *> Initializers = None);
5590 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5593 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5594 /// mark all the non-trivial destructors of its members and bases as
5596 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5597 CXXRecordDecl *Record);
5599 /// \brief The list of classes whose vtables have been used within
5600 /// this translation unit, and the source locations at which the
5601 /// first use occurred.
5602 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5604 /// \brief The list of vtables that are required but have not yet been
5606 SmallVector<VTableUse, 16> VTableUses;
5608 /// \brief The set of classes whose vtables have been used within
5609 /// this translation unit, and a bit that will be true if the vtable is
5610 /// required to be emitted (otherwise, it should be emitted only if needed
5611 /// by code generation).
5612 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5614 /// \brief Load any externally-stored vtable uses.
5615 void LoadExternalVTableUses();
5617 /// \brief Note that the vtable for the given class was used at the
5619 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5620 bool DefinitionRequired = false);
5622 /// \brief Mark the exception specifications of all virtual member functions
5623 /// in the given class as needed.
5624 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5625 const CXXRecordDecl *RD);
5627 /// MarkVirtualMembersReferenced - Will mark all members of the given
5628 /// CXXRecordDecl referenced.
5629 void MarkVirtualMembersReferenced(SourceLocation Loc,
5630 const CXXRecordDecl *RD);
5632 /// \brief Define all of the vtables that have been used in this
5633 /// translation unit and reference any virtual members used by those
5636 /// \returns true if any work was done, false otherwise.
5637 bool DefineUsedVTables();
5639 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5641 void ActOnMemInitializers(Decl *ConstructorDecl,
5642 SourceLocation ColonLoc,
5643 ArrayRef<CXXCtorInitializer*> MemInits,
5646 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5647 /// ensure that referenceDLLExportedClassMethods is called some point later
5648 /// when all outer classes of Class are complete.
5649 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5651 void referenceDLLExportedClassMethods();
5653 void propagateDLLAttrToBaseClassTemplate(
5654 CXXRecordDecl *Class, Attr *ClassAttr,
5655 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5656 SourceLocation BaseLoc);
5658 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5659 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5661 SourceLocation LBrac,
5662 SourceLocation RBrac,
5663 AttributeList *AttrList);
5664 void ActOnFinishCXXMemberDecls();
5665 void ActOnFinishCXXNonNestedClass(Decl *D);
5667 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5668 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5669 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5670 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5671 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5672 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5673 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5674 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5675 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5676 CachedTokens &Toks);
5677 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5678 bool IsInsideALocalClassWithinATemplateFunction();
5680 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5682 Expr *AssertMessageExpr,
5683 SourceLocation RParenLoc);
5684 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5686 StringLiteral *AssertMessageExpr,
5687 SourceLocation RParenLoc,
5690 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5691 SourceLocation FriendLoc,
5692 TypeSourceInfo *TSInfo);
5693 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5694 MultiTemplateParamsArg TemplateParams);
5695 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5696 MultiTemplateParamsArg TemplateParams);
5698 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5700 void CheckConstructor(CXXConstructorDecl *Constructor);
5701 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5703 bool CheckDestructor(CXXDestructorDecl *Destructor);
5704 void CheckConversionDeclarator(Declarator &D, QualType &R,
5706 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5707 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5709 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5711 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5712 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5713 const FunctionProtoType *T);
5714 void CheckDelayedMemberExceptionSpecs();
5716 //===--------------------------------------------------------------------===//
5717 // C++ Derived Classes
5720 /// ActOnBaseSpecifier - Parsed a base specifier
5721 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5722 SourceRange SpecifierRange,
5723 bool Virtual, AccessSpecifier Access,
5724 TypeSourceInfo *TInfo,
5725 SourceLocation EllipsisLoc);
5727 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5728 SourceRange SpecifierRange,
5729 ParsedAttributes &Attrs,
5730 bool Virtual, AccessSpecifier Access,
5731 ParsedType basetype,
5732 SourceLocation BaseLoc,
5733 SourceLocation EllipsisLoc);
5735 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5736 MutableArrayRef<CXXBaseSpecifier *> Bases);
5737 void ActOnBaseSpecifiers(Decl *ClassDecl,
5738 MutableArrayRef<CXXBaseSpecifier *> Bases);
5740 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5741 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5742 CXXBasePaths &Paths);
5744 // FIXME: I don't like this name.
5745 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5747 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5748 SourceLocation Loc, SourceRange Range,
5749 CXXCastPath *BasePath = nullptr,
5750 bool IgnoreAccess = false);
5751 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5752 unsigned InaccessibleBaseID,
5753 unsigned AmbigiousBaseConvID,
5754 SourceLocation Loc, SourceRange Range,
5755 DeclarationName Name,
5756 CXXCastPath *BasePath,
5757 bool IgnoreAccess = false);
5759 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5761 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5762 const CXXMethodDecl *Old);
5764 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5765 /// covariant, according to C++ [class.virtual]p5.
5766 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5767 const CXXMethodDecl *Old);
5769 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5770 /// spec is a subset of base spec.
5771 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5772 const CXXMethodDecl *Old);
5774 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5776 /// CheckOverrideControl - Check C++11 override control semantics.
5777 void CheckOverrideControl(NamedDecl *D);
5779 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5780 /// not used in the declaration of an overriding method.
5781 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5783 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5784 /// overrides a virtual member function marked 'final', according to
5785 /// C++11 [class.virtual]p4.
5786 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5787 const CXXMethodDecl *Old);
5790 //===--------------------------------------------------------------------===//
5791 // C++ Access Control
5801 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5802 NamedDecl *PrevMemberDecl,
5803 AccessSpecifier LexicalAS);
5805 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5806 DeclAccessPair FoundDecl);
5807 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5808 DeclAccessPair FoundDecl);
5809 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5810 SourceRange PlacementRange,
5811 CXXRecordDecl *NamingClass,
5812 DeclAccessPair FoundDecl,
5813 bool Diagnose = true);
5814 AccessResult CheckConstructorAccess(SourceLocation Loc,
5815 CXXConstructorDecl *D,
5816 DeclAccessPair FoundDecl,
5817 const InitializedEntity &Entity,
5818 bool IsCopyBindingRefToTemp = false);
5819 AccessResult CheckConstructorAccess(SourceLocation Loc,
5820 CXXConstructorDecl *D,
5821 DeclAccessPair FoundDecl,
5822 const InitializedEntity &Entity,
5823 const PartialDiagnostic &PDiag);
5824 AccessResult CheckDestructorAccess(SourceLocation Loc,
5825 CXXDestructorDecl *Dtor,
5826 const PartialDiagnostic &PDiag,
5827 QualType objectType = QualType());
5828 AccessResult CheckFriendAccess(NamedDecl *D);
5829 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5830 CXXRecordDecl *NamingClass,
5831 DeclAccessPair Found);
5832 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5835 DeclAccessPair FoundDecl);
5836 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5837 DeclAccessPair FoundDecl);
5838 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5839 QualType Base, QualType Derived,
5840 const CXXBasePath &Path,
5842 bool ForceCheck = false,
5843 bool ForceUnprivileged = false);
5844 void CheckLookupAccess(const LookupResult &R);
5845 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5846 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5847 AccessSpecifier access,
5848 QualType objectType);
5850 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5851 const MultiLevelTemplateArgumentList &TemplateArgs);
5852 void PerformDependentDiagnostics(const DeclContext *Pattern,
5853 const MultiLevelTemplateArgumentList &TemplateArgs);
5855 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5857 /// \brief When true, access checking violations are treated as SFINAE
5858 /// failures rather than hard errors.
5859 bool AccessCheckingSFINAE;
5861 enum AbstractDiagSelID {
5865 AbstractVariableType,
5868 AbstractSynthesizedIvarType,
5872 bool isAbstractType(SourceLocation Loc, QualType T);
5873 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5874 TypeDiagnoser &Diagnoser);
5875 template <typename... Ts>
5876 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5877 const Ts &...Args) {
5878 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5879 return RequireNonAbstractType(Loc, T, Diagnoser);
5882 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5884 //===--------------------------------------------------------------------===//
5885 // C++ Overloaded Operators [C++ 13.5]
5888 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5890 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5892 //===--------------------------------------------------------------------===//
5893 // C++ Templates [C++ 14]
5895 void FilterAcceptableTemplateNames(LookupResult &R,
5896 bool AllowFunctionTemplates = true);
5897 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5898 bool AllowFunctionTemplates = true);
5900 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5901 QualType ObjectType, bool EnteringContext,
5902 bool &MemberOfUnknownSpecialization);
5904 TemplateNameKind isTemplateName(Scope *S,
5906 bool hasTemplateKeyword,
5907 UnqualifiedId &Name,
5908 ParsedType ObjectType,
5909 bool EnteringContext,
5910 TemplateTy &Template,
5911 bool &MemberOfUnknownSpecialization);
5913 /// Determine whether a particular identifier might be the name in a C++1z
5914 /// deduction-guide declaration.
5915 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5916 SourceLocation NameLoc,
5917 ParsedTemplateTy *Template = nullptr);
5919 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5920 SourceLocation IILoc,
5922 const CXXScopeSpec *SS,
5923 TemplateTy &SuggestedTemplate,
5924 TemplateNameKind &SuggestedKind);
5926 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5927 NamedDecl *Instantiation,
5928 bool InstantiatedFromMember,
5929 const NamedDecl *Pattern,
5930 const NamedDecl *PatternDef,
5931 TemplateSpecializationKind TSK,
5932 bool Complain = true);
5934 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5935 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5937 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5938 SourceLocation EllipsisLoc,
5939 SourceLocation KeyLoc,
5940 IdentifierInfo *ParamName,
5941 SourceLocation ParamNameLoc,
5942 unsigned Depth, unsigned Position,
5943 SourceLocation EqualLoc,
5944 ParsedType DefaultArg);
5946 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5947 SourceLocation Loc);
5948 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5950 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5953 SourceLocation EqualLoc,
5955 Decl *ActOnTemplateTemplateParameter(Scope *S,
5956 SourceLocation TmpLoc,
5957 TemplateParameterList *Params,
5958 SourceLocation EllipsisLoc,
5959 IdentifierInfo *ParamName,
5960 SourceLocation ParamNameLoc,
5963 SourceLocation EqualLoc,
5964 ParsedTemplateArgument DefaultArg);
5966 TemplateParameterList *
5967 ActOnTemplateParameterList(unsigned Depth,
5968 SourceLocation ExportLoc,
5969 SourceLocation TemplateLoc,
5970 SourceLocation LAngleLoc,
5971 ArrayRef<Decl *> Params,
5972 SourceLocation RAngleLoc,
5973 Expr *RequiresClause);
5975 /// \brief The context in which we are checking a template parameter list.
5976 enum TemplateParamListContext {
5979 TPC_FunctionTemplate,
5980 TPC_ClassTemplateMember,
5981 TPC_FriendClassTemplate,
5982 TPC_FriendFunctionTemplate,
5983 TPC_FriendFunctionTemplateDefinition,
5984 TPC_TypeAliasTemplate
5987 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5988 TemplateParameterList *OldParams,
5989 TemplateParamListContext TPC);
5990 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5991 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5992 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5993 ArrayRef<TemplateParameterList *> ParamLists,
5994 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5996 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5997 SourceLocation KWLoc, CXXScopeSpec &SS,
5998 IdentifierInfo *Name, SourceLocation NameLoc,
5999 AttributeList *Attr,
6000 TemplateParameterList *TemplateParams,
6002 SourceLocation ModulePrivateLoc,
6003 SourceLocation FriendLoc,
6004 unsigned NumOuterTemplateParamLists,
6005 TemplateParameterList **OuterTemplateParamLists,
6006 SkipBodyInfo *SkipBody = nullptr);
6008 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6010 SourceLocation Loc);
6012 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6013 TemplateArgumentListInfo &Out);
6015 void NoteAllFoundTemplates(TemplateName Name);
6017 QualType CheckTemplateIdType(TemplateName Template,
6018 SourceLocation TemplateLoc,
6019 TemplateArgumentListInfo &TemplateArgs);
6022 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6023 TemplateTy Template, IdentifierInfo *TemplateII,
6024 SourceLocation TemplateIILoc,
6025 SourceLocation LAngleLoc,
6026 ASTTemplateArgsPtr TemplateArgs,
6027 SourceLocation RAngleLoc,
6028 bool IsCtorOrDtorName = false,
6029 bool IsClassName = false);
6031 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6032 /// such as \c class T::template apply<U>.
6033 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6034 TypeSpecifierType TagSpec,
6035 SourceLocation TagLoc,
6037 SourceLocation TemplateKWLoc,
6038 TemplateTy TemplateD,
6039 SourceLocation TemplateLoc,
6040 SourceLocation LAngleLoc,
6041 ASTTemplateArgsPtr TemplateArgsIn,
6042 SourceLocation RAngleLoc);
6044 DeclResult ActOnVarTemplateSpecialization(
6045 Scope *S, Declarator &D, TypeSourceInfo *DI,
6046 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6047 StorageClass SC, bool IsPartialSpecialization);
6049 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6050 SourceLocation TemplateLoc,
6051 SourceLocation TemplateNameLoc,
6052 const TemplateArgumentListInfo &TemplateArgs);
6054 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6055 const DeclarationNameInfo &NameInfo,
6056 VarTemplateDecl *Template,
6057 SourceLocation TemplateLoc,
6058 const TemplateArgumentListInfo *TemplateArgs);
6060 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6061 SourceLocation TemplateKWLoc,
6064 const TemplateArgumentListInfo *TemplateArgs);
6066 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6067 SourceLocation TemplateKWLoc,
6068 const DeclarationNameInfo &NameInfo,
6069 const TemplateArgumentListInfo *TemplateArgs);
6071 TemplateNameKind ActOnDependentTemplateName(
6072 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6073 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6074 TemplateTy &Template, bool AllowInjectedClassName = false);
6077 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6078 SourceLocation KWLoc,
6079 SourceLocation ModulePrivateLoc,
6080 TemplateIdAnnotation &TemplateId,
6081 AttributeList *Attr,
6082 MultiTemplateParamsArg TemplateParameterLists,
6083 SkipBodyInfo *SkipBody = nullptr);
6085 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6086 TemplateDecl *PrimaryTemplate,
6087 unsigned NumExplicitArgs,
6088 ArrayRef<TemplateArgument> Args);
6089 void CheckTemplatePartialSpecialization(
6090 ClassTemplatePartialSpecializationDecl *Partial);
6091 void CheckTemplatePartialSpecialization(
6092 VarTemplatePartialSpecializationDecl *Partial);
6094 Decl *ActOnTemplateDeclarator(Scope *S,
6095 MultiTemplateParamsArg TemplateParameterLists,
6099 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6100 TemplateSpecializationKind NewTSK,
6101 NamedDecl *PrevDecl,
6102 TemplateSpecializationKind PrevTSK,
6103 SourceLocation PrevPtOfInstantiation,
6106 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6107 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6108 LookupResult &Previous);
6110 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6111 TemplateArgumentListInfo *ExplicitTemplateArgs,
6112 LookupResult &Previous);
6113 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6114 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6117 ActOnExplicitInstantiation(Scope *S,
6118 SourceLocation ExternLoc,
6119 SourceLocation TemplateLoc,
6121 SourceLocation KWLoc,
6122 const CXXScopeSpec &SS,
6123 TemplateTy Template,
6124 SourceLocation TemplateNameLoc,
6125 SourceLocation LAngleLoc,
6126 ASTTemplateArgsPtr TemplateArgs,
6127 SourceLocation RAngleLoc,
6128 AttributeList *Attr);
6131 ActOnExplicitInstantiation(Scope *S,
6132 SourceLocation ExternLoc,
6133 SourceLocation TemplateLoc,
6135 SourceLocation KWLoc,
6137 IdentifierInfo *Name,
6138 SourceLocation NameLoc,
6139 AttributeList *Attr);
6141 DeclResult ActOnExplicitInstantiation(Scope *S,
6142 SourceLocation ExternLoc,
6143 SourceLocation TemplateLoc,
6147 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6148 SourceLocation TemplateLoc,
6149 SourceLocation RAngleLoc,
6151 SmallVectorImpl<TemplateArgument>
6153 bool &HasDefaultArg);
6155 /// \brief Specifies the context in which a particular template
6156 /// argument is being checked.
6157 enum CheckTemplateArgumentKind {
6158 /// \brief The template argument was specified in the code or was
6159 /// instantiated with some deduced template arguments.
6162 /// \brief The template argument was deduced via template argument
6166 /// \brief The template argument was deduced from an array bound
6167 /// via template argument deduction.
6168 CTAK_DeducedFromArrayBound
6171 bool CheckTemplateArgument(NamedDecl *Param,
6172 TemplateArgumentLoc &Arg,
6173 NamedDecl *Template,
6174 SourceLocation TemplateLoc,
6175 SourceLocation RAngleLoc,
6176 unsigned ArgumentPackIndex,
6177 SmallVectorImpl<TemplateArgument> &Converted,
6178 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6180 /// \brief Check that the given template arguments can be be provided to
6181 /// the given template, converting the arguments along the way.
6183 /// \param Template The template to which the template arguments are being
6186 /// \param TemplateLoc The location of the template name in the source.
6188 /// \param TemplateArgs The list of template arguments. If the template is
6189 /// a template template parameter, this function may extend the set of
6190 /// template arguments to also include substituted, defaulted template
6193 /// \param PartialTemplateArgs True if the list of template arguments is
6194 /// intentionally partial, e.g., because we're checking just the initial
6195 /// set of template arguments.
6197 /// \param Converted Will receive the converted, canonicalized template
6200 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6201 /// contain the converted forms of the template arguments as written.
6202 /// Otherwise, \p TemplateArgs will not be modified.
6204 /// \returns true if an error occurred, false otherwise.
6205 bool CheckTemplateArgumentList(TemplateDecl *Template,
6206 SourceLocation TemplateLoc,
6207 TemplateArgumentListInfo &TemplateArgs,
6208 bool PartialTemplateArgs,
6209 SmallVectorImpl<TemplateArgument> &Converted,
6210 bool UpdateArgsWithConversions = true);
6212 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6213 TemplateArgumentLoc &Arg,
6214 SmallVectorImpl<TemplateArgument> &Converted);
6216 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6217 TypeSourceInfo *Arg);
6218 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6219 QualType InstantiatedParamType, Expr *Arg,
6220 TemplateArgument &Converted,
6221 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6222 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6223 TemplateArgumentLoc &Arg,
6224 unsigned ArgumentPackIndex);
6227 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6229 SourceLocation Loc);
6231 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6232 SourceLocation Loc);
6234 /// \brief Enumeration describing how template parameter lists are compared
6236 enum TemplateParameterListEqualKind {
6237 /// \brief We are matching the template parameter lists of two templates
6238 /// that might be redeclarations.
6241 /// template<typename T> struct X;
6242 /// template<typename T> struct X;
6246 /// \brief We are matching the template parameter lists of two template
6247 /// template parameters as part of matching the template parameter lists
6248 /// of two templates that might be redeclarations.
6251 /// template<template<int I> class TT> struct X;
6252 /// template<template<int Value> class Other> struct X;
6254 TPL_TemplateTemplateParmMatch,
6256 /// \brief We are matching the template parameter lists of a template
6257 /// template argument against the template parameter lists of a template
6258 /// template parameter.
6261 /// template<template<int Value> class Metafun> struct X;
6262 /// template<int Value> struct integer_c;
6263 /// X<integer_c> xic;
6265 TPL_TemplateTemplateArgumentMatch
6268 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6269 TemplateParameterList *Old,
6271 TemplateParameterListEqualKind Kind,
6272 SourceLocation TemplateArgLoc
6273 = SourceLocation());
6275 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6277 /// \brief Called when the parser has parsed a C++ typename
6278 /// specifier, e.g., "typename T::type".
6280 /// \param S The scope in which this typename type occurs.
6281 /// \param TypenameLoc the location of the 'typename' keyword
6282 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6283 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6284 /// \param IdLoc the location of the identifier.
6286 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6287 const CXXScopeSpec &SS, const IdentifierInfo &II,
6288 SourceLocation IdLoc);
6290 /// \brief Called when the parser has parsed a C++ typename
6291 /// specifier that ends in a template-id, e.g.,
6292 /// "typename MetaFun::template apply<T1, T2>".
6294 /// \param S The scope in which this typename type occurs.
6295 /// \param TypenameLoc the location of the 'typename' keyword
6296 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6297 /// \param TemplateLoc the location of the 'template' keyword, if any.
6298 /// \param TemplateName The template name.
6299 /// \param TemplateII The identifier used to name the template.
6300 /// \param TemplateIILoc The location of the template name.
6301 /// \param LAngleLoc The location of the opening angle bracket ('<').
6302 /// \param TemplateArgs The template arguments.
6303 /// \param RAngleLoc The location of the closing angle bracket ('>').
6305 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6306 const CXXScopeSpec &SS,
6307 SourceLocation TemplateLoc,
6308 TemplateTy TemplateName,
6309 IdentifierInfo *TemplateII,
6310 SourceLocation TemplateIILoc,
6311 SourceLocation LAngleLoc,
6312 ASTTemplateArgsPtr TemplateArgs,
6313 SourceLocation RAngleLoc);
6315 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6316 SourceLocation KeywordLoc,
6317 NestedNameSpecifierLoc QualifierLoc,
6318 const IdentifierInfo &II,
6319 SourceLocation IILoc);
6321 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6323 DeclarationName Name);
6324 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6326 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6327 bool RebuildTemplateParamsInCurrentInstantiation(
6328 TemplateParameterList *Params);
6331 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6332 const TemplateArgumentList &Args);
6335 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6336 const TemplateArgument *Args,
6339 //===--------------------------------------------------------------------===//
6340 // C++ Variadic Templates (C++0x [temp.variadic])
6341 //===--------------------------------------------------------------------===//
6343 /// Determine whether an unexpanded parameter pack might be permitted in this
6344 /// location. Useful for error recovery.
6345 bool isUnexpandedParameterPackPermitted();
6347 /// \brief The context in which an unexpanded parameter pack is
6348 /// being diagnosed.
6350 /// Note that the values of this enumeration line up with the first
6351 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6352 enum UnexpandedParameterPackContext {
6353 /// \brief An arbitrary expression.
6354 UPPC_Expression = 0,
6356 /// \brief The base type of a class type.
6359 /// \brief The type of an arbitrary declaration.
6360 UPPC_DeclarationType,
6362 /// \brief The type of a data member.
6363 UPPC_DataMemberType,
6365 /// \brief The size of a bit-field.
6368 /// \brief The expression in a static assertion.
6369 UPPC_StaticAssertExpression,
6371 /// \brief The fixed underlying type of an enumeration.
6372 UPPC_FixedUnderlyingType,
6374 /// \brief The enumerator value.
6375 UPPC_EnumeratorValue,
6377 /// \brief A using declaration.
6378 UPPC_UsingDeclaration,
6380 /// \brief A friend declaration.
6381 UPPC_FriendDeclaration,
6383 /// \brief A declaration qualifier.
6384 UPPC_DeclarationQualifier,
6386 /// \brief An initializer.
6389 /// \brief A default argument.
6390 UPPC_DefaultArgument,
6392 /// \brief The type of a non-type template parameter.
6393 UPPC_NonTypeTemplateParameterType,
6395 /// \brief The type of an exception.
6398 /// \brief Partial specialization.
6399 UPPC_PartialSpecialization,
6401 /// \brief Microsoft __if_exists.
6404 /// \brief Microsoft __if_not_exists.
6407 /// \brief Lambda expression.
6410 /// \brief Block expression,
6414 /// \brief Diagnose unexpanded parameter packs.
6416 /// \param Loc The location at which we should emit the diagnostic.
6418 /// \param UPPC The context in which we are diagnosing unexpanded
6419 /// parameter packs.
6421 /// \param Unexpanded the set of unexpanded parameter packs.
6423 /// \returns true if an error occurred, false otherwise.
6424 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6425 UnexpandedParameterPackContext UPPC,
6426 ArrayRef<UnexpandedParameterPack> Unexpanded);
6428 /// \brief If the given type contains an unexpanded parameter pack,
6429 /// diagnose the error.
6431 /// \param Loc The source location where a diagnostc should be emitted.
6433 /// \param T The type that is being checked for unexpanded parameter
6436 /// \returns true if an error occurred, false otherwise.
6437 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6438 UnexpandedParameterPackContext UPPC);
6440 /// \brief If the given expression contains an unexpanded parameter
6441 /// pack, diagnose the error.
6443 /// \param E The expression that is being checked for unexpanded
6444 /// parameter packs.
6446 /// \returns true if an error occurred, false otherwise.
6447 bool DiagnoseUnexpandedParameterPack(Expr *E,
6448 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6450 /// \brief If the given nested-name-specifier contains an unexpanded
6451 /// parameter pack, diagnose the error.
6453 /// \param SS The nested-name-specifier that is being checked for
6454 /// unexpanded parameter packs.
6456 /// \returns true if an error occurred, false otherwise.
6457 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6458 UnexpandedParameterPackContext UPPC);
6460 /// \brief If the given name contains an unexpanded parameter pack,
6461 /// diagnose the error.
6463 /// \param NameInfo The name (with source location information) that
6464 /// is being checked for unexpanded parameter packs.
6466 /// \returns true if an error occurred, false otherwise.
6467 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6468 UnexpandedParameterPackContext UPPC);
6470 /// \brief If the given template name contains an unexpanded parameter pack,
6471 /// diagnose the error.
6473 /// \param Loc The location of the template name.
6475 /// \param Template The template name that is being checked for unexpanded
6476 /// parameter packs.
6478 /// \returns true if an error occurred, false otherwise.
6479 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6480 TemplateName Template,
6481 UnexpandedParameterPackContext UPPC);
6483 /// \brief If the given template argument contains an unexpanded parameter
6484 /// pack, diagnose the error.
6486 /// \param Arg The template argument that is being checked for unexpanded
6487 /// parameter packs.
6489 /// \returns true if an error occurred, false otherwise.
6490 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6491 UnexpandedParameterPackContext UPPC);
6493 /// \brief Collect the set of unexpanded parameter packs within the given
6494 /// template argument.
6496 /// \param Arg The template argument that will be traversed to find
6497 /// unexpanded parameter packs.
6498 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6499 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6501 /// \brief Collect the set of unexpanded parameter packs within the given
6502 /// template argument.
6504 /// \param Arg The template argument that will be traversed to find
6505 /// unexpanded parameter packs.
6506 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6507 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6509 /// \brief Collect the set of unexpanded parameter packs within the given
6512 /// \param T The type that will be traversed to find
6513 /// unexpanded parameter packs.
6514 void collectUnexpandedParameterPacks(QualType T,
6515 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6517 /// \brief Collect the set of unexpanded parameter packs within the given
6520 /// \param TL The type that will be traversed to find
6521 /// unexpanded parameter packs.
6522 void collectUnexpandedParameterPacks(TypeLoc TL,
6523 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6525 /// \brief Collect the set of unexpanded parameter packs within the given
6526 /// nested-name-specifier.
6528 /// \param NNS The nested-name-specifier that will be traversed to find
6529 /// unexpanded parameter packs.
6530 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6531 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6533 /// \brief Collect the set of unexpanded parameter packs within the given
6536 /// \param NameInfo The name that will be traversed to find
6537 /// unexpanded parameter packs.
6538 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6539 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6541 /// \brief Invoked when parsing a template argument followed by an
6542 /// ellipsis, which creates a pack expansion.
6544 /// \param Arg The template argument preceding the ellipsis, which
6545 /// may already be invalid.
6547 /// \param EllipsisLoc The location of the ellipsis.
6548 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6549 SourceLocation EllipsisLoc);
6551 /// \brief Invoked when parsing a type followed by an ellipsis, which
6552 /// creates a pack expansion.
6554 /// \param Type The type preceding the ellipsis, which will become
6555 /// the pattern of the pack expansion.
6557 /// \param EllipsisLoc The location of the ellipsis.
6558 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6560 /// \brief Construct a pack expansion type from the pattern of the pack
6562 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6563 SourceLocation EllipsisLoc,
6564 Optional<unsigned> NumExpansions);
6566 /// \brief Construct a pack expansion type from the pattern of the pack
6568 QualType CheckPackExpansion(QualType Pattern,
6569 SourceRange PatternRange,
6570 SourceLocation EllipsisLoc,
6571 Optional<unsigned> NumExpansions);
6573 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6574 /// creates a pack expansion.
6576 /// \param Pattern The expression preceding the ellipsis, which will become
6577 /// the pattern of the pack expansion.
6579 /// \param EllipsisLoc The location of the ellipsis.
6580 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6582 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6583 /// creates a pack expansion.
6585 /// \param Pattern The expression preceding the ellipsis, which will become
6586 /// the pattern of the pack expansion.
6588 /// \param EllipsisLoc The location of the ellipsis.
6589 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6590 Optional<unsigned> NumExpansions);
6592 /// \brief Determine whether we could expand a pack expansion with the
6593 /// given set of parameter packs into separate arguments by repeatedly
6594 /// transforming the pattern.
6596 /// \param EllipsisLoc The location of the ellipsis that identifies the
6599 /// \param PatternRange The source range that covers the entire pattern of
6600 /// the pack expansion.
6602 /// \param Unexpanded The set of unexpanded parameter packs within the
6605 /// \param ShouldExpand Will be set to \c true if the transformer should
6606 /// expand the corresponding pack expansions into separate arguments. When
6607 /// set, \c NumExpansions must also be set.
6609 /// \param RetainExpansion Whether the caller should add an unexpanded
6610 /// pack expansion after all of the expanded arguments. This is used
6611 /// when extending explicitly-specified template argument packs per
6612 /// C++0x [temp.arg.explicit]p9.
6614 /// \param NumExpansions The number of separate arguments that will be in
6615 /// the expanded form of the corresponding pack expansion. This is both an
6616 /// input and an output parameter, which can be set by the caller if the
6617 /// number of expansions is known a priori (e.g., due to a prior substitution)
6618 /// and will be set by the callee when the number of expansions is known.
6619 /// The callee must set this value when \c ShouldExpand is \c true; it may
6620 /// set this value in other cases.
6622 /// \returns true if an error occurred (e.g., because the parameter packs
6623 /// are to be instantiated with arguments of different lengths), false
6624 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6626 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6627 SourceRange PatternRange,
6628 ArrayRef<UnexpandedParameterPack> Unexpanded,
6629 const MultiLevelTemplateArgumentList &TemplateArgs,
6631 bool &RetainExpansion,
6632 Optional<unsigned> &NumExpansions);
6634 /// \brief Determine the number of arguments in the given pack expansion
6637 /// This routine assumes that the number of arguments in the expansion is
6638 /// consistent across all of the unexpanded parameter packs in its pattern.
6640 /// Returns an empty Optional if the type can't be expanded.
6641 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6642 const MultiLevelTemplateArgumentList &TemplateArgs);
6644 /// \brief Determine whether the given declarator contains any unexpanded
6645 /// parameter packs.
6647 /// This routine is used by the parser to disambiguate function declarators
6648 /// with an ellipsis prior to the ')', e.g.,
6654 /// To determine whether we have an (unnamed) function parameter pack or
6655 /// a variadic function.
6657 /// \returns true if the declarator contains any unexpanded parameter packs,
6658 /// false otherwise.
6659 bool containsUnexpandedParameterPacks(Declarator &D);
6661 /// \brief Returns the pattern of the pack expansion for a template argument.
6663 /// \param OrigLoc The template argument to expand.
6665 /// \param Ellipsis Will be set to the location of the ellipsis.
6667 /// \param NumExpansions Will be set to the number of expansions that will
6668 /// be generated from this pack expansion, if known a priori.
6669 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6670 TemplateArgumentLoc OrigLoc,
6671 SourceLocation &Ellipsis,
6672 Optional<unsigned> &NumExpansions) const;
6674 /// Given a template argument that contains an unexpanded parameter pack, but
6675 /// which has already been substituted, attempt to determine the number of
6676 /// elements that will be produced once this argument is fully-expanded.
6678 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6679 /// avoid actually expanding the pack where possible.
6680 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6682 //===--------------------------------------------------------------------===//
6683 // C++ Template Argument Deduction (C++ [temp.deduct])
6684 //===--------------------------------------------------------------------===//
6686 /// Adjust the type \p ArgFunctionType to match the calling convention,
6687 /// noreturn, and optionally the exception specification of \p FunctionType.
6688 /// Deduction often wants to ignore these properties when matching function
6690 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6691 bool AdjustExceptionSpec = false);
6693 /// \brief Describes the result of template argument deduction.
6695 /// The TemplateDeductionResult enumeration describes the result of
6696 /// template argument deduction, as returned from
6697 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6698 /// structure provides additional information about the results of
6699 /// template argument deduction, e.g., the deduced template argument
6700 /// list (if successful) or the specific template parameters or
6701 /// deduced arguments that were involved in the failure.
6702 enum TemplateDeductionResult {
6703 /// \brief Template argument deduction was successful.
6705 /// \brief The declaration was invalid; do nothing.
6707 /// \brief Template argument deduction exceeded the maximum template
6708 /// instantiation depth (which has already been diagnosed).
6709 TDK_InstantiationDepth,
6710 /// \brief Template argument deduction did not deduce a value
6711 /// for every template parameter.
6713 /// \brief Template argument deduction produced inconsistent
6714 /// deduced values for the given template parameter.
6716 /// \brief Template argument deduction failed due to inconsistent
6717 /// cv-qualifiers on a template parameter type that would
6718 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6719 /// but were given a non-const "X".
6721 /// \brief Substitution of the deduced template argument values
6722 /// resulted in an error.
6723 TDK_SubstitutionFailure,
6724 /// \brief After substituting deduced template arguments, a dependent
6725 /// parameter type did not match the corresponding argument.
6726 TDK_DeducedMismatch,
6727 /// \brief After substituting deduced template arguments, an element of
6728 /// a dependent parameter type did not match the corresponding element
6729 /// of the corresponding argument (when deducing from an initializer list).
6730 TDK_DeducedMismatchNested,
6731 /// \brief A non-depnedent component of the parameter did not match the
6732 /// corresponding component of the argument.
6733 TDK_NonDeducedMismatch,
6734 /// \brief When performing template argument deduction for a function
6735 /// template, there were too many call arguments.
6736 TDK_TooManyArguments,
6737 /// \brief When performing template argument deduction for a function
6738 /// template, there were too few call arguments.
6739 TDK_TooFewArguments,
6740 /// \brief The explicitly-specified template arguments were not valid
6741 /// template arguments for the given template.
6742 TDK_InvalidExplicitArguments,
6743 /// \brief Checking non-dependent argument conversions failed.
6744 TDK_NonDependentConversionFailure,
6745 /// \brief Deduction failed; that's all we know.
6746 TDK_MiscellaneousDeductionFailure,
6747 /// \brief CUDA Target attributes do not match.
6748 TDK_CUDATargetMismatch
6751 TemplateDeductionResult
6752 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6753 const TemplateArgumentList &TemplateArgs,
6754 sema::TemplateDeductionInfo &Info);
6756 TemplateDeductionResult
6757 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6758 const TemplateArgumentList &TemplateArgs,
6759 sema::TemplateDeductionInfo &Info);
6761 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6762 FunctionTemplateDecl *FunctionTemplate,
6763 TemplateArgumentListInfo &ExplicitTemplateArgs,
6764 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6765 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6766 sema::TemplateDeductionInfo &Info);
6768 /// brief A function argument from which we performed template argument
6769 // deduction for a call.
6770 struct OriginalCallArg {
6771 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6772 unsigned ArgIdx, QualType OriginalArgType)
6773 : OriginalParamType(OriginalParamType),
6774 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6775 OriginalArgType(OriginalArgType) {}
6777 QualType OriginalParamType;
6778 bool DecomposedParam;
6780 QualType OriginalArgType;
6783 TemplateDeductionResult FinishTemplateArgumentDeduction(
6784 FunctionTemplateDecl *FunctionTemplate,
6785 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6786 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6787 sema::TemplateDeductionInfo &Info,
6788 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6789 bool PartialOverloading = false,
6790 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6792 TemplateDeductionResult DeduceTemplateArguments(
6793 FunctionTemplateDecl *FunctionTemplate,
6794 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6795 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6796 bool PartialOverloading,
6797 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6799 TemplateDeductionResult
6800 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6801 TemplateArgumentListInfo *ExplicitTemplateArgs,
6802 QualType ArgFunctionType,
6803 FunctionDecl *&Specialization,
6804 sema::TemplateDeductionInfo &Info,
6805 bool IsAddressOfFunction = false);
6807 TemplateDeductionResult
6808 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6810 CXXConversionDecl *&Specialization,
6811 sema::TemplateDeductionInfo &Info);
6813 TemplateDeductionResult
6814 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6815 TemplateArgumentListInfo *ExplicitTemplateArgs,
6816 FunctionDecl *&Specialization,
6817 sema::TemplateDeductionInfo &Info,
6818 bool IsAddressOfFunction = false);
6820 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6821 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6822 /// \brief Substitute Replacement for auto in TypeWithAuto
6823 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6824 QualType Replacement);
6825 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6826 /// \p Replacement. This does not retain any \c auto type sugar.
6827 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6829 /// \brief Result type of DeduceAutoType.
6830 enum DeduceAutoResult {
6833 DAR_FailedAlreadyDiagnosed
6837 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6838 Optional<unsigned> DependentDeductionDepth = None);
6840 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6841 Optional<unsigned> DependentDeductionDepth = None);
6842 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6843 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6844 bool Diagnose = true);
6846 /// \brief Declare implicit deduction guides for a class template if we've
6847 /// not already done so.
6848 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6849 SourceLocation Loc);
6851 QualType DeduceTemplateSpecializationFromInitializer(
6852 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6853 const InitializationKind &Kind, MultiExprArg Init);
6855 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6856 QualType Type, TypeSourceInfo *TSI,
6857 SourceRange Range, bool DirectInit,
6860 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6862 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6863 SourceLocation ReturnLoc,
6864 Expr *&RetExpr, AutoType *AT);
6866 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6867 FunctionTemplateDecl *FT2,
6869 TemplatePartialOrderingContext TPOC,
6870 unsigned NumCallArguments1,
6871 unsigned NumCallArguments2);
6872 UnresolvedSetIterator
6873 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6874 TemplateSpecCandidateSet &FailedCandidates,
6876 const PartialDiagnostic &NoneDiag,
6877 const PartialDiagnostic &AmbigDiag,
6878 const PartialDiagnostic &CandidateDiag,
6879 bool Complain = true, QualType TargetType = QualType());
6881 ClassTemplatePartialSpecializationDecl *
6882 getMoreSpecializedPartialSpecialization(
6883 ClassTemplatePartialSpecializationDecl *PS1,
6884 ClassTemplatePartialSpecializationDecl *PS2,
6885 SourceLocation Loc);
6887 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6888 sema::TemplateDeductionInfo &Info);
6890 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6891 VarTemplatePartialSpecializationDecl *PS1,
6892 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6894 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6895 sema::TemplateDeductionInfo &Info);
6897 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6898 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6900 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6903 llvm::SmallBitVector &Used);
6904 void MarkDeducedTemplateParameters(
6905 const FunctionTemplateDecl *FunctionTemplate,
6906 llvm::SmallBitVector &Deduced) {
6907 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6909 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6910 const FunctionTemplateDecl *FunctionTemplate,
6911 llvm::SmallBitVector &Deduced);
6913 //===--------------------------------------------------------------------===//
6914 // C++ Template Instantiation
6917 MultiLevelTemplateArgumentList
6918 getTemplateInstantiationArgs(NamedDecl *D,
6919 const TemplateArgumentList *Innermost = nullptr,
6920 bool RelativeToPrimary = false,
6921 const FunctionDecl *Pattern = nullptr);
6923 /// A context in which code is being synthesized (where a source location
6924 /// alone is not sufficient to identify the context). This covers template
6925 /// instantiation and various forms of implicitly-generated functions.
6926 struct CodeSynthesisContext {
6927 /// \brief The kind of template instantiation we are performing
6928 enum SynthesisKind {
6929 /// We are instantiating a template declaration. The entity is
6930 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6931 TemplateInstantiation,
6933 /// We are instantiating a default argument for a template
6934 /// parameter. The Entity is the template parameter whose argument is
6935 /// being instantiated, the Template is the template, and the
6936 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6938 DefaultTemplateArgumentInstantiation,
6940 /// We are instantiating a default argument for a function.
6941 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6942 /// provides the template arguments as specified.
6943 DefaultFunctionArgumentInstantiation,
6945 /// We are substituting explicit template arguments provided for
6946 /// a function template. The entity is a FunctionTemplateDecl.
6947 ExplicitTemplateArgumentSubstitution,
6949 /// We are substituting template argument determined as part of
6950 /// template argument deduction for either a class template
6951 /// partial specialization or a function template. The
6952 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6954 DeducedTemplateArgumentSubstitution,
6956 /// We are substituting prior template arguments into a new
6957 /// template parameter. The template parameter itself is either a
6958 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6959 PriorTemplateArgumentSubstitution,
6961 /// We are checking the validity of a default template argument that
6962 /// has been used when naming a template-id.
6963 DefaultTemplateArgumentChecking,
6965 /// We are instantiating the exception specification for a function
6966 /// template which was deferred until it was needed.
6967 ExceptionSpecInstantiation,
6969 /// We are declaring an implicit special member function.
6970 DeclaringSpecialMember,
6973 /// \brief Was the enclosing context a non-instantiation SFINAE context?
6974 bool SavedInNonInstantiationSFINAEContext;
6976 /// \brief The point of instantiation or synthesis within the source code.
6977 SourceLocation PointOfInstantiation;
6979 /// \brief The entity that is being synthesized.
6982 /// \brief The template (or partial specialization) in which we are
6983 /// performing the instantiation, for substitutions of prior template
6985 NamedDecl *Template;
6987 /// \brief The list of template arguments we are substituting, if they
6988 /// are not part of the entity.
6989 const TemplateArgument *TemplateArgs;
6991 // FIXME: Wrap this union around more members, or perhaps store the
6992 // kind-specific members in the RAII object owning the context.
6994 /// \brief The number of template arguments in TemplateArgs.
6995 unsigned NumTemplateArgs;
6997 /// \brief The special member being declared or defined.
6998 CXXSpecialMember SpecialMember;
7001 ArrayRef<TemplateArgument> template_arguments() const {
7002 assert(Kind != DeclaringSpecialMember);
7003 return {TemplateArgs, NumTemplateArgs};
7006 /// \brief The template deduction info object associated with the
7007 /// substitution or checking of explicit or deduced template arguments.
7008 sema::TemplateDeductionInfo *DeductionInfo;
7010 /// \brief The source range that covers the construct that cause
7011 /// the instantiation, e.g., the template-id that causes a class
7012 /// template instantiation.
7013 SourceRange InstantiationRange;
7015 CodeSynthesisContext()
7016 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7017 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7019 /// \brief Determines whether this template is an actual instantiation
7020 /// that should be counted toward the maximum instantiation depth.
7021 bool isInstantiationRecord() const;
7024 /// \brief List of active code synthesis contexts.
7026 /// This vector is treated as a stack. As synthesis of one entity requires
7027 /// synthesis of another, additional contexts are pushed onto the stack.
7028 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7030 /// Specializations whose definitions are currently being instantiated.
7031 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7033 /// Non-dependent types used in templates that have already been instantiated
7034 /// by some template instantiation.
7035 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7037 /// \brief Extra modules inspected when performing a lookup during a template
7038 /// instantiation. Computed lazily.
7039 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7041 /// \brief Cache of additional modules that should be used for name lookup
7042 /// within the current template instantiation. Computed lazily; use
7043 /// getLookupModules() to get a complete set.
7044 llvm::DenseSet<Module*> LookupModulesCache;
7046 /// \brief Get the set of additional modules that should be checked during
7047 /// name lookup. A module and its imports become visible when instanting a
7048 /// template defined within it.
7049 llvm::DenseSet<Module*> &getLookupModules();
7051 /// \brief Map from the most recent declaration of a namespace to the most
7052 /// recent visible declaration of that namespace.
7053 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7055 /// \brief Whether we are in a SFINAE context that is not associated with
7056 /// template instantiation.
7058 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7059 /// of a template instantiation or template argument deduction.
7060 bool InNonInstantiationSFINAEContext;
7062 /// \brief The number of \p CodeSynthesisContexts that are not template
7063 /// instantiations and, therefore, should not be counted as part of the
7064 /// instantiation depth.
7066 /// When the instantiation depth reaches the user-configurable limit
7067 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7068 // FIXME: Should we have a similar limit for other forms of synthesis?
7069 unsigned NonInstantiationEntries;
7071 /// \brief The depth of the context stack at the point when the most recent
7072 /// error or warning was produced.
7074 /// This value is used to suppress printing of redundant context stacks
7075 /// when there are multiple errors or warnings in the same instantiation.
7076 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7077 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7079 /// \brief The current index into pack expansion arguments that will be
7080 /// used for substitution of parameter packs.
7082 /// The pack expansion index will be -1 to indicate that parameter packs
7083 /// should be instantiated as themselves. Otherwise, the index specifies
7084 /// which argument within the parameter pack will be used for substitution.
7085 int ArgumentPackSubstitutionIndex;
7087 /// \brief RAII object used to change the argument pack substitution index
7088 /// within a \c Sema object.
7090 /// See \c ArgumentPackSubstitutionIndex for more information.
7091 class ArgumentPackSubstitutionIndexRAII {
7093 int OldSubstitutionIndex;
7096 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7097 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7098 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7101 ~ArgumentPackSubstitutionIndexRAII() {
7102 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7106 friend class ArgumentPackSubstitutionRAII;
7108 /// \brief For each declaration that involved template argument deduction, the
7109 /// set of diagnostics that were suppressed during that template argument
7112 /// FIXME: Serialize this structure to the AST file.
7113 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7114 SuppressedDiagnosticsMap;
7115 SuppressedDiagnosticsMap SuppressedDiagnostics;
7117 /// \brief A stack object to be created when performing template
7120 /// Construction of an object of type \c InstantiatingTemplate
7121 /// pushes the current instantiation onto the stack of active
7122 /// instantiations. If the size of this stack exceeds the maximum
7123 /// number of recursive template instantiations, construction
7124 /// produces an error and evaluates true.
7126 /// Destruction of this object will pop the named instantiation off
7128 struct InstantiatingTemplate {
7129 /// \brief Note that we are instantiating a class template,
7130 /// function template, variable template, alias template,
7131 /// or a member thereof.
7132 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7134 SourceRange InstantiationRange = SourceRange());
7136 struct ExceptionSpecification {};
7137 /// \brief Note that we are instantiating an exception specification
7138 /// of a function template.
7139 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7140 FunctionDecl *Entity, ExceptionSpecification,
7141 SourceRange InstantiationRange = SourceRange());
7143 /// \brief Note that we are instantiating a default argument in a
7145 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7146 TemplateParameter Param, TemplateDecl *Template,
7147 ArrayRef<TemplateArgument> TemplateArgs,
7148 SourceRange InstantiationRange = SourceRange());
7150 /// \brief Note that we are substituting either explicitly-specified or
7151 /// deduced template arguments during function template argument deduction.
7152 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7153 FunctionTemplateDecl *FunctionTemplate,
7154 ArrayRef<TemplateArgument> TemplateArgs,
7155 CodeSynthesisContext::SynthesisKind Kind,
7156 sema::TemplateDeductionInfo &DeductionInfo,
7157 SourceRange InstantiationRange = SourceRange());
7159 /// \brief Note that we are instantiating as part of template
7160 /// argument deduction for a class template declaration.
7161 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7162 TemplateDecl *Template,
7163 ArrayRef<TemplateArgument> TemplateArgs,
7164 sema::TemplateDeductionInfo &DeductionInfo,
7165 SourceRange InstantiationRange = SourceRange());
7167 /// \brief Note that we are instantiating as part of template
7168 /// argument deduction for a class template partial
7170 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7171 ClassTemplatePartialSpecializationDecl *PartialSpec,
7172 ArrayRef<TemplateArgument> TemplateArgs,
7173 sema::TemplateDeductionInfo &DeductionInfo,
7174 SourceRange InstantiationRange = SourceRange());
7176 /// \brief Note that we are instantiating as part of template
7177 /// argument deduction for a variable template partial
7179 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7180 VarTemplatePartialSpecializationDecl *PartialSpec,
7181 ArrayRef<TemplateArgument> TemplateArgs,
7182 sema::TemplateDeductionInfo &DeductionInfo,
7183 SourceRange InstantiationRange = SourceRange());
7185 /// \brief Note that we are instantiating a default argument for a function
7187 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7189 ArrayRef<TemplateArgument> TemplateArgs,
7190 SourceRange InstantiationRange = SourceRange());
7192 /// \brief Note that we are substituting prior template arguments into a
7193 /// non-type parameter.
7194 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7195 NamedDecl *Template,
7196 NonTypeTemplateParmDecl *Param,
7197 ArrayRef<TemplateArgument> TemplateArgs,
7198 SourceRange InstantiationRange);
7200 /// \brief Note that we are substituting prior template arguments into a
7201 /// template template parameter.
7202 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7203 NamedDecl *Template,
7204 TemplateTemplateParmDecl *Param,
7205 ArrayRef<TemplateArgument> TemplateArgs,
7206 SourceRange InstantiationRange);
7208 /// \brief Note that we are checking the default template argument
7209 /// against the template parameter for a given template-id.
7210 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7211 TemplateDecl *Template,
7213 ArrayRef<TemplateArgument> TemplateArgs,
7214 SourceRange InstantiationRange);
7217 /// \brief Note that we have finished instantiating this template.
7220 ~InstantiatingTemplate() { Clear(); }
7222 /// \brief Determines whether we have exceeded the maximum
7223 /// recursive template instantiations.
7224 bool isInvalid() const { return Invalid; }
7226 /// \brief Determine whether we are already instantiating this
7227 /// specialization in some surrounding active instantiation.
7228 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7233 bool AlreadyInstantiating;
7234 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7235 SourceRange InstantiationRange);
7237 InstantiatingTemplate(
7238 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7239 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7240 Decl *Entity, NamedDecl *Template = nullptr,
7241 ArrayRef<TemplateArgument> TemplateArgs = None,
7242 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7244 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7246 InstantiatingTemplate&
7247 operator=(const InstantiatingTemplate&) = delete;
7250 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7251 void popCodeSynthesisContext();
7253 /// Determine whether we are currently performing template instantiation.
7254 bool inTemplateInstantiation() const {
7255 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7258 void PrintContextStack() {
7259 if (!CodeSynthesisContexts.empty() &&
7260 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7261 PrintInstantiationStack();
7262 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7264 if (PragmaAttributeCurrentTargetDecl)
7265 PrintPragmaAttributeInstantiationPoint();
7267 void PrintInstantiationStack();
7269 void PrintPragmaAttributeInstantiationPoint();
7271 /// \brief Determines whether we are currently in a context where
7272 /// template argument substitution failures are not considered
7275 /// \returns An empty \c Optional if we're not in a SFINAE context.
7276 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7277 /// template-deduction context object, which can be used to capture
7278 /// diagnostics that will be suppressed.
7279 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7281 /// \brief Determines whether we are currently in a context that
7282 /// is not evaluated as per C++ [expr] p5.
7283 bool isUnevaluatedContext() const {
7284 assert(!ExprEvalContexts.empty() &&
7285 "Must be in an expression evaluation context");
7286 return ExprEvalContexts.back().isUnevaluated();
7289 /// \brief RAII class used to determine whether SFINAE has
7290 /// trapped any errors that occur during template argument
7294 unsigned PrevSFINAEErrors;
7295 bool PrevInNonInstantiationSFINAEContext;
7296 bool PrevAccessCheckingSFINAE;
7299 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7300 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7301 PrevInNonInstantiationSFINAEContext(
7302 SemaRef.InNonInstantiationSFINAEContext),
7303 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7305 if (!SemaRef.isSFINAEContext())
7306 SemaRef.InNonInstantiationSFINAEContext = true;
7307 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7311 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7312 SemaRef.InNonInstantiationSFINAEContext
7313 = PrevInNonInstantiationSFINAEContext;
7314 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7317 /// \brief Determine whether any SFINAE errors have been trapped.
7318 bool hasErrorOccurred() const {
7319 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7323 /// \brief RAII class used to indicate that we are performing provisional
7324 /// semantic analysis to determine the validity of a construct, so
7325 /// typo-correction and diagnostics in the immediate context (not within
7326 /// implicitly-instantiated templates) should be suppressed.
7327 class TentativeAnalysisScope {
7329 // FIXME: Using a SFINAETrap for this is a hack.
7331 bool PrevDisableTypoCorrection;
7333 explicit TentativeAnalysisScope(Sema &SemaRef)
7334 : SemaRef(SemaRef), Trap(SemaRef, true),
7335 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7336 SemaRef.DisableTypoCorrection = true;
7338 ~TentativeAnalysisScope() {
7339 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7343 /// \brief The current instantiation scope used to store local
7345 LocalInstantiationScope *CurrentInstantiationScope;
7347 /// \brief Tracks whether we are in a context where typo correction is
7349 bool DisableTypoCorrection;
7351 /// \brief The number of typos corrected by CorrectTypo.
7352 unsigned TyposCorrected;
7354 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7355 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7357 /// \brief A cache containing identifiers for which typo correction failed and
7358 /// their locations, so that repeated attempts to correct an identifier in a
7359 /// given location are ignored if typo correction already failed for it.
7360 IdentifierSourceLocations TypoCorrectionFailures;
7362 /// \brief Worker object for performing CFG-based warnings.
7363 sema::AnalysisBasedWarnings AnalysisWarnings;
7364 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7366 /// \brief An entity for which implicit template instantiation is required.
7368 /// The source location associated with the declaration is the first place in
7369 /// the source code where the declaration was "used". It is not necessarily
7370 /// the point of instantiation (which will be either before or after the
7371 /// namespace-scope declaration that triggered this implicit instantiation),
7372 /// However, it is the location that diagnostics should generally refer to,
7373 /// because users will need to know what code triggered the instantiation.
7374 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7376 /// \brief The queue of implicit template instantiations that are required
7377 /// but have not yet been performed.
7378 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7380 class SavePendingInstantiationsAndVTableUsesRAII {
7382 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7383 : S(S), Enabled(Enabled) {
7384 if (!Enabled) return;
7386 SavedPendingInstantiations.swap(S.PendingInstantiations);
7387 SavedVTableUses.swap(S.VTableUses);
7390 ~SavePendingInstantiationsAndVTableUsesRAII() {
7391 if (!Enabled) return;
7393 // Restore the set of pending vtables.
7394 assert(S.VTableUses.empty() &&
7395 "VTableUses should be empty before it is discarded.");
7396 S.VTableUses.swap(SavedVTableUses);
7398 // Restore the set of pending implicit instantiations.
7399 assert(S.PendingInstantiations.empty() &&
7400 "PendingInstantiations should be empty before it is discarded.");
7401 S.PendingInstantiations.swap(SavedPendingInstantiations);
7406 SmallVector<VTableUse, 16> SavedVTableUses;
7407 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7411 /// \brief The queue of implicit template instantiations that are required
7412 /// and must be performed within the current local scope.
7414 /// This queue is only used for member functions of local classes in
7415 /// templates, which must be instantiated in the same scope as their
7416 /// enclosing function, so that they can reference function-local
7417 /// types, static variables, enumerators, etc.
7418 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7420 class SavePendingLocalImplicitInstantiationsRAII {
7422 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7423 SavedPendingLocalImplicitInstantiations.swap(
7424 S.PendingLocalImplicitInstantiations);
7427 ~SavePendingLocalImplicitInstantiationsRAII() {
7428 assert(S.PendingLocalImplicitInstantiations.empty() &&
7429 "there shouldn't be any pending local implicit instantiations");
7430 SavedPendingLocalImplicitInstantiations.swap(
7431 S.PendingLocalImplicitInstantiations);
7436 std::deque<PendingImplicitInstantiation>
7437 SavedPendingLocalImplicitInstantiations;
7440 /// A helper class for building up ExtParameterInfos.
7441 class ExtParameterInfoBuilder {
7442 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7443 bool HasInteresting = false;
7446 /// Set the ExtParameterInfo for the parameter at the given index,
7448 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7449 assert(Infos.size() <= index);
7450 Infos.resize(index);
7451 Infos.push_back(info);
7453 if (!HasInteresting)
7454 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7457 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7458 /// ExtParameterInfo array we've built up.
7459 const FunctionProtoType::ExtParameterInfo *
7460 getPointerOrNull(unsigned numParams) {
7461 if (!HasInteresting) return nullptr;
7462 Infos.resize(numParams);
7463 return Infos.data();
7467 void PerformPendingInstantiations(bool LocalOnly = false);
7469 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7470 const MultiLevelTemplateArgumentList &TemplateArgs,
7471 SourceLocation Loc, DeclarationName Entity,
7472 bool AllowDeducedTST = false);
7474 QualType SubstType(QualType T,
7475 const MultiLevelTemplateArgumentList &TemplateArgs,
7476 SourceLocation Loc, DeclarationName Entity);
7478 TypeSourceInfo *SubstType(TypeLoc TL,
7479 const MultiLevelTemplateArgumentList &TemplateArgs,
7480 SourceLocation Loc, DeclarationName Entity);
7482 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7483 const MultiLevelTemplateArgumentList &TemplateArgs,
7485 DeclarationName Entity,
7486 CXXRecordDecl *ThisContext,
7487 unsigned ThisTypeQuals);
7488 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7489 const MultiLevelTemplateArgumentList &Args);
7490 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7491 const MultiLevelTemplateArgumentList &TemplateArgs,
7492 int indexAdjustment,
7493 Optional<unsigned> NumExpansions,
7494 bool ExpectParameterPack);
7495 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7496 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7497 const MultiLevelTemplateArgumentList &TemplateArgs,
7498 SmallVectorImpl<QualType> &ParamTypes,
7499 SmallVectorImpl<ParmVarDecl *> *OutParams,
7500 ExtParameterInfoBuilder &ParamInfos);
7501 ExprResult SubstExpr(Expr *E,
7502 const MultiLevelTemplateArgumentList &TemplateArgs);
7504 /// \brief Substitute the given template arguments into a list of
7505 /// expressions, expanding pack expansions if required.
7507 /// \param Exprs The list of expressions to substitute into.
7509 /// \param IsCall Whether this is some form of call, in which case
7510 /// default arguments will be dropped.
7512 /// \param TemplateArgs The set of template arguments to substitute.
7514 /// \param Outputs Will receive all of the substituted arguments.
7516 /// \returns true if an error occurred, false otherwise.
7517 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7518 const MultiLevelTemplateArgumentList &TemplateArgs,
7519 SmallVectorImpl<Expr *> &Outputs);
7521 StmtResult SubstStmt(Stmt *S,
7522 const MultiLevelTemplateArgumentList &TemplateArgs);
7524 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7525 const MultiLevelTemplateArgumentList &TemplateArgs);
7527 ExprResult SubstInitializer(Expr *E,
7528 const MultiLevelTemplateArgumentList &TemplateArgs,
7529 bool CXXDirectInit);
7532 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7533 CXXRecordDecl *Pattern,
7534 const MultiLevelTemplateArgumentList &TemplateArgs);
7537 InstantiateClass(SourceLocation PointOfInstantiation,
7538 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7539 const MultiLevelTemplateArgumentList &TemplateArgs,
7540 TemplateSpecializationKind TSK,
7541 bool Complain = true);
7543 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7544 EnumDecl *Instantiation, EnumDecl *Pattern,
7545 const MultiLevelTemplateArgumentList &TemplateArgs,
7546 TemplateSpecializationKind TSK);
7548 bool InstantiateInClassInitializer(
7549 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7550 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7552 struct LateInstantiatedAttribute {
7553 const Attr *TmplAttr;
7554 LocalInstantiationScope *Scope;
7557 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7559 : TmplAttr(A), Scope(S), NewDecl(D)
7562 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7564 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7565 const Decl *Pattern, Decl *Inst,
7566 LateInstantiatedAttrVec *LateAttrs = nullptr,
7567 LocalInstantiationScope *OuterMostScope = nullptr);
7570 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7571 const Decl *Pattern, Decl *Inst,
7572 LateInstantiatedAttrVec *LateAttrs = nullptr,
7573 LocalInstantiationScope *OuterMostScope = nullptr);
7576 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7577 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7578 TemplateSpecializationKind TSK,
7579 bool Complain = true);
7581 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7582 CXXRecordDecl *Instantiation,
7583 const MultiLevelTemplateArgumentList &TemplateArgs,
7584 TemplateSpecializationKind TSK);
7586 void InstantiateClassTemplateSpecializationMembers(
7587 SourceLocation PointOfInstantiation,
7588 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7589 TemplateSpecializationKind TSK);
7591 NestedNameSpecifierLoc
7592 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7593 const MultiLevelTemplateArgumentList &TemplateArgs);
7596 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7597 const MultiLevelTemplateArgumentList &TemplateArgs);
7599 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7601 const MultiLevelTemplateArgumentList &TemplateArgs);
7602 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7603 TemplateArgumentListInfo &Result,
7604 const MultiLevelTemplateArgumentList &TemplateArgs);
7606 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7607 FunctionDecl *Function);
7608 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7609 FunctionDecl *Function,
7610 bool Recursive = false,
7611 bool DefinitionRequired = false,
7612 bool AtEndOfTU = false);
7613 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7614 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7615 const TemplateArgumentList &TemplateArgList,
7616 const TemplateArgumentListInfo &TemplateArgsInfo,
7617 SmallVectorImpl<TemplateArgument> &Converted,
7618 SourceLocation PointOfInstantiation, void *InsertPos,
7619 LateInstantiatedAttrVec *LateAttrs = nullptr,
7620 LocalInstantiationScope *StartingScope = nullptr);
7621 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7622 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7623 const MultiLevelTemplateArgumentList &TemplateArgs);
7625 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7626 const MultiLevelTemplateArgumentList &TemplateArgs,
7627 LateInstantiatedAttrVec *LateAttrs,
7629 LocalInstantiationScope *StartingScope,
7630 bool InstantiatingVarTemplate = false);
7631 void InstantiateVariableInitializer(
7632 VarDecl *Var, VarDecl *OldVar,
7633 const MultiLevelTemplateArgumentList &TemplateArgs);
7634 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7635 VarDecl *Var, bool Recursive = false,
7636 bool DefinitionRequired = false,
7637 bool AtEndOfTU = false);
7638 void InstantiateStaticDataMemberDefinition(
7639 SourceLocation PointOfInstantiation,
7641 bool Recursive = false,
7642 bool DefinitionRequired = false);
7644 void InstantiateMemInitializers(CXXConstructorDecl *New,
7645 const CXXConstructorDecl *Tmpl,
7646 const MultiLevelTemplateArgumentList &TemplateArgs);
7648 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7649 const MultiLevelTemplateArgumentList &TemplateArgs);
7650 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7651 const MultiLevelTemplateArgumentList &TemplateArgs);
7653 // Objective-C declarations.
7654 enum ObjCContainerKind {
7661 OCK_CategoryImplementation
7663 ObjCContainerKind getObjCContainerKind() const;
7665 DeclResult actOnObjCTypeParam(Scope *S,
7666 ObjCTypeParamVariance variance,
7667 SourceLocation varianceLoc,
7669 IdentifierInfo *paramName,
7670 SourceLocation paramLoc,
7671 SourceLocation colonLoc,
7672 ParsedType typeBound);
7674 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7675 ArrayRef<Decl *> typeParams,
7676 SourceLocation rAngleLoc);
7677 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7679 Decl *ActOnStartClassInterface(Scope *S,
7680 SourceLocation AtInterfaceLoc,
7681 IdentifierInfo *ClassName,
7682 SourceLocation ClassLoc,
7683 ObjCTypeParamList *typeParamList,
7684 IdentifierInfo *SuperName,
7685 SourceLocation SuperLoc,
7686 ArrayRef<ParsedType> SuperTypeArgs,
7687 SourceRange SuperTypeArgsRange,
7688 Decl * const *ProtoRefs,
7689 unsigned NumProtoRefs,
7690 const SourceLocation *ProtoLocs,
7691 SourceLocation EndProtoLoc,
7692 AttributeList *AttrList);
7694 void ActOnSuperClassOfClassInterface(Scope *S,
7695 SourceLocation AtInterfaceLoc,
7696 ObjCInterfaceDecl *IDecl,
7697 IdentifierInfo *ClassName,
7698 SourceLocation ClassLoc,
7699 IdentifierInfo *SuperName,
7700 SourceLocation SuperLoc,
7701 ArrayRef<ParsedType> SuperTypeArgs,
7702 SourceRange SuperTypeArgsRange);
7704 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7705 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7706 IdentifierInfo *SuperName,
7707 SourceLocation SuperLoc);
7709 Decl *ActOnCompatibilityAlias(
7710 SourceLocation AtCompatibilityAliasLoc,
7711 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7712 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7714 bool CheckForwardProtocolDeclarationForCircularDependency(
7715 IdentifierInfo *PName,
7716 SourceLocation &PLoc, SourceLocation PrevLoc,
7717 const ObjCList<ObjCProtocolDecl> &PList);
7719 Decl *ActOnStartProtocolInterface(
7720 SourceLocation AtProtoInterfaceLoc,
7721 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7722 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7723 const SourceLocation *ProtoLocs,
7724 SourceLocation EndProtoLoc,
7725 AttributeList *AttrList);
7727 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7728 IdentifierInfo *ClassName,
7729 SourceLocation ClassLoc,
7730 ObjCTypeParamList *typeParamList,
7731 IdentifierInfo *CategoryName,
7732 SourceLocation CategoryLoc,
7733 Decl * const *ProtoRefs,
7734 unsigned NumProtoRefs,
7735 const SourceLocation *ProtoLocs,
7736 SourceLocation EndProtoLoc,
7737 AttributeList *AttrList);
7739 Decl *ActOnStartClassImplementation(
7740 SourceLocation AtClassImplLoc,
7741 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7742 IdentifierInfo *SuperClassname,
7743 SourceLocation SuperClassLoc);
7745 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7746 IdentifierInfo *ClassName,
7747 SourceLocation ClassLoc,
7748 IdentifierInfo *CatName,
7749 SourceLocation CatLoc);
7751 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7752 ArrayRef<Decl *> Decls);
7754 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7755 IdentifierInfo **IdentList,
7756 SourceLocation *IdentLocs,
7757 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7760 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7761 ArrayRef<IdentifierLocPair> IdentList,
7762 AttributeList *attrList);
7764 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7765 ArrayRef<IdentifierLocPair> ProtocolId,
7766 SmallVectorImpl<Decl *> &Protocols);
7768 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7769 SourceLocation ProtocolLoc,
7770 IdentifierInfo *TypeArgId,
7771 SourceLocation TypeArgLoc,
7772 bool SelectProtocolFirst = false);
7774 /// Given a list of identifiers (and their locations), resolve the
7775 /// names to either Objective-C protocol qualifiers or type
7776 /// arguments, as appropriate.
7777 void actOnObjCTypeArgsOrProtocolQualifiers(
7779 ParsedType baseType,
7780 SourceLocation lAngleLoc,
7781 ArrayRef<IdentifierInfo *> identifiers,
7782 ArrayRef<SourceLocation> identifierLocs,
7783 SourceLocation rAngleLoc,
7784 SourceLocation &typeArgsLAngleLoc,
7785 SmallVectorImpl<ParsedType> &typeArgs,
7786 SourceLocation &typeArgsRAngleLoc,
7787 SourceLocation &protocolLAngleLoc,
7788 SmallVectorImpl<Decl *> &protocols,
7789 SourceLocation &protocolRAngleLoc,
7790 bool warnOnIncompleteProtocols);
7792 /// Build a an Objective-C protocol-qualified 'id' type where no
7793 /// base type was specified.
7794 TypeResult actOnObjCProtocolQualifierType(
7795 SourceLocation lAngleLoc,
7796 ArrayRef<Decl *> protocols,
7797 ArrayRef<SourceLocation> protocolLocs,
7798 SourceLocation rAngleLoc);
7800 /// Build a specialized and/or protocol-qualified Objective-C type.
7801 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7804 ParsedType BaseType,
7805 SourceLocation TypeArgsLAngleLoc,
7806 ArrayRef<ParsedType> TypeArgs,
7807 SourceLocation TypeArgsRAngleLoc,
7808 SourceLocation ProtocolLAngleLoc,
7809 ArrayRef<Decl *> Protocols,
7810 ArrayRef<SourceLocation> ProtocolLocs,
7811 SourceLocation ProtocolRAngleLoc);
7813 /// Build an Objective-C type parameter type.
7814 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7815 SourceLocation ProtocolLAngleLoc,
7816 ArrayRef<ObjCProtocolDecl *> Protocols,
7817 ArrayRef<SourceLocation> ProtocolLocs,
7818 SourceLocation ProtocolRAngleLoc,
7819 bool FailOnError = false);
7821 /// Build an Objective-C object pointer type.
7822 QualType BuildObjCObjectType(QualType BaseType,
7824 SourceLocation TypeArgsLAngleLoc,
7825 ArrayRef<TypeSourceInfo *> TypeArgs,
7826 SourceLocation TypeArgsRAngleLoc,
7827 SourceLocation ProtocolLAngleLoc,
7828 ArrayRef<ObjCProtocolDecl *> Protocols,
7829 ArrayRef<SourceLocation> ProtocolLocs,
7830 SourceLocation ProtocolRAngleLoc,
7831 bool FailOnError = false);
7833 /// Check the application of the Objective-C '__kindof' qualifier to
7835 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7837 /// Ensure attributes are consistent with type.
7838 /// \param [in, out] Attributes The attributes to check; they will
7839 /// be modified to be consistent with \p PropertyTy.
7840 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7842 unsigned &Attributes,
7843 bool propertyInPrimaryClass);
7845 /// Process the specified property declaration and create decls for the
7846 /// setters and getters as needed.
7847 /// \param property The property declaration being processed
7848 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7851 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7852 ObjCPropertyDecl *SuperProperty,
7853 const IdentifierInfo *Name,
7854 bool OverridingProtocolProperty);
7856 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7857 ObjCInterfaceDecl *ID);
7859 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7860 ArrayRef<Decl *> allMethods = None,
7861 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7863 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7864 SourceLocation LParenLoc,
7865 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7866 Selector GetterSel, Selector SetterSel,
7867 tok::ObjCKeywordKind MethodImplKind,
7868 DeclContext *lexicalDC = nullptr);
7870 Decl *ActOnPropertyImplDecl(Scope *S,
7871 SourceLocation AtLoc,
7872 SourceLocation PropertyLoc,
7874 IdentifierInfo *PropertyId,
7875 IdentifierInfo *PropertyIvar,
7876 SourceLocation PropertyIvarLoc,
7877 ObjCPropertyQueryKind QueryKind);
7879 enum ObjCSpecialMethodKind {
7885 OSMK_NonRetainingInit
7888 struct ObjCArgInfo {
7889 IdentifierInfo *Name;
7890 SourceLocation NameLoc;
7891 // The Type is null if no type was specified, and the DeclSpec is invalid
7894 ObjCDeclSpec DeclSpec;
7896 /// ArgAttrs - Attribute list for this argument.
7897 AttributeList *ArgAttrs;
7900 Decl *ActOnMethodDeclaration(
7902 SourceLocation BeginLoc, // location of the + or -.
7903 SourceLocation EndLoc, // location of the ; or {.
7904 tok::TokenKind MethodType,
7905 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7906 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7907 // optional arguments. The number of types/arguments is obtained
7908 // from the Sel.getNumArgs().
7909 ObjCArgInfo *ArgInfo,
7910 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7911 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7912 bool isVariadic, bool MethodDefinition);
7914 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7915 const ObjCObjectPointerType *OPT,
7917 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7920 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7921 bool inferObjCARCLifetime(ValueDecl *decl);
7924 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7926 SourceLocation OpLoc,
7927 DeclarationName MemberName,
7928 SourceLocation MemberLoc,
7929 SourceLocation SuperLoc, QualType SuperType,
7933 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7934 IdentifierInfo &propertyName,
7935 SourceLocation receiverNameLoc,
7936 SourceLocation propertyNameLoc);
7938 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7940 /// \brief Describes the kind of message expression indicated by a message
7941 /// send that starts with an identifier.
7942 enum ObjCMessageKind {
7943 /// \brief The message is sent to 'super'.
7945 /// \brief The message is an instance message.
7946 ObjCInstanceMessage,
7947 /// \brief The message is a class message, and the identifier is a type
7952 ObjCMessageKind getObjCMessageKind(Scope *S,
7953 IdentifierInfo *Name,
7954 SourceLocation NameLoc,
7956 bool HasTrailingDot,
7957 ParsedType &ReceiverType);
7959 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7961 SourceLocation LBracLoc,
7962 ArrayRef<SourceLocation> SelectorLocs,
7963 SourceLocation RBracLoc,
7966 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7967 QualType ReceiverType,
7968 SourceLocation SuperLoc,
7970 ObjCMethodDecl *Method,
7971 SourceLocation LBracLoc,
7972 ArrayRef<SourceLocation> SelectorLocs,
7973 SourceLocation RBracLoc,
7975 bool isImplicit = false);
7977 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7978 bool isSuperReceiver,
7981 ObjCMethodDecl *Method,
7984 ExprResult ActOnClassMessage(Scope *S,
7985 ParsedType Receiver,
7987 SourceLocation LBracLoc,
7988 ArrayRef<SourceLocation> SelectorLocs,
7989 SourceLocation RBracLoc,
7992 ExprResult BuildInstanceMessage(Expr *Receiver,
7993 QualType ReceiverType,
7994 SourceLocation SuperLoc,
7996 ObjCMethodDecl *Method,
7997 SourceLocation LBracLoc,
7998 ArrayRef<SourceLocation> SelectorLocs,
7999 SourceLocation RBracLoc,
8001 bool isImplicit = false);
8003 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8004 QualType ReceiverType,
8007 ObjCMethodDecl *Method,
8010 ExprResult ActOnInstanceMessage(Scope *S,
8013 SourceLocation LBracLoc,
8014 ArrayRef<SourceLocation> SelectorLocs,
8015 SourceLocation RBracLoc,
8018 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8019 ObjCBridgeCastKind Kind,
8020 SourceLocation BridgeKeywordLoc,
8021 TypeSourceInfo *TSInfo,
8024 ExprResult ActOnObjCBridgedCast(Scope *S,
8025 SourceLocation LParenLoc,
8026 ObjCBridgeCastKind Kind,
8027 SourceLocation BridgeKeywordLoc,
8029 SourceLocation RParenLoc,
8032 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8034 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8036 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8039 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8040 QualType DestType, QualType SrcType,
8041 ObjCInterfaceDecl *&RelatedClass,
8042 ObjCMethodDecl *&ClassMethod,
8043 ObjCMethodDecl *&InstanceMethod,
8044 TypedefNameDecl *&TDNDecl,
8045 bool CfToNs, bool Diagnose = true);
8047 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8048 QualType DestType, QualType SrcType,
8049 Expr *&SrcExpr, bool Diagnose = true);
8051 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8052 bool Diagnose = true);
8054 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8056 /// \brief Check whether the given new method is a valid override of the
8057 /// given overridden method, and set any properties that should be inherited.
8058 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8059 const ObjCMethodDecl *Overridden);
8061 /// \brief Describes the compatibility of a result type with its method.
8062 enum ResultTypeCompatibilityKind {
8068 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8069 ObjCInterfaceDecl *CurrentClass,
8070 ResultTypeCompatibilityKind RTC);
8072 enum PragmaOptionsAlignKind {
8073 POAK_Native, // #pragma options align=native
8074 POAK_Natural, // #pragma options align=natural
8075 POAK_Packed, // #pragma options align=packed
8076 POAK_Power, // #pragma options align=power
8077 POAK_Mac68k, // #pragma options align=mac68k
8078 POAK_Reset // #pragma options align=reset
8081 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8082 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8083 SourceLocation PragmaLoc);
8085 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8086 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8087 StringRef SlotLabel, Expr *Alignment);
8089 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8090 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8092 /// ActOnPragmaMSComment - Called on well formed
8093 /// \#pragma comment(kind, "arg").
8094 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8097 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8098 /// pointers_to_members(representation method[, general purpose
8099 /// representation]).
8100 void ActOnPragmaMSPointersToMembers(
8101 LangOptions::PragmaMSPointersToMembersKind Kind,
8102 SourceLocation PragmaLoc);
8104 /// \brief Called on well formed \#pragma vtordisp().
8105 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8106 SourceLocation PragmaLoc,
8107 MSVtorDispAttr::Mode Value);
8109 enum PragmaSectionKind {
8116 bool UnifySection(StringRef SectionName,
8118 DeclaratorDecl *TheDecl);
8119 bool UnifySection(StringRef SectionName,
8121 SourceLocation PragmaSectionLocation);
8123 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8124 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8125 PragmaMsStackAction Action,
8126 llvm::StringRef StackSlotLabel,
8127 StringLiteral *SegmentName,
8128 llvm::StringRef PragmaName);
8130 /// \brief Called on well formed \#pragma section().
8131 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8132 int SectionFlags, StringLiteral *SegmentName);
8134 /// \brief Called on well-formed \#pragma init_seg().
8135 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8136 StringLiteral *SegmentName);
8138 /// \brief Called on #pragma clang __debug dump II
8139 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8141 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8142 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8145 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8146 void ActOnPragmaUnused(const Token &Identifier,
8148 SourceLocation PragmaLoc);
8150 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8151 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8152 SourceLocation PragmaLoc);
8154 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8155 SourceLocation Loc);
8156 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8158 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8159 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8160 SourceLocation PragmaLoc,
8161 SourceLocation WeakNameLoc);
8163 /// ActOnPragmaRedefineExtname - Called on well formed
8164 /// \#pragma redefine_extname oldname newname.
8165 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8166 IdentifierInfo* AliasName,
8167 SourceLocation PragmaLoc,
8168 SourceLocation WeakNameLoc,
8169 SourceLocation AliasNameLoc);
8171 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8172 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8173 IdentifierInfo* AliasName,
8174 SourceLocation PragmaLoc,
8175 SourceLocation WeakNameLoc,
8176 SourceLocation AliasNameLoc);
8178 /// ActOnPragmaFPContract - Called on well formed
8179 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8180 /// \#pragma clang fp contract
8181 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8183 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8184 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8185 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8187 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8188 void AddMsStructLayoutForRecord(RecordDecl *RD);
8190 /// FreePackedContext - Deallocate and null out PackContext.
8191 void FreePackedContext();
8193 /// PushNamespaceVisibilityAttr - Note that we've entered a
8194 /// namespace with a visibility attribute.
8195 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8196 SourceLocation Loc);
8198 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8199 /// add an appropriate visibility attribute.
8200 void AddPushedVisibilityAttribute(Decl *RD);
8202 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8203 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8204 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8206 /// FreeVisContext - Deallocate and null out VisContext.
8207 void FreeVisContext();
8209 /// AddCFAuditedAttribute - Check whether we're currently within
8210 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8211 /// the appropriate attribute.
8212 void AddCFAuditedAttribute(Decl *D);
8214 /// \brief Called on well-formed '\#pragma clang attribute push'.
8215 void ActOnPragmaAttributePush(AttributeList &Attribute,
8216 SourceLocation PragmaLoc,
8217 attr::ParsedSubjectMatchRuleSet Rules);
8219 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8220 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8222 /// \brief Adds the attributes that have been specified using the
8223 /// '\#pragma clang attribute push' directives to the given declaration.
8224 void AddPragmaAttributes(Scope *S, Decl *D);
8226 void DiagnoseUnterminatedPragmaAttribute();
8228 /// \brief Called on well formed \#pragma clang optimize.
8229 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8231 /// \brief Get the location for the currently active "\#pragma clang optimize
8232 /// off". If this location is invalid, then the state of the pragma is "on".
8233 SourceLocation getOptimizeOffPragmaLocation() const {
8234 return OptimizeOffPragmaLocation;
8237 /// \brief Only called on function definitions; if there is a pragma in scope
8238 /// with the effect of a range-based optnone, consider marking the function
8239 /// with attribute optnone.
8240 void AddRangeBasedOptnone(FunctionDecl *FD);
8242 /// \brief Adds the 'optnone' attribute to the function declaration if there
8243 /// are no conflicts; Loc represents the location causing the 'optnone'
8244 /// attribute to be added (usually because of a pragma).
8245 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8247 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8248 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8249 unsigned SpellingListIndex, bool IsPackExpansion);
8250 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8251 unsigned SpellingListIndex, bool IsPackExpansion);
8253 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8255 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8256 unsigned SpellingListIndex);
8258 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8260 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8261 unsigned SpellingListIndex);
8263 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8265 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8266 unsigned SpellingListIndex);
8268 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8270 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8271 Expr *MinBlocks, unsigned SpellingListIndex);
8273 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8274 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8275 unsigned SpellingListIndex, bool InInstantiation = false);
8277 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8278 ParameterABI ABI, unsigned SpellingListIndex);
8280 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8281 unsigned SpellingListIndex, bool isNSConsumed,
8282 bool isTemplateInstantiation);
8284 //===--------------------------------------------------------------------===//
8285 // C++ Coroutines TS
8287 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8288 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8289 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8291 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8292 bool IsImplicit = false);
8293 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8294 UnresolvedLookupExpr* Lookup);
8295 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8296 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8297 bool IsImplicit = false);
8298 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8299 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8300 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8302 //===--------------------------------------------------------------------===//
8303 // OpenCL extensions.
8306 std::string CurrOpenCLExtension;
8307 /// Extensions required by an OpenCL type.
8308 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8309 /// Extensions required by an OpenCL declaration.
8310 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8312 llvm::StringRef getCurrentOpenCLExtension() const {
8313 return CurrOpenCLExtension;
8315 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8316 CurrOpenCLExtension = Ext;
8319 /// \brief Set OpenCL extensions for a type which can only be used when these
8320 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8321 /// \param Exts A space separated list of OpenCL extensions.
8322 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8324 /// \brief Set OpenCL extensions for a declaration which can only be
8325 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8327 /// \param Exts A space separated list of OpenCL extensions.
8328 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8330 /// \brief Set current OpenCL extensions for a type which can only be used
8331 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8332 /// empty, do nothing.
8333 void setCurrentOpenCLExtensionForType(QualType T);
8335 /// \brief Set current OpenCL extensions for a declaration which
8336 /// can only be used when these OpenCL extensions are enabled. If current
8337 /// OpenCL extension is empty, do nothing.
8338 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8340 bool isOpenCLDisabledDecl(Decl *FD);
8342 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8343 /// is disabled due to required OpenCL extensions being disabled. If so,
8344 /// emit diagnostics.
8345 /// \return true if type is disabled.
8346 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8348 /// \brief Check if declaration \p D used by expression \p E
8349 /// is disabled due to required OpenCL extensions being disabled. If so,
8350 /// emit diagnostics.
8351 /// \return true if type is disabled.
8352 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8354 //===--------------------------------------------------------------------===//
8355 // OpenMP directives and clauses.
8358 void *VarDataSharingAttributesStack;
8359 /// Set to true inside '#pragma omp declare target' region.
8360 bool IsInOpenMPDeclareTargetContext = false;
8361 /// \brief Initialization of data-sharing attributes stack.
8362 void InitDataSharingAttributesStack();
8363 void DestroyDataSharingAttributesStack();
8365 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8366 bool StrictlyPositive = true);
8367 /// Returns OpenMP nesting level for current directive.
8368 unsigned getOpenMPNestingLevel() const;
8370 /// Push new OpenMP function region for non-capturing function.
8371 void pushOpenMPFunctionRegion();
8373 /// Pop OpenMP function region for non-capturing function.
8374 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8376 /// Checks if a type or a declaration is disabled due to the owning extension
8377 /// being disabled, and emits diagnostic messages if it is disabled.
8378 /// \param D type or declaration to be checked.
8379 /// \param DiagLoc source location for the diagnostic message.
8380 /// \param DiagInfo information to be emitted for the diagnostic message.
8381 /// \param SrcRange source range of the declaration.
8382 /// \param Map maps type or declaration to the extensions.
8383 /// \param Selector selects diagnostic message: 0 for type and 1 for
8385 /// \return true if the type or declaration is disabled.
8386 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8387 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8388 MapT &Map, unsigned Selector = 0,
8389 SourceRange SrcRange = SourceRange());
8392 /// \brief Return true if the provided declaration \a VD should be captured by
8394 /// \param Level Relative level of nested OpenMP construct for that the check
8396 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8398 /// \brief Check if the specified variable is used in one of the private
8399 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8401 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8402 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8403 ExprObjectKind OK, SourceLocation Loc);
8405 /// \brief Check if the specified variable is used in 'private' clause.
8406 /// \param Level Relative level of nested OpenMP construct for that the check
8408 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8410 /// \brief Check if the specified variable is captured by 'target' directive.
8411 /// \param Level Relative level of nested OpenMP construct for that the check
8413 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8415 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8417 /// \brief Called on start of new data sharing attribute block.
8418 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8419 const DeclarationNameInfo &DirName, Scope *CurScope,
8420 SourceLocation Loc);
8421 /// \brief Start analysis of clauses.
8422 void StartOpenMPClause(OpenMPClauseKind K);
8423 /// \brief End analysis of clauses.
8424 void EndOpenMPClause();
8425 /// \brief Called on end of data sharing attribute block.
8426 void EndOpenMPDSABlock(Stmt *CurDirective);
8428 /// \brief Check if the current region is an OpenMP loop region and if it is,
8429 /// mark loop control variable, used in \p Init for loop initialization, as
8430 /// private by default.
8431 /// \param Init First part of the for loop.
8432 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8434 // OpenMP directives and clauses.
8435 /// \brief Called on correct id-expression from the '#pragma omp
8437 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8438 CXXScopeSpec &ScopeSpec,
8439 const DeclarationNameInfo &Id);
8440 /// \brief Called on well-formed '#pragma omp threadprivate'.
8441 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8443 ArrayRef<Expr *> VarList);
8444 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8445 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8447 ArrayRef<Expr *> VarList);
8448 /// \brief Check if the specified type is allowed to be used in 'omp declare
8449 /// reduction' construct.
8450 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8451 TypeResult ParsedType);
8452 /// \brief Called on start of '#pragma omp declare reduction'.
8453 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8454 Scope *S, DeclContext *DC, DeclarationName Name,
8455 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8456 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8457 /// \brief Initialize declare reduction construct initializer.
8458 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8459 /// \brief Finish current declare reduction construct initializer.
8460 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8461 /// \brief Initialize declare reduction construct initializer.
8462 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8463 /// \brief Finish current declare reduction construct initializer.
8464 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8465 /// \brief Called at the end of '#pragma omp declare reduction'.
8466 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8467 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8469 /// Called on the start of target region i.e. '#pragma omp declare target'.
8470 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8471 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8472 void ActOnFinishOpenMPDeclareTargetDirective();
8473 /// Called on correct id-expression from the '#pragma omp declare target'.
8474 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8475 const DeclarationNameInfo &Id,
8476 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8477 NamedDeclSetType &SameDirectiveDecls);
8478 /// Check declaration inside target region.
8479 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8480 /// Return true inside OpenMP target region.
8481 bool isInOpenMPDeclareTargetContext() const {
8482 return IsInOpenMPDeclareTargetContext;
8485 /// Return the number of captured regions created for an OpenMP directive.
8486 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8488 /// \brief Initialization of captured region for OpenMP region.
8489 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8490 /// \brief End of OpenMP region.
8492 /// \param S Statement associated with the current OpenMP region.
8493 /// \param Clauses List of clauses for the current OpenMP region.
8495 /// \returns Statement for finished OpenMP region.
8496 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8497 StmtResult ActOnOpenMPExecutableDirective(
8498 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8499 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8500 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8501 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8502 /// of the associated statement.
8503 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8505 SourceLocation StartLoc,
8506 SourceLocation EndLoc);
8507 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8508 /// of the associated statement.
8509 StmtResult ActOnOpenMPSimdDirective(
8510 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8511 SourceLocation EndLoc,
8512 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8513 /// \brief Called on well-formed '\#pragma omp for' after parsing
8514 /// of the associated statement.
8515 StmtResult ActOnOpenMPForDirective(
8516 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8517 SourceLocation EndLoc,
8518 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8519 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8520 /// of the associated statement.
8521 StmtResult ActOnOpenMPForSimdDirective(
8522 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8523 SourceLocation EndLoc,
8524 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8525 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8526 /// of the associated statement.
8527 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8528 Stmt *AStmt, SourceLocation StartLoc,
8529 SourceLocation EndLoc);
8530 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8531 /// associated statement.
8532 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8533 SourceLocation EndLoc);
8534 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8535 /// associated statement.
8536 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8537 Stmt *AStmt, SourceLocation StartLoc,
8538 SourceLocation EndLoc);
8539 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8540 /// associated statement.
8541 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8542 SourceLocation EndLoc);
8543 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8544 /// associated statement.
8545 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8546 ArrayRef<OMPClause *> Clauses,
8547 Stmt *AStmt, SourceLocation StartLoc,
8548 SourceLocation EndLoc);
8549 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8550 /// of the associated statement.
8551 StmtResult ActOnOpenMPParallelForDirective(
8552 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8553 SourceLocation EndLoc,
8554 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8555 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8556 /// parsing of the associated statement.
8557 StmtResult ActOnOpenMPParallelForSimdDirective(
8558 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8559 SourceLocation EndLoc,
8560 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8561 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8562 /// parsing of the associated statement.
8563 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8565 SourceLocation StartLoc,
8566 SourceLocation EndLoc);
8567 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8568 /// associated statement.
8569 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8570 Stmt *AStmt, SourceLocation StartLoc,
8571 SourceLocation EndLoc);
8572 /// \brief Called on well-formed '\#pragma omp taskyield'.
8573 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8574 SourceLocation EndLoc);
8575 /// \brief Called on well-formed '\#pragma omp barrier'.
8576 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8577 SourceLocation EndLoc);
8578 /// \brief Called on well-formed '\#pragma omp taskwait'.
8579 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8580 SourceLocation EndLoc);
8581 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8582 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8583 SourceLocation EndLoc);
8584 /// \brief Called on well-formed '\#pragma omp flush'.
8585 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8586 SourceLocation StartLoc,
8587 SourceLocation EndLoc);
8588 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8589 /// associated statement.
8590 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8591 Stmt *AStmt, SourceLocation StartLoc,
8592 SourceLocation EndLoc);
8593 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8594 /// associated statement.
8595 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8596 Stmt *AStmt, SourceLocation StartLoc,
8597 SourceLocation EndLoc);
8598 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8599 /// associated statement.
8600 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8601 Stmt *AStmt, SourceLocation StartLoc,
8602 SourceLocation EndLoc);
8603 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8604 /// the associated statement.
8605 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8606 Stmt *AStmt, SourceLocation StartLoc,
8607 SourceLocation EndLoc);
8608 /// \brief Called on well-formed '\#pragma omp target enter data' after
8609 /// parsing of the associated statement.
8610 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8611 SourceLocation StartLoc,
8612 SourceLocation EndLoc);
8613 /// \brief Called on well-formed '\#pragma omp target exit data' after
8614 /// parsing of the associated statement.
8615 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8616 SourceLocation StartLoc,
8617 SourceLocation EndLoc);
8618 /// \brief Called on well-formed '\#pragma omp target parallel' after
8619 /// parsing of the associated statement.
8620 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8622 SourceLocation StartLoc,
8623 SourceLocation EndLoc);
8624 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8625 /// parsing of the associated statement.
8626 StmtResult ActOnOpenMPTargetParallelForDirective(
8627 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8628 SourceLocation EndLoc,
8629 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8630 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8631 /// associated statement.
8632 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8633 Stmt *AStmt, SourceLocation StartLoc,
8634 SourceLocation EndLoc);
8635 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8637 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8638 SourceLocation EndLoc,
8639 OpenMPDirectiveKind CancelRegion);
8640 /// \brief Called on well-formed '\#pragma omp cancel'.
8641 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8642 SourceLocation StartLoc,
8643 SourceLocation EndLoc,
8644 OpenMPDirectiveKind CancelRegion);
8645 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8646 /// associated statement.
8647 StmtResult ActOnOpenMPTaskLoopDirective(
8648 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8649 SourceLocation EndLoc,
8650 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8651 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8652 /// the associated statement.
8653 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8654 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8655 SourceLocation EndLoc,
8656 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8657 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8658 /// of the associated statement.
8659 StmtResult ActOnOpenMPDistributeDirective(
8660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8661 SourceLocation EndLoc,
8662 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8663 /// \brief Called on well-formed '\#pragma omp target update'.
8664 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8665 SourceLocation StartLoc,
8666 SourceLocation EndLoc);
8667 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8668 /// parsing of the associated statement.
8669 StmtResult ActOnOpenMPDistributeParallelForDirective(
8670 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8671 SourceLocation EndLoc,
8672 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8673 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8674 /// after parsing of the associated statement.
8675 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8676 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8677 SourceLocation EndLoc,
8678 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8679 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8680 /// parsing of the associated statement.
8681 StmtResult ActOnOpenMPDistributeSimdDirective(
8682 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8683 SourceLocation EndLoc,
8684 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8685 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8686 /// parsing of the associated statement.
8687 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8688 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8689 SourceLocation EndLoc,
8690 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8691 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8692 /// the associated statement.
8693 StmtResult ActOnOpenMPTargetSimdDirective(
8694 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8695 SourceLocation EndLoc,
8696 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8697 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8698 /// the associated statement.
8699 StmtResult ActOnOpenMPTeamsDistributeDirective(
8700 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8701 SourceLocation EndLoc,
8702 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8703 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8704 /// of the associated statement.
8705 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8706 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8707 SourceLocation EndLoc,
8708 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8709 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8710 /// after parsing of the associated statement.
8711 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8713 SourceLocation EndLoc,
8714 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8715 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8716 /// after parsing of the associated statement.
8717 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8718 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8719 SourceLocation EndLoc,
8720 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8721 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8722 /// associated statement.
8723 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8725 SourceLocation StartLoc,
8726 SourceLocation EndLoc);
8727 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8728 /// of the associated statement.
8729 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8730 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8731 SourceLocation EndLoc,
8732 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8733 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8734 /// after parsing of the associated statement.
8735 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8736 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8737 SourceLocation EndLoc,
8738 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8739 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8740 /// simd' after parsing of the associated statement.
8741 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8742 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8743 SourceLocation EndLoc,
8744 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8745 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8746 /// parsing of the associated statement.
8747 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8749 SourceLocation EndLoc,
8750 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8752 /// Checks correctness of linear modifiers.
8753 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8754 SourceLocation LinLoc);
8755 /// Checks that the specified declaration matches requirements for the linear
8757 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8758 OpenMPLinearClauseKind LinKind, QualType Type);
8760 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8761 /// the associated method/function.
8762 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8763 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8764 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8765 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8766 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8768 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8770 SourceLocation StartLoc,
8771 SourceLocation LParenLoc,
8772 SourceLocation EndLoc);
8773 /// \brief Called on well-formed 'if' clause.
8774 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8775 Expr *Condition, SourceLocation StartLoc,
8776 SourceLocation LParenLoc,
8777 SourceLocation NameModifierLoc,
8778 SourceLocation ColonLoc,
8779 SourceLocation EndLoc);
8780 /// \brief Called on well-formed 'final' clause.
8781 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8782 SourceLocation LParenLoc,
8783 SourceLocation EndLoc);
8784 /// \brief Called on well-formed 'num_threads' clause.
8785 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8786 SourceLocation StartLoc,
8787 SourceLocation LParenLoc,
8788 SourceLocation EndLoc);
8789 /// \brief Called on well-formed 'safelen' clause.
8790 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8791 SourceLocation StartLoc,
8792 SourceLocation LParenLoc,
8793 SourceLocation EndLoc);
8794 /// \brief Called on well-formed 'simdlen' clause.
8795 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8796 SourceLocation LParenLoc,
8797 SourceLocation EndLoc);
8798 /// \brief Called on well-formed 'collapse' clause.
8799 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8800 SourceLocation StartLoc,
8801 SourceLocation LParenLoc,
8802 SourceLocation EndLoc);
8803 /// \brief Called on well-formed 'ordered' clause.
8805 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8806 SourceLocation LParenLoc = SourceLocation(),
8807 Expr *NumForLoops = nullptr);
8808 /// \brief Called on well-formed 'grainsize' clause.
8809 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8810 SourceLocation LParenLoc,
8811 SourceLocation EndLoc);
8812 /// \brief Called on well-formed 'num_tasks' clause.
8813 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8814 SourceLocation LParenLoc,
8815 SourceLocation EndLoc);
8816 /// \brief Called on well-formed 'hint' clause.
8817 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8818 SourceLocation LParenLoc,
8819 SourceLocation EndLoc);
8821 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8823 SourceLocation ArgumentLoc,
8824 SourceLocation StartLoc,
8825 SourceLocation LParenLoc,
8826 SourceLocation EndLoc);
8827 /// \brief Called on well-formed 'default' clause.
8828 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8829 SourceLocation KindLoc,
8830 SourceLocation StartLoc,
8831 SourceLocation LParenLoc,
8832 SourceLocation EndLoc);
8833 /// \brief Called on well-formed 'proc_bind' clause.
8834 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8835 SourceLocation KindLoc,
8836 SourceLocation StartLoc,
8837 SourceLocation LParenLoc,
8838 SourceLocation EndLoc);
8840 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8841 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8842 SourceLocation StartLoc, SourceLocation LParenLoc,
8843 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8844 SourceLocation EndLoc);
8845 /// \brief Called on well-formed 'schedule' clause.
8846 OMPClause *ActOnOpenMPScheduleClause(
8847 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8848 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8849 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8850 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8852 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8853 SourceLocation EndLoc);
8854 /// \brief Called on well-formed 'nowait' clause.
8855 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8856 SourceLocation EndLoc);
8857 /// \brief Called on well-formed 'untied' clause.
8858 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8859 SourceLocation EndLoc);
8860 /// \brief Called on well-formed 'mergeable' clause.
8861 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8862 SourceLocation EndLoc);
8863 /// \brief Called on well-formed 'read' clause.
8864 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8865 SourceLocation EndLoc);
8866 /// \brief Called on well-formed 'write' clause.
8867 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8868 SourceLocation EndLoc);
8869 /// \brief Called on well-formed 'update' clause.
8870 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8871 SourceLocation EndLoc);
8872 /// \brief Called on well-formed 'capture' clause.
8873 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8874 SourceLocation EndLoc);
8875 /// \brief Called on well-formed 'seq_cst' clause.
8876 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8877 SourceLocation EndLoc);
8878 /// \brief Called on well-formed 'threads' clause.
8879 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8880 SourceLocation EndLoc);
8881 /// \brief Called on well-formed 'simd' clause.
8882 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8883 SourceLocation EndLoc);
8884 /// \brief Called on well-formed 'nogroup' clause.
8885 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8886 SourceLocation EndLoc);
8888 OMPClause *ActOnOpenMPVarListClause(
8889 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8890 SourceLocation StartLoc, SourceLocation LParenLoc,
8891 SourceLocation ColonLoc, SourceLocation EndLoc,
8892 CXXScopeSpec &ReductionIdScopeSpec,
8893 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8894 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8895 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8896 SourceLocation DepLinMapLoc);
8897 /// \brief Called on well-formed 'private' clause.
8898 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8899 SourceLocation StartLoc,
8900 SourceLocation LParenLoc,
8901 SourceLocation EndLoc);
8902 /// \brief Called on well-formed 'firstprivate' clause.
8903 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8904 SourceLocation StartLoc,
8905 SourceLocation LParenLoc,
8906 SourceLocation EndLoc);
8907 /// \brief Called on well-formed 'lastprivate' clause.
8908 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8909 SourceLocation StartLoc,
8910 SourceLocation LParenLoc,
8911 SourceLocation EndLoc);
8912 /// \brief Called on well-formed 'shared' clause.
8913 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8914 SourceLocation StartLoc,
8915 SourceLocation LParenLoc,
8916 SourceLocation EndLoc);
8917 /// \brief Called on well-formed 'reduction' clause.
8918 OMPClause *ActOnOpenMPReductionClause(
8919 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8920 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8921 CXXScopeSpec &ReductionIdScopeSpec,
8922 const DeclarationNameInfo &ReductionId,
8923 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8924 /// \brief Called on well-formed 'linear' clause.
8926 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8927 SourceLocation StartLoc, SourceLocation LParenLoc,
8928 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8929 SourceLocation ColonLoc, SourceLocation EndLoc);
8930 /// \brief Called on well-formed 'aligned' clause.
8931 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8933 SourceLocation StartLoc,
8934 SourceLocation LParenLoc,
8935 SourceLocation ColonLoc,
8936 SourceLocation EndLoc);
8937 /// \brief Called on well-formed 'copyin' clause.
8938 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8939 SourceLocation StartLoc,
8940 SourceLocation LParenLoc,
8941 SourceLocation EndLoc);
8942 /// \brief Called on well-formed 'copyprivate' clause.
8943 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8944 SourceLocation StartLoc,
8945 SourceLocation LParenLoc,
8946 SourceLocation EndLoc);
8947 /// \brief Called on well-formed 'flush' pseudo clause.
8948 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8949 SourceLocation StartLoc,
8950 SourceLocation LParenLoc,
8951 SourceLocation EndLoc);
8952 /// \brief Called on well-formed 'depend' clause.
8954 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8955 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8956 SourceLocation StartLoc, SourceLocation LParenLoc,
8957 SourceLocation EndLoc);
8958 /// \brief Called on well-formed 'device' clause.
8959 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8960 SourceLocation LParenLoc,
8961 SourceLocation EndLoc);
8962 /// \brief Called on well-formed 'map' clause.
8964 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8965 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8966 SourceLocation MapLoc, SourceLocation ColonLoc,
8967 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8968 SourceLocation LParenLoc, SourceLocation EndLoc);
8969 /// \brief Called on well-formed 'num_teams' clause.
8970 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8971 SourceLocation LParenLoc,
8972 SourceLocation EndLoc);
8973 /// \brief Called on well-formed 'thread_limit' clause.
8974 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8975 SourceLocation StartLoc,
8976 SourceLocation LParenLoc,
8977 SourceLocation EndLoc);
8978 /// \brief Called on well-formed 'priority' clause.
8979 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8980 SourceLocation LParenLoc,
8981 SourceLocation EndLoc);
8982 /// \brief Called on well-formed 'dist_schedule' clause.
8983 OMPClause *ActOnOpenMPDistScheduleClause(
8984 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8985 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8986 SourceLocation CommaLoc, SourceLocation EndLoc);
8987 /// \brief Called on well-formed 'defaultmap' clause.
8988 OMPClause *ActOnOpenMPDefaultmapClause(
8989 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8990 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8991 SourceLocation KindLoc, SourceLocation EndLoc);
8992 /// \brief Called on well-formed 'to' clause.
8993 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8994 SourceLocation StartLoc,
8995 SourceLocation LParenLoc,
8996 SourceLocation EndLoc);
8997 /// \brief Called on well-formed 'from' clause.
8998 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8999 SourceLocation StartLoc,
9000 SourceLocation LParenLoc,
9001 SourceLocation EndLoc);
9002 /// Called on well-formed 'use_device_ptr' clause.
9003 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9004 SourceLocation StartLoc,
9005 SourceLocation LParenLoc,
9006 SourceLocation EndLoc);
9007 /// Called on well-formed 'is_device_ptr' clause.
9008 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9009 SourceLocation StartLoc,
9010 SourceLocation LParenLoc,
9011 SourceLocation EndLoc);
9013 /// \brief The kind of conversion being performed.
9014 enum CheckedConversionKind {
9015 /// \brief An implicit conversion.
9016 CCK_ImplicitConversion,
9017 /// \brief A C-style cast.
9019 /// \brief A functional-style cast.
9021 /// \brief A cast other than a C-style cast.
9025 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9026 /// cast. If there is already an implicit cast, merge into the existing one.
9027 /// If isLvalue, the result of the cast is an lvalue.
9028 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9029 ExprValueKind VK = VK_RValue,
9030 const CXXCastPath *BasePath = nullptr,
9031 CheckedConversionKind CCK
9032 = CCK_ImplicitConversion);
9034 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9035 /// to the conversion from scalar type ScalarTy to the Boolean type.
9036 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9038 /// IgnoredValueConversions - Given that an expression's result is
9039 /// syntactically ignored, perform any conversions that are
9041 ExprResult IgnoredValueConversions(Expr *E);
9043 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9044 // functions and arrays to their respective pointers (C99 6.3.2.1).
9045 ExprResult UsualUnaryConversions(Expr *E);
9047 /// CallExprUnaryConversions - a special case of an unary conversion
9048 /// performed on a function designator of a call expression.
9049 ExprResult CallExprUnaryConversions(Expr *E);
9051 // DefaultFunctionArrayConversion - converts functions and arrays
9052 // to their respective pointers (C99 6.3.2.1).
9053 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9055 // DefaultFunctionArrayLvalueConversion - converts functions and
9056 // arrays to their respective pointers and performs the
9057 // lvalue-to-rvalue conversion.
9058 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9059 bool Diagnose = true);
9061 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9062 // the operand. This is DefaultFunctionArrayLvalueConversion,
9063 // except that it assumes the operand isn't of function or array
9065 ExprResult DefaultLvalueConversion(Expr *E);
9067 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9068 // do not have a prototype. Integer promotions are performed on each
9069 // argument, and arguments that have type float are promoted to double.
9070 ExprResult DefaultArgumentPromotion(Expr *E);
9072 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9073 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9074 /// we don't have xvalues there.
9075 ExprResult TemporaryMaterializationConversion(Expr *E);
9077 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9078 enum VariadicCallType {
9082 VariadicConstructor,
9083 VariadicDoesNotApply
9086 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9087 const FunctionProtoType *Proto,
9090 // Used for determining in which context a type is allowed to be passed to a
9100 // Determines which VarArgKind fits an expression.
9101 VarArgKind isValidVarArgType(const QualType &Ty);
9103 /// Check to see if the given expression is a valid argument to a variadic
9104 /// function, issuing a diagnostic if not.
9105 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9107 /// Check to see if a given expression could have '.c_str()' called on it.
9108 bool hasCStrMethod(const Expr *E);
9110 /// GatherArgumentsForCall - Collector argument expressions for various
9111 /// form of call prototypes.
9112 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9113 const FunctionProtoType *Proto,
9114 unsigned FirstParam, ArrayRef<Expr *> Args,
9115 SmallVectorImpl<Expr *> &AllArgs,
9116 VariadicCallType CallType = VariadicDoesNotApply,
9117 bool AllowExplicit = false,
9118 bool IsListInitialization = false);
9120 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9121 // will create a runtime trap if the resulting type is not a POD type.
9122 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9123 FunctionDecl *FDecl);
9125 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9126 // operands and then handles various conversions that are common to binary
9127 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9128 // routine returns the first non-arithmetic type found. The client is
9129 // responsible for emitting appropriate error diagnostics.
9130 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9131 bool IsCompAssign = false);
9133 /// AssignConvertType - All of the 'assignment' semantic checks return this
9134 /// enum to indicate whether the assignment was allowed. These checks are
9135 /// done for simple assignments, as well as initialization, return from
9136 /// function, argument passing, etc. The query is phrased in terms of a
9137 /// source and destination type.
9138 enum AssignConvertType {
9139 /// Compatible - the types are compatible according to the standard.
9142 /// PointerToInt - The assignment converts a pointer to an int, which we
9143 /// accept as an extension.
9146 /// IntToPointer - The assignment converts an int to a pointer, which we
9147 /// accept as an extension.
9150 /// FunctionVoidPointer - The assignment is between a function pointer and
9151 /// void*, which the standard doesn't allow, but we accept as an extension.
9152 FunctionVoidPointer,
9154 /// IncompatiblePointer - The assignment is between two pointers types that
9155 /// are not compatible, but we accept them as an extension.
9156 IncompatiblePointer,
9158 /// IncompatiblePointerSign - The assignment is between two pointers types
9159 /// which point to integers which have a different sign, but are otherwise
9160 /// identical. This is a subset of the above, but broken out because it's by
9161 /// far the most common case of incompatible pointers.
9162 IncompatiblePointerSign,
9164 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9165 /// c/v/r qualifiers, which we accept as an extension.
9166 CompatiblePointerDiscardsQualifiers,
9168 /// IncompatiblePointerDiscardsQualifiers - The assignment
9169 /// discards qualifiers that we don't permit to be discarded,
9170 /// like address spaces.
9171 IncompatiblePointerDiscardsQualifiers,
9173 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9174 /// nested pointer types, and the qualifiers other than the first two
9175 /// levels differ e.g. char ** -> const char **, but we accept them as an
9177 IncompatibleNestedPointerQualifiers,
9179 /// IncompatibleVectors - The assignment is between two vector types that
9180 /// have the same size, which we accept as an extension.
9181 IncompatibleVectors,
9183 /// IntToBlockPointer - The assignment converts an int to a block
9184 /// pointer. We disallow this.
9187 /// IncompatibleBlockPointer - The assignment is between two block
9188 /// pointers types that are not compatible.
9189 IncompatibleBlockPointer,
9191 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9192 /// id type and something else (that is incompatible with it). For example,
9193 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9194 IncompatibleObjCQualifiedId,
9196 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9197 /// object with __weak qualifier.
9198 IncompatibleObjCWeakRef,
9200 /// Incompatible - We reject this conversion outright, it is invalid to
9201 /// represent it in the AST.
9205 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9206 /// assignment conversion type specified by ConvTy. This returns true if the
9207 /// conversion was invalid or false if the conversion was accepted.
9208 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9210 QualType DstType, QualType SrcType,
9211 Expr *SrcExpr, AssignmentAction Action,
9212 bool *Complained = nullptr);
9214 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9215 /// enum. If AllowMask is true, then we also allow the complement of a valid
9216 /// value, to be used as a mask.
9217 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9218 bool AllowMask) const;
9220 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9221 /// integer not in the range of enum values.
9222 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9225 /// CheckAssignmentConstraints - Perform type checking for assignment,
9226 /// argument passing, variable initialization, and function return values.
9228 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9232 /// Check assignment constraints and optionally prepare for a conversion of
9233 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9235 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9238 bool ConvertRHS = true);
9240 /// Check assignment constraints for an assignment of RHS to LHSType.
9242 /// \param LHSType The destination type for the assignment.
9243 /// \param RHS The source expression for the assignment.
9244 /// \param Diagnose If \c true, diagnostics may be produced when checking
9245 /// for assignability. If a diagnostic is produced, \p RHS will be
9246 /// set to ExprError(). Note that this function may still return
9247 /// without producing a diagnostic, even for an invalid assignment.
9248 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9249 /// in an audited Core Foundation API and does not need to be checked
9250 /// for ARC retain issues.
9251 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9252 /// conversions necessary to perform the assignment. If \c false,
9253 /// \p Diagnose must also be \c false.
9254 AssignConvertType CheckSingleAssignmentConstraints(
9255 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9256 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9258 // \brief If the lhs type is a transparent union, check whether we
9259 // can initialize the transparent union with the given expression.
9260 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9263 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9265 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9267 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9268 AssignmentAction Action,
9269 bool AllowExplicit = false);
9270 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9271 AssignmentAction Action,
9273 ImplicitConversionSequence& ICS);
9274 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9275 const ImplicitConversionSequence& ICS,
9276 AssignmentAction Action,
9277 CheckedConversionKind CCK
9278 = CCK_ImplicitConversion);
9279 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9280 const StandardConversionSequence& SCS,
9281 AssignmentAction Action,
9282 CheckedConversionKind CCK);
9284 /// the following "Check" methods will return a valid/converted QualType
9285 /// or a null QualType (indicating an error diagnostic was issued).
9287 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9288 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9290 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9292 QualType CheckPointerToMemberOperands( // C++ 5.5
9293 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9294 SourceLocation OpLoc, bool isIndirect);
9295 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9296 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9298 QualType CheckRemainderOperands( // C99 6.5.5
9299 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9300 bool IsCompAssign = false);
9301 QualType CheckAdditionOperands( // C99 6.5.6
9302 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9303 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9304 QualType CheckSubtractionOperands( // C99 6.5.6
9305 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9306 QualType* CompLHSTy = nullptr);
9307 QualType CheckShiftOperands( // C99 6.5.7
9308 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9309 BinaryOperatorKind Opc, bool IsCompAssign = false);
9310 QualType CheckCompareOperands( // C99 6.5.8/9
9311 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9312 BinaryOperatorKind Opc, bool isRelational);
9313 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9314 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9315 BinaryOperatorKind Opc);
9316 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9317 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9318 BinaryOperatorKind Opc);
9319 // CheckAssignmentOperands is used for both simple and compound assignment.
9320 // For simple assignment, pass both expressions and a null converted type.
9321 // For compound assignment, pass both expressions and the converted type.
9322 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9323 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9325 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9326 UnaryOperatorKind Opcode, Expr *Op);
9327 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9328 BinaryOperatorKind Opcode,
9329 Expr *LHS, Expr *RHS);
9330 ExprResult checkPseudoObjectRValue(Expr *E);
9331 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9333 QualType CheckConditionalOperands( // C99 6.5.15
9334 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9335 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9336 QualType CXXCheckConditionalOperands( // C++ 5.16
9337 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9338 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9339 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9340 bool ConvertArgs = true);
9341 QualType FindCompositePointerType(SourceLocation Loc,
9342 ExprResult &E1, ExprResult &E2,
9343 bool ConvertArgs = true) {
9344 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9345 QualType Composite =
9346 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9352 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9353 SourceLocation QuestionLoc);
9355 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9356 SourceLocation QuestionLoc);
9358 void DiagnoseAlwaysNonNullPointer(Expr *E,
9359 Expr::NullPointerConstantKind NullType,
9360 bool IsEqual, SourceRange Range);
9362 /// type checking for vector binary operators.
9363 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9364 SourceLocation Loc, bool IsCompAssign,
9365 bool AllowBothBool, bool AllowBoolConversion);
9366 QualType GetSignedVectorType(QualType V);
9367 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9368 SourceLocation Loc, bool isRelational);
9369 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9370 SourceLocation Loc);
9372 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9373 bool isLaxVectorConversion(QualType srcType, QualType destType);
9375 /// type checking declaration initializers (C99 6.7.8)
9376 bool CheckForConstantInitializer(Expr *e, QualType t);
9378 // type checking C++ declaration initializers (C++ [dcl.init]).
9380 /// ReferenceCompareResult - Expresses the result of comparing two
9381 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9382 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9383 enum ReferenceCompareResult {
9384 /// Ref_Incompatible - The two types are incompatible, so direct
9385 /// reference binding is not possible.
9386 Ref_Incompatible = 0,
9387 /// Ref_Related - The two types are reference-related, which means
9388 /// that their unqualified forms (T1 and T2) are either the same
9389 /// or T1 is a base class of T2.
9391 /// Ref_Compatible - The two types are reference-compatible.
9395 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9396 QualType T1, QualType T2,
9397 bool &DerivedToBase,
9398 bool &ObjCConversion,
9399 bool &ObjCLifetimeConversion);
9401 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9402 Expr *CastExpr, CastKind &CastKind,
9403 ExprValueKind &VK, CXXCastPath &Path);
9405 /// \brief Force an expression with unknown-type to an expression of the
9407 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9409 /// \brief Type-check an expression that's being passed to an
9410 /// __unknown_anytype parameter.
9411 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9412 Expr *result, QualType ¶mType);
9414 // CheckVectorCast - check type constraints for vectors.
9415 // Since vectors are an extension, there are no C standard reference for this.
9416 // We allow casting between vectors and integer datatypes of the same size.
9417 // returns true if the cast is invalid
9418 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9421 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9422 /// implicit casts if necessary.
9423 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9425 // CheckExtVectorCast - check type constraints for extended vectors.
9426 // Since vectors are an extension, there are no C standard reference for this.
9427 // We allow casting between vectors and integer datatypes of the same size,
9428 // or vectors and the element type of that vector.
9429 // returns the cast expr
9430 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9433 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9434 SourceLocation LParenLoc,
9436 SourceLocation RParenLoc);
9438 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9440 /// \brief Checks for invalid conversions and casts between
9441 /// retainable pointers and other pointer kinds for ARC and Weak.
9442 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9443 QualType castType, Expr *&op,
9444 CheckedConversionKind CCK,
9445 bool Diagnose = true,
9446 bool DiagnoseCFAudited = false,
9447 BinaryOperatorKind Opc = BO_PtrMemD
9450 Expr *stripARCUnbridgedCast(Expr *e);
9451 void diagnoseARCUnbridgedCast(Expr *e);
9453 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9456 /// checkRetainCycles - Check whether an Objective-C message send
9457 /// might create an obvious retain cycle.
9458 void checkRetainCycles(ObjCMessageExpr *msg);
9459 void checkRetainCycles(Expr *receiver, Expr *argument);
9460 void checkRetainCycles(VarDecl *Var, Expr *Init);
9462 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9463 /// to weak/__unsafe_unretained type.
9464 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9466 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9467 /// to weak/__unsafe_unretained expression.
9468 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9470 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9471 /// \param Method - May be null.
9472 /// \param [out] ReturnType - The return type of the send.
9473 /// \return true iff there were any incompatible types.
9474 bool CheckMessageArgumentTypes(QualType ReceiverType,
9475 MultiExprArg Args, Selector Sel,
9476 ArrayRef<SourceLocation> SelectorLocs,
9477 ObjCMethodDecl *Method, bool isClassMessage,
9478 bool isSuperMessage,
9479 SourceLocation lbrac, SourceLocation rbrac,
9480 SourceRange RecRange,
9481 QualType &ReturnType, ExprValueKind &VK);
9483 /// \brief Determine the result of a message send expression based on
9484 /// the type of the receiver, the method expected to receive the message,
9485 /// and the form of the message send.
9486 QualType getMessageSendResultType(QualType ReceiverType,
9487 ObjCMethodDecl *Method,
9488 bool isClassMessage, bool isSuperMessage);
9490 /// \brief If the given expression involves a message send to a method
9491 /// with a related result type, emit a note describing what happened.
9492 void EmitRelatedResultTypeNote(const Expr *E);
9494 /// \brief Given that we had incompatible pointer types in a return
9495 /// statement, check whether we're in a method with a related result
9496 /// type, and if so, emit a note describing what happened.
9497 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9499 class ConditionResult {
9501 FullExprArg Condition;
9507 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9509 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9510 HasKnownValue(IsConstexpr && Condition.get() &&
9511 !Condition.get()->isValueDependent()),
9512 KnownValue(HasKnownValue &&
9513 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9514 explicit ConditionResult(bool Invalid)
9515 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9516 HasKnownValue(false), KnownValue(false) {}
9519 ConditionResult() : ConditionResult(false) {}
9520 bool isInvalid() const { return Invalid; }
9521 std::pair<VarDecl *, Expr *> get() const {
9522 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9525 llvm::Optional<bool> getKnownValue() const {
9531 static ConditionResult ConditionError() { return ConditionResult(true); }
9533 enum class ConditionKind {
9534 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9535 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9536 Switch ///< An integral condition for a 'switch' statement.
9539 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9540 Expr *SubExpr, ConditionKind CK);
9542 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9543 SourceLocation StmtLoc,
9546 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9548 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9549 SourceLocation StmtLoc,
9551 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9553 /// CheckBooleanCondition - Diagnose problems involving the use of
9554 /// the given expression as a boolean condition (e.g. in an if
9555 /// statement). Also performs the standard function and array
9556 /// decays, possibly changing the input variable.
9558 /// \param Loc - A location associated with the condition, e.g. the
9560 /// \return true iff there were any errors
9561 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9562 bool IsConstexpr = false);
9564 /// DiagnoseAssignmentAsCondition - Given that an expression is
9565 /// being used as a boolean condition, warn if it's an assignment.
9566 void DiagnoseAssignmentAsCondition(Expr *E);
9568 /// \brief Redundant parentheses over an equality comparison can indicate
9569 /// that the user intended an assignment used as condition.
9570 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9572 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9573 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9575 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9576 /// the specified width and sign. If an overflow occurs, detect it and emit
9577 /// the specified diagnostic.
9578 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9579 unsigned NewWidth, bool NewSign,
9580 SourceLocation Loc, unsigned DiagID);
9582 /// Checks that the Objective-C declaration is declared in the global scope.
9583 /// Emits an error and marks the declaration as invalid if it's not declared
9584 /// in the global scope.
9585 bool CheckObjCDeclScope(Decl *D);
9587 /// \brief Abstract base class used for diagnosing integer constant
9588 /// expression violations.
9589 class VerifyICEDiagnoser {
9593 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9595 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9596 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9597 virtual ~VerifyICEDiagnoser() { }
9600 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9601 /// and reports the appropriate diagnostics. Returns false on success.
9602 /// Can optionally return the value of the expression.
9603 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9604 VerifyICEDiagnoser &Diagnoser,
9605 bool AllowFold = true);
9606 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9608 bool AllowFold = true);
9609 ExprResult VerifyIntegerConstantExpression(Expr *E,
9610 llvm::APSInt *Result = nullptr);
9612 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9613 /// the correct width, and that the field type is valid.
9614 /// Returns false on success.
9615 /// Can optionally return whether the bit-field is of width 0
9616 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9617 QualType FieldTy, bool IsMsStruct,
9618 Expr *BitWidth, bool *ZeroWidth = nullptr);
9621 unsigned ForceCUDAHostDeviceDepth = 0;
9624 /// Increments our count of the number of times we've seen a pragma forcing
9625 /// functions to be __host__ __device__. So long as this count is greater
9626 /// than zero, all functions encountered will be __host__ __device__.
9627 void PushForceCUDAHostDevice();
9629 /// Decrements our count of the number of times we've seen a pragma forcing
9630 /// functions to be __host__ __device__. Returns false if the count is 0
9631 /// before incrementing, so you can emit an error.
9632 bool PopForceCUDAHostDevice();
9634 /// Diagnostics that are emitted only if we discover that the given function
9635 /// must be codegen'ed. Because handling these correctly adds overhead to
9636 /// compilation, this is currently only enabled for CUDA compilations.
9637 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9638 std::vector<PartialDiagnosticAt>>
9641 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9642 /// key in a hashtable, both the FD and location are hashed.
9643 struct FunctionDeclAndLoc {
9644 CanonicalDeclPtr<FunctionDecl> FD;
9648 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9649 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9650 /// same deferred diag twice.
9651 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9653 /// An inverse call graph, mapping known-emitted functions to one of their
9654 /// known-emitted callers (plus the location of the call).
9656 /// Functions that we can tell a priori must be emitted aren't added to this
9658 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9659 /* Caller = */ FunctionDeclAndLoc>
9660 CUDAKnownEmittedFns;
9662 /// A partial call graph maintained during CUDA compilation to support
9663 /// deferred diagnostics.
9665 /// Functions are only added here if, at the time they're considered, they are
9666 /// not known-emitted. As soon as we discover that a function is
9667 /// known-emitted, we remove it and everything it transitively calls from this
9668 /// set and add those functions to CUDAKnownEmittedFns.
9669 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9670 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9674 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9676 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9677 /// which are not allowed to appear inside __device__ functions and are
9678 /// allowed to appear in __host__ __device__ functions only if the host+device
9679 /// function is never codegen'ed.
9681 /// To handle this, we use the notion of "deferred diagnostics", where we
9682 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9684 /// This class lets you emit either a regular diagnostic, a deferred
9685 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9686 /// its constructor, thus simplifying the process of creating these "maybe
9687 /// deferred" diagnostics.
9688 class CUDADiagBuilder {
9691 /// Emit no diagnostics.
9693 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9695 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9696 /// emit a call stack showing how this function can be reached by an a
9697 /// priori known-emitted function.
9698 K_ImmediateWithCallStack,
9699 /// Create a deferred diagnostic, which is emitted only if the function
9700 /// it's attached to is codegen'ed. Also emit a call stack as with
9701 /// K_ImmediateWithCallStack.
9705 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9706 FunctionDecl *Fn, Sema &S);
9709 /// Convertible to bool: True if we immediately emitted an error, false if
9710 /// we didn't emit an error or we created a deferred error.
9714 /// if (CUDADiagBuilder(...) << foo << bar)
9715 /// return ExprError();
9717 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9718 /// want to use these instead of creating a CUDADiagBuilder yourself.
9719 operator bool() const { return ImmediateDiag.hasValue(); }
9721 template <typename T>
9722 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9724 if (Diag.ImmediateDiag.hasValue())
9725 *Diag.ImmediateDiag << Value;
9726 else if (Diag.PartialDiag.hasValue())
9727 *Diag.PartialDiag << Value;
9738 // Invariant: At most one of these Optionals has a value.
9739 // FIXME: Switch these to a Variant once that exists.
9740 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9741 llvm::Optional<PartialDiagnostic> PartialDiag;
9744 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9745 /// is "used as device code".
9747 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9748 /// - If CurContext is a __device__ or __global__ function, emits the
9749 /// diagnostics immediately.
9750 /// - If CurContext is a __host__ __device__ function and we are compiling for
9751 /// the device, creates a diagnostic which is emitted if and when we realize
9752 /// that the function will be codegen'ed.
9756 /// // Variable-length arrays are not allowed in CUDA device code.
9757 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9758 /// return ExprError();
9759 /// // Otherwise, continue parsing as normal.
9760 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9762 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9763 /// is "used as host code".
9765 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9766 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9768 enum CUDAFunctionTarget {
9776 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9779 /// Use this rather than examining the function's attributes yourself -- you
9780 /// will get it wrong. Returns CFT_Host if D is null.
9781 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9782 bool IgnoreImplicitHDAttr = false);
9783 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9785 /// Gets the CUDA target for the current context.
9786 CUDAFunctionTarget CurrentCUDATarget() {
9787 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9790 // CUDA function call preference. Must be ordered numerically from
9792 enum CUDAFunctionPreference {
9793 CFP_Never, // Invalid caller/callee combination.
9794 CFP_WrongSide, // Calls from host-device to host or device
9795 // function that do not match current compilation
9797 CFP_HostDevice, // Any calls to host/device functions.
9798 CFP_SameSide, // Calls from host-device to host or device
9799 // function matching current compilation mode.
9800 CFP_Native, // host-to-host or device-to-device calls.
9803 /// Identifies relative preference of a given Caller/Callee
9804 /// combination, based on their host/device attributes.
9805 /// \param Caller function which needs address of \p Callee.
9806 /// nullptr in case of global context.
9807 /// \param Callee target function
9809 /// \returns preference value for particular Caller/Callee combination.
9810 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9811 const FunctionDecl *Callee);
9813 /// Determines whether Caller may invoke Callee, based on their CUDA
9814 /// host/device attributes. Returns false if the call is not allowed.
9816 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9817 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9818 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9819 const FunctionDecl *Callee) {
9820 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9823 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9824 /// depending on FD and the current compilation settings.
9825 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9826 const LookupResult &Previous);
9829 /// Check whether we're allowed to call Callee from the current context.
9831 /// - If the call is never allowed in a semantically-correct program
9832 /// (CFP_Never), emits an error and returns false.
9834 /// - If the call is allowed in semantically-correct programs, but only if
9835 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9836 /// be emitted if and when the caller is codegen'ed, and returns true.
9838 /// Will only create deferred diagnostics for a given SourceLocation once,
9839 /// so you can safely call this multiple times without generating duplicate
9840 /// deferred errors.
9842 /// - Otherwise, returns true without emitting any diagnostics.
9843 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9845 /// Set __device__ or __host__ __device__ attributes on the given lambda
9846 /// operator() method.
9848 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9849 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9850 /// functions become __host__ __device__ themselves.
9851 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9853 /// Finds a function in \p Matches with highest calling priority
9854 /// from \p Caller context and erases all functions with lower
9855 /// calling priority.
9856 void EraseUnwantedCUDAMatches(
9857 const FunctionDecl *Caller,
9858 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9860 /// Given a implicit special member, infer its CUDA target from the
9861 /// calls it needs to make to underlying base/field special members.
9862 /// \param ClassDecl the class for which the member is being created.
9863 /// \param CSM the kind of special member.
9864 /// \param MemberDecl the special member itself.
9865 /// \param ConstRHS true if this is a copy operation with a const object on
9867 /// \param Diagnose true if this call should emit diagnostics.
9868 /// \return true if there was an error inferring.
9869 /// The result of this call is implicit CUDA target attribute(s) attached to
9870 /// the member declaration.
9871 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9872 CXXSpecialMember CSM,
9873 CXXMethodDecl *MemberDecl,
9877 /// \return true if \p CD can be considered empty according to CUDA
9878 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9879 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9880 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9882 /// Check whether NewFD is a valid overload for CUDA. Emits
9883 /// diagnostics and invalidates NewFD if not.
9884 void checkCUDATargetOverload(FunctionDecl *NewFD,
9885 const LookupResult &Previous);
9886 /// Copies target attributes from the template TD to the function FD.
9887 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9889 /// \name Code completion
9891 /// \brief Describes the context in which code completion occurs.
9892 enum ParserCompletionContext {
9893 /// \brief Code completion occurs at top-level or namespace context.
9895 /// \brief Code completion occurs within a class, struct, or union.
9897 /// \brief Code completion occurs within an Objective-C interface, protocol,
9900 /// \brief Code completion occurs within an Objective-C implementation or
9901 /// category implementation
9902 PCC_ObjCImplementation,
9903 /// \brief Code completion occurs within the list of instance variables
9904 /// in an Objective-C interface, protocol, category, or implementation.
9905 PCC_ObjCInstanceVariableList,
9906 /// \brief Code completion occurs following one or more template
9909 /// \brief Code completion occurs following one or more template
9910 /// headers within a class.
9912 /// \brief Code completion occurs within an expression.
9914 /// \brief Code completion occurs within a statement, which may
9915 /// also be an expression or a declaration.
9917 /// \brief Code completion occurs at the beginning of the
9918 /// initialization statement (or expression) in a for loop.
9920 /// \brief Code completion occurs within the condition of an if,
9921 /// while, switch, or for statement.
9923 /// \brief Code completion occurs within the body of a function on a
9924 /// recovery path, where we do not have a specific handle on our position
9926 PCC_RecoveryInFunction,
9927 /// \brief Code completion occurs where only a type is permitted.
9929 /// \brief Code completion occurs in a parenthesized expression, which
9930 /// might also be a type cast.
9931 PCC_ParenthesizedExpression,
9932 /// \brief Code completion occurs within a sequence of declaration
9933 /// specifiers within a function, method, or block.
9934 PCC_LocalDeclarationSpecifiers
9937 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9938 void CodeCompleteOrdinaryName(Scope *S,
9939 ParserCompletionContext CompletionContext);
9940 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9941 bool AllowNonIdentifiers,
9942 bool AllowNestedNameSpecifiers);
9944 struct CodeCompleteExpressionData;
9945 void CodeCompleteExpression(Scope *S,
9946 const CodeCompleteExpressionData &Data);
9947 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9948 SourceLocation OpLoc, bool IsArrow,
9949 bool IsBaseExprStatement);
9950 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9951 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9952 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9953 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9954 const VirtSpecifiers *VS = nullptr);
9955 void CodeCompleteBracketDeclarator(Scope *S);
9956 void CodeCompleteCase(Scope *S);
9957 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9958 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9959 ArrayRef<Expr *> Args);
9960 void CodeCompleteInitializer(Scope *S, Decl *D);
9961 void CodeCompleteReturn(Scope *S);
9962 void CodeCompleteAfterIf(Scope *S);
9963 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9965 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9966 bool EnteringContext);
9967 void CodeCompleteUsing(Scope *S);
9968 void CodeCompleteUsingDirective(Scope *S);
9969 void CodeCompleteNamespaceDecl(Scope *S);
9970 void CodeCompleteNamespaceAliasDecl(Scope *S);
9971 void CodeCompleteOperatorName(Scope *S);
9972 void CodeCompleteConstructorInitializer(
9974 ArrayRef<CXXCtorInitializer *> Initializers);
9976 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9977 bool AfterAmpersand);
9979 void CodeCompleteObjCAtDirective(Scope *S);
9980 void CodeCompleteObjCAtVisibility(Scope *S);
9981 void CodeCompleteObjCAtStatement(Scope *S);
9982 void CodeCompleteObjCAtExpression(Scope *S);
9983 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9984 void CodeCompleteObjCPropertyGetter(Scope *S);
9985 void CodeCompleteObjCPropertySetter(Scope *S);
9986 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9988 void CodeCompleteObjCMessageReceiver(Scope *S);
9989 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9990 ArrayRef<IdentifierInfo *> SelIdents,
9991 bool AtArgumentExpression);
9992 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9993 ArrayRef<IdentifierInfo *> SelIdents,
9994 bool AtArgumentExpression,
9995 bool IsSuper = false);
9996 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9997 ArrayRef<IdentifierInfo *> SelIdents,
9998 bool AtArgumentExpression,
9999 ObjCInterfaceDecl *Super = nullptr);
10000 void CodeCompleteObjCForCollection(Scope *S,
10001 DeclGroupPtrTy IterationVar);
10002 void CodeCompleteObjCSelector(Scope *S,
10003 ArrayRef<IdentifierInfo *> SelIdents);
10004 void CodeCompleteObjCProtocolReferences(
10005 ArrayRef<IdentifierLocPair> Protocols);
10006 void CodeCompleteObjCProtocolDecl(Scope *S);
10007 void CodeCompleteObjCInterfaceDecl(Scope *S);
10008 void CodeCompleteObjCSuperclass(Scope *S,
10009 IdentifierInfo *ClassName,
10010 SourceLocation ClassNameLoc);
10011 void CodeCompleteObjCImplementationDecl(Scope *S);
10012 void CodeCompleteObjCInterfaceCategory(Scope *S,
10013 IdentifierInfo *ClassName,
10014 SourceLocation ClassNameLoc);
10015 void CodeCompleteObjCImplementationCategory(Scope *S,
10016 IdentifierInfo *ClassName,
10017 SourceLocation ClassNameLoc);
10018 void CodeCompleteObjCPropertyDefinition(Scope *S);
10019 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10020 IdentifierInfo *PropertyName);
10021 void CodeCompleteObjCMethodDecl(Scope *S,
10022 bool IsInstanceMethod,
10023 ParsedType ReturnType);
10024 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10025 bool IsInstanceMethod,
10026 bool AtParameterName,
10027 ParsedType ReturnType,
10028 ArrayRef<IdentifierInfo *> SelIdents);
10029 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10030 SourceLocation ClassNameLoc,
10031 bool IsBaseExprStatement);
10032 void CodeCompletePreprocessorDirective(bool InConditional);
10033 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10034 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10035 void CodeCompletePreprocessorExpression();
10036 void CodeCompletePreprocessorMacroArgument(Scope *S,
10037 IdentifierInfo *Macro,
10038 MacroInfo *MacroInfo,
10039 unsigned Argument);
10040 void CodeCompleteNaturalLanguage();
10041 void CodeCompleteAvailabilityPlatformName();
10042 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10043 CodeCompletionTUInfo &CCTUInfo,
10044 SmallVectorImpl<CodeCompletionResult> &Results);
10047 //===--------------------------------------------------------------------===//
10048 // Extra semantic analysis beyond the C type system
10051 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10052 unsigned ByteNo) const;
10055 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10056 const ArraySubscriptExpr *ASE=nullptr,
10057 bool AllowOnePastEnd=true, bool IndexNegated=false);
10058 void CheckArrayAccess(const Expr *E);
10059 // Used to grab the relevant information from a FormatAttr and a
10060 // FunctionDeclaration.
10061 struct FormatStringInfo {
10062 unsigned FormatIdx;
10063 unsigned FirstDataArg;
10067 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10068 FormatStringInfo *FSI);
10069 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10070 const FunctionProtoType *Proto);
10071 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10072 ArrayRef<const Expr *> Args);
10073 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10074 const FunctionProtoType *Proto);
10075 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10076 void CheckConstructorCall(FunctionDecl *FDecl,
10077 ArrayRef<const Expr *> Args,
10078 const FunctionProtoType *Proto,
10079 SourceLocation Loc);
10081 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10082 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10083 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10084 VariadicCallType CallType);
10086 bool CheckObjCString(Expr *Arg);
10087 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10089 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10090 unsigned BuiltinID, CallExpr *TheCall);
10092 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10093 unsigned MaxWidth);
10094 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10095 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10097 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10098 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10099 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10100 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10101 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10102 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10103 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10105 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10106 bool SemaBuiltinVAStartARM(CallExpr *Call);
10107 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10108 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10109 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10112 // Used by C++ template instantiation.
10113 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10114 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10115 SourceLocation BuiltinLoc,
10116 SourceLocation RParenLoc);
10119 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10120 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10121 bool SemaBuiltinAssume(CallExpr *TheCall);
10122 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10123 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10124 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10125 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10126 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10127 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10128 AtomicExpr::AtomicOp Op);
10129 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10130 llvm::APSInt &Result);
10131 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10132 int Low, int High);
10133 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10134 unsigned Multiple);
10135 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10136 int ArgNum, unsigned ExpectedFieldNum,
10139 enum FormatStringType {
10146 FST_FreeBSDKPrintf,
10151 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10153 bool FormatStringHasSArg(const StringLiteral *FExpr);
10155 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10158 bool CheckFormatArguments(const FormatAttr *Format,
10159 ArrayRef<const Expr *> Args,
10161 VariadicCallType CallType,
10162 SourceLocation Loc, SourceRange Range,
10163 llvm::SmallBitVector &CheckedVarArgs);
10164 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10165 bool HasVAListArg, unsigned format_idx,
10166 unsigned firstDataArg, FormatStringType Type,
10167 VariadicCallType CallType,
10168 SourceLocation Loc, SourceRange range,
10169 llvm::SmallBitVector &CheckedVarArgs);
10171 void CheckAbsoluteValueFunction(const CallExpr *Call,
10172 const FunctionDecl *FDecl);
10174 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10176 void CheckMemaccessArguments(const CallExpr *Call,
10178 IdentifierInfo *FnName);
10180 void CheckStrlcpycatArguments(const CallExpr *Call,
10181 IdentifierInfo *FnName);
10183 void CheckStrncatArguments(const CallExpr *Call,
10184 IdentifierInfo *FnName);
10186 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10187 SourceLocation ReturnLoc,
10188 bool isObjCMethod = false,
10189 const AttrVec *Attrs = nullptr,
10190 const FunctionDecl *FD = nullptr);
10192 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10193 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10194 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10195 void CheckUnsequencedOperations(Expr *E);
10197 /// \brief Perform semantic checks on a completed expression. This will either
10198 /// be a full-expression or a default argument expression.
10199 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10200 bool IsConstexpr = false);
10202 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10205 /// Check if there is a field shadowing.
10206 void CheckShadowInheritedFields(const SourceLocation &Loc,
10207 DeclarationName FieldName,
10208 const CXXRecordDecl *RD);
10210 /// \brief Check if the given expression contains 'break' or 'continue'
10211 /// statement that produces control flow different from GCC.
10212 void CheckBreakContinueBinding(Expr *E);
10214 /// \brief Check whether receiver is mutable ObjC container which
10215 /// attempts to add itself into the container
10216 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10218 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10219 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10220 bool DeleteWasArrayForm);
10222 /// \brief Register a magic integral constant to be used as a type tag.
10223 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10224 uint64_t MagicValue, QualType Type,
10225 bool LayoutCompatible, bool MustBeNull);
10227 struct TypeTagData {
10230 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10231 Type(Type), LayoutCompatible(LayoutCompatible),
10232 MustBeNull(MustBeNull)
10237 /// If true, \c Type should be compared with other expression's types for
10238 /// layout-compatibility.
10239 unsigned LayoutCompatible : 1;
10240 unsigned MustBeNull : 1;
10243 /// A pair of ArgumentKind identifier and magic value. This uniquely
10244 /// identifies the magic value.
10245 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10248 /// \brief A map from magic value to type information.
10249 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10250 TypeTagForDatatypeMagicValues;
10252 /// \brief Peform checks on a call of a function with argument_with_type_tag
10253 /// or pointer_with_type_tag attributes.
10254 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10255 const Expr * const *ExprArgs);
10257 /// \brief Check if we are taking the address of a packed field
10258 /// as this may be a problem if the pointer value is dereferenced.
10259 void CheckAddressOfPackedMember(Expr *rhs);
10261 /// \brief The parser's current scope.
10263 /// The parser maintains this state here.
10266 mutable IdentifierInfo *Ident_super;
10267 mutable IdentifierInfo *Ident___float128;
10269 /// Nullability type specifiers.
10270 IdentifierInfo *Ident__Nonnull = nullptr;
10271 IdentifierInfo *Ident__Nullable = nullptr;
10272 IdentifierInfo *Ident__Null_unspecified = nullptr;
10274 IdentifierInfo *Ident_NSError = nullptr;
10277 friend class Parser;
10278 friend class InitializationSequence;
10279 friend class ASTReader;
10280 friend class ASTDeclReader;
10281 friend class ASTWriter;
10284 /// Retrieve the keyword associated
10285 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10287 /// The struct behind the CFErrorRef pointer.
10288 RecordDecl *CFError = nullptr;
10290 /// Retrieve the identifier "NSError".
10291 IdentifierInfo *getNSErrorIdent();
10293 /// \brief Retrieve the parser's current scope.
10295 /// This routine must only be used when it is certain that semantic analysis
10296 /// and the parser are in precisely the same context, which is not the case
10297 /// when, e.g., we are performing any kind of template instantiation.
10298 /// Therefore, the only safe places to use this scope are in the parser
10299 /// itself and in routines directly invoked from the parser and *never* from
10300 /// template substitution or instantiation.
10301 Scope *getCurScope() const { return CurScope; }
10303 void incrementMSManglingNumber() const {
10304 return CurScope->incrementMSManglingNumber();
10307 IdentifierInfo *getSuperIdentifier() const;
10308 IdentifierInfo *getFloat128Identifier() const;
10310 Decl *getObjCDeclContext() const;
10312 DeclContext *getCurLexicalContext() const {
10313 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10316 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10318 /// \param D The declaration to check. Note that this may be altered to point
10319 /// to another declaration that \c D gets it's availability from. i.e., we
10320 /// walk the list of typedefs to find an availability attribute.
10322 /// \param Message If non-null, this will be populated with the message from
10323 /// the availability attribute that is selected.
10324 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10325 std::string *Message);
10327 const DeclContext *getCurObjCLexicalContext() const {
10328 const DeclContext *DC = getCurLexicalContext();
10329 // A category implicitly has the attribute of the interface.
10330 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10331 DC = CatD->getClassInterface();
10335 /// \brief To be used for checking whether the arguments being passed to
10336 /// function exceeds the number of parameters expected for it.
10337 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10338 bool PartialOverloading = false) {
10339 // We check whether we're just after a comma in code-completion.
10340 if (NumArgs > 0 && PartialOverloading)
10341 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10342 return NumArgs > NumParams;
10345 // Emitting members of dllexported classes is delayed until the class
10346 // (including field initializers) is fully parsed.
10347 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10350 /// \brief Helper class that collects misaligned member designations and
10351 /// their location info for delayed diagnostics.
10352 struct MisalignedMember {
10356 CharUnits Alignment;
10358 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10359 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10360 CharUnits Alignment)
10361 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10362 explicit MisalignedMember(Expr *E)
10363 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10365 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10367 /// \brief Small set of gathered accesses to potentially misaligned members
10368 /// due to the packed attribute.
10369 SmallVector<MisalignedMember, 4> MisalignedMembers;
10371 /// \brief Adds an expression to the set of gathered misaligned members.
10372 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10373 CharUnits Alignment);
10376 /// \brief Diagnoses the current set of gathered accesses. This typically
10377 /// happens at full expression level. The set is cleared after emitting the
10379 void DiagnoseMisalignedMembers();
10381 /// \brief This function checks if the expression is in the sef of potentially
10382 /// misaligned members and it is converted to some pointer type T with lower
10383 /// or equal alignment requirements. If so it removes it. This is used when
10384 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10386 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10388 /// \brief This function calls Action when it determines that E designates a
10389 /// misaligned member due to the packed attribute. This is used to emit
10390 /// local diagnostics like in reference binding.
10391 void RefersToMemberWithReducedAlignment(
10393 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10397 /// \brief RAII object that enters a new expression evaluation context.
10398 class EnterExpressionEvaluationContext {
10400 bool Entered = true;
10404 EnterExpressionEvaluationContext(Sema &Actions,
10405 Sema::ExpressionEvaluationContext NewContext,
10406 Decl *LambdaContextDecl = nullptr,
10407 bool IsDecltype = false,
10408 bool ShouldEnter = true)
10409 : Actions(Actions), Entered(ShouldEnter) {
10411 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10414 EnterExpressionEvaluationContext(Sema &Actions,
10415 Sema::ExpressionEvaluationContext NewContext,
10416 Sema::ReuseLambdaContextDecl_t,
10417 bool IsDecltype = false)
10418 : Actions(Actions) {
10419 Actions.PushExpressionEvaluationContext(NewContext,
10420 Sema::ReuseLambdaContextDecl,
10424 enum InitListTag { InitList };
10425 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10426 bool ShouldEnter = true)
10427 : Actions(Actions), Entered(false) {
10428 // In C++11 onwards, narrowing checks are performed on the contents of
10429 // braced-init-lists, even when they occur within unevaluated operands.
10430 // Therefore we still need to instantiate constexpr functions used in such
10432 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10433 Actions.getLangOpts().CPlusPlus11) {
10434 Actions.PushExpressionEvaluationContext(
10435 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10440 ~EnterExpressionEvaluationContext() {
10442 Actions.PopExpressionEvaluationContext();
10446 DeductionFailureInfo
10447 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10448 sema::TemplateDeductionInfo &Info);
10450 /// \brief Contains a late templated function.
10451 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10452 struct LateParsedTemplate {
10454 /// \brief The template function declaration to be late parsed.
10458 } // end namespace clang
10461 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10463 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10464 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10465 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10467 static FunctionDeclAndLoc getEmptyKey() {
10468 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10471 static FunctionDeclAndLoc getTombstoneKey() {
10472 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10475 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10476 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10477 FDL.Loc.getRawEncoding());
10480 static bool isEqual(const FunctionDeclAndLoc &LHS,
10481 const FunctionDeclAndLoc &RHS) {
10482 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10485 } // namespace llvm