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;
1470 Module *CachedFakeTopLevelModule;
1473 /// \brief Get the module owning an entity.
1474 Module *getOwningModule(Decl *Entity);
1476 /// \brief Make a merged definition of an existing hidden definition \p ND
1477 /// visible at the specified location.
1478 void makeMergedDefinitionVisible(NamedDecl *ND);
1480 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1482 /// Determine whether a declaration is visible to name lookup.
1483 bool isVisible(const NamedDecl *D) {
1484 return !D->isHidden() || isVisibleSlow(D);
1487 /// Determine whether any declaration of an entity is visible.
1489 hasVisibleDeclaration(const NamedDecl *D,
1490 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1491 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1493 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1494 llvm::SmallVectorImpl<Module *> *Modules);
1496 bool hasVisibleMergedDefinition(NamedDecl *Def);
1498 /// Determine if \p D has a visible definition. If not, suggest a declaration
1499 /// that should be made visible to expose the definition.
1500 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1501 bool OnlyNeedComplete = false);
1502 bool hasVisibleDefinition(const NamedDecl *D) {
1504 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1507 /// Determine if the template parameter \p D has a visible default argument.
1509 hasVisibleDefaultArgument(const NamedDecl *D,
1510 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1512 /// Determine if there is a visible declaration of \p D that is a member
1513 /// specialization declaration (as opposed to an instantiated declaration).
1514 bool hasVisibleMemberSpecialization(
1515 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1517 /// Determine if \p A and \p B are equivalent internal linkage declarations
1518 /// from different modules, and thus an ambiguity error can be downgraded to
1519 /// an extension warning.
1520 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1521 const NamedDecl *B);
1522 void diagnoseEquivalentInternalLinkageDeclarations(
1523 SourceLocation Loc, const NamedDecl *D,
1524 ArrayRef<const NamedDecl *> Equiv);
1526 bool isCompleteType(SourceLocation Loc, QualType T) {
1527 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1529 bool RequireCompleteType(SourceLocation Loc, QualType T,
1530 TypeDiagnoser &Diagnoser);
1531 bool RequireCompleteType(SourceLocation Loc, QualType T,
1534 template <typename... Ts>
1535 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1536 const Ts &...Args) {
1537 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1538 return RequireCompleteType(Loc, T, Diagnoser);
1541 void completeExprArrayBound(Expr *E);
1542 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1543 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1545 template <typename... Ts>
1546 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1547 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1548 return RequireCompleteExprType(E, Diagnoser);
1551 bool RequireLiteralType(SourceLocation Loc, QualType T,
1552 TypeDiagnoser &Diagnoser);
1553 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1555 template <typename... Ts>
1556 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1557 const Ts &...Args) {
1558 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1559 return RequireLiteralType(Loc, T, Diagnoser);
1562 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1563 const CXXScopeSpec &SS, QualType T);
1565 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1566 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1567 /// context, such as when building a type for decltype(auto).
1568 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1569 bool AsUnevaluated = true);
1570 QualType BuildUnaryTransformType(QualType BaseType,
1571 UnaryTransformType::UTTKind UKind,
1572 SourceLocation Loc);
1574 //===--------------------------------------------------------------------===//
1575 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1578 struct SkipBodyInfo {
1579 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1581 NamedDecl *Previous;
1584 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1586 void DiagnoseUseOfUnimplementedSelectors();
1588 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1590 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1591 Scope *S, CXXScopeSpec *SS = nullptr,
1592 bool isClassName = false, bool HasTrailingDot = false,
1593 ParsedType ObjectType = nullptr,
1594 bool IsCtorOrDtorName = false,
1595 bool WantNontrivialTypeSourceInfo = false,
1596 bool IsClassTemplateDeductionContext = true,
1597 IdentifierInfo **CorrectedII = nullptr);
1598 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1599 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1600 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1601 SourceLocation IILoc,
1604 ParsedType &SuggestedType,
1605 bool IsTemplateName = false);
1607 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1608 /// type name has failed in a dependent context. In these situations, we
1609 /// automatically form a DependentTypeName that will retry lookup in a related
1610 /// scope during instantiation.
1611 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1612 SourceLocation NameLoc,
1613 bool IsTemplateTypeArg);
1615 /// \brief Describes the result of the name lookup and resolution performed
1616 /// by \c ClassifyName().
1617 enum NameClassificationKind {
1623 NC_NestedNameSpecifier,
1629 class NameClassification {
1630 NameClassificationKind Kind;
1632 TemplateName Template;
1634 const IdentifierInfo *Keyword;
1636 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1639 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1641 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1643 NameClassification(const IdentifierInfo *Keyword)
1644 : Kind(NC_Keyword), Keyword(Keyword) { }
1646 static NameClassification Error() {
1647 return NameClassification(NC_Error);
1650 static NameClassification Unknown() {
1651 return NameClassification(NC_Unknown);
1654 static NameClassification NestedNameSpecifier() {
1655 return NameClassification(NC_NestedNameSpecifier);
1658 static NameClassification TypeTemplate(TemplateName Name) {
1659 NameClassification Result(NC_TypeTemplate);
1660 Result.Template = Name;
1664 static NameClassification VarTemplate(TemplateName Name) {
1665 NameClassification Result(NC_VarTemplate);
1666 Result.Template = Name;
1670 static NameClassification FunctionTemplate(TemplateName Name) {
1671 NameClassification Result(NC_FunctionTemplate);
1672 Result.Template = Name;
1676 NameClassificationKind getKind() const { return Kind; }
1678 ParsedType getType() const {
1679 assert(Kind == NC_Type);
1683 ExprResult getExpression() const {
1684 assert(Kind == NC_Expression);
1688 TemplateName getTemplateName() const {
1689 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1690 Kind == NC_VarTemplate);
1694 TemplateNameKind getTemplateNameKind() const {
1696 case NC_TypeTemplate:
1697 return TNK_Type_template;
1698 case NC_FunctionTemplate:
1699 return TNK_Function_template;
1700 case NC_VarTemplate:
1701 return TNK_Var_template;
1703 llvm_unreachable("unsupported name classification.");
1708 /// \brief Perform name lookup on the given name, classifying it based on
1709 /// the results of name lookup and the following token.
1711 /// This routine is used by the parser to resolve identifiers and help direct
1712 /// parsing. When the identifier cannot be found, this routine will attempt
1713 /// to correct the typo and classify based on the resulting name.
1715 /// \param S The scope in which we're performing name lookup.
1717 /// \param SS The nested-name-specifier that precedes the name.
1719 /// \param Name The identifier. If typo correction finds an alternative name,
1720 /// this pointer parameter will be updated accordingly.
1722 /// \param NameLoc The location of the identifier.
1724 /// \param NextToken The token following the identifier. Used to help
1725 /// disambiguate the name.
1727 /// \param IsAddressOfOperand True if this name is the operand of a unary
1728 /// address of ('&') expression, assuming it is classified as an
1731 /// \param CCC The correction callback, if typo correction is desired.
1733 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1734 SourceLocation NameLoc, const Token &NextToken,
1735 bool IsAddressOfOperand,
1736 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1738 /// Describes the detailed kind of a template name. Used in diagnostics.
1739 enum class TemplateNameKindForDiagnostics {
1744 TemplateTemplateParam,
1747 TemplateNameKindForDiagnostics
1748 getTemplateNameKindForDiagnostics(TemplateName Name);
1750 /// Determine whether it's plausible that E was intended to be a
1752 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1753 if (!getLangOpts().CPlusPlus || E.isInvalid())
1755 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1756 return !DRE->hasExplicitTemplateArgs();
1757 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1758 return !ME->hasExplicitTemplateArgs();
1759 // Any additional cases recognized here should also be handled by
1760 // diagnoseExprIntendedAsTemplateName.
1763 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1764 SourceLocation Less,
1765 SourceLocation Greater);
1767 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1769 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1770 MultiTemplateParamsArg TemplateParameterLists);
1771 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1772 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1773 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1774 DeclarationName Name,
1775 SourceLocation Loc);
1777 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1778 SourceLocation FallbackLoc,
1779 SourceLocation ConstQualLoc = SourceLocation(),
1780 SourceLocation VolatileQualLoc = SourceLocation(),
1781 SourceLocation RestrictQualLoc = SourceLocation(),
1782 SourceLocation AtomicQualLoc = SourceLocation(),
1783 SourceLocation UnalignedQualLoc = SourceLocation());
1785 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1786 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1787 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1788 const LookupResult &R);
1789 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1790 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1791 const LookupResult &R);
1792 void CheckShadow(Scope *S, VarDecl *D);
1794 /// Warn if 'E', which is an expression that is about to be modified, refers
1795 /// to a shadowing declaration.
1796 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1798 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1801 /// Map of current shadowing declarations to shadowed declarations. Warn if
1802 /// it looks like the user is trying to modify the shadowing declaration.
1803 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1806 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1807 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1808 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1809 TypedefNameDecl *NewTD);
1810 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1811 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1812 TypeSourceInfo *TInfo,
1813 LookupResult &Previous);
1814 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1815 LookupResult &Previous, bool &Redeclaration);
1816 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1817 TypeSourceInfo *TInfo,
1818 LookupResult &Previous,
1819 MultiTemplateParamsArg TemplateParamLists,
1821 ArrayRef<BindingDecl *> Bindings = None);
1823 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1824 MultiTemplateParamsArg TemplateParamLists);
1825 // Returns true if the variable declaration is a redeclaration
1826 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1827 void CheckVariableDeclarationType(VarDecl *NewVD);
1828 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1830 void CheckCompleteVariableDeclaration(VarDecl *VD);
1831 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1832 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1834 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1835 TypeSourceInfo *TInfo,
1836 LookupResult &Previous,
1837 MultiTemplateParamsArg TemplateParamLists,
1839 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1841 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1842 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1844 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1845 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1846 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1847 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1848 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1849 // Returns true if the function declaration is a redeclaration
1850 bool CheckFunctionDeclaration(Scope *S,
1851 FunctionDecl *NewFD, LookupResult &Previous,
1852 bool IsMemberSpecialization);
1853 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1854 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1855 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1856 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1857 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1860 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1861 SourceLocation NameLoc, IdentifierInfo *Name,
1862 QualType T, TypeSourceInfo *TSInfo,
1864 void ActOnParamDefaultArgument(Decl *param,
1865 SourceLocation EqualLoc,
1867 void ActOnParamUnparsedDefaultArgument(Decl *param,
1868 SourceLocation EqualLoc,
1869 SourceLocation ArgLoc);
1870 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1871 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1872 SourceLocation EqualLoc);
1874 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1875 void ActOnUninitializedDecl(Decl *dcl);
1876 void ActOnInitializerError(Decl *Dcl);
1878 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1879 void ActOnCXXForRangeDecl(Decl *D);
1880 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1881 IdentifierInfo *Ident,
1882 ParsedAttributes &Attrs,
1883 SourceLocation AttrEnd);
1884 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1885 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1886 void FinalizeDeclaration(Decl *D);
1887 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1888 ArrayRef<Decl *> Group);
1889 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1891 /// Should be called on all declarations that might have attached
1892 /// documentation comments.
1893 void ActOnDocumentableDecl(Decl *D);
1894 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1896 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1897 SourceLocation LocAfterDecls);
1898 void CheckForFunctionRedefinition(
1899 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1900 SkipBodyInfo *SkipBody = nullptr);
1901 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1902 MultiTemplateParamsArg TemplateParamLists,
1903 SkipBodyInfo *SkipBody = nullptr);
1904 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1905 SkipBodyInfo *SkipBody = nullptr);
1906 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1907 bool isObjCMethodDecl(Decl *D) {
1908 return D && isa<ObjCMethodDecl>(D);
1911 /// \brief Determine whether we can delay parsing the body of a function or
1912 /// function template until it is used, assuming we don't care about emitting
1913 /// code for that function.
1915 /// This will be \c false if we may need the body of the function in the
1916 /// middle of parsing an expression (where it's impractical to switch to
1917 /// parsing a different function), for instance, if it's constexpr in C++11
1918 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1919 bool canDelayFunctionBody(const Declarator &D);
1921 /// \brief Determine whether we can skip parsing the body of a function
1922 /// definition, assuming we don't care about analyzing its body or emitting
1923 /// code for that function.
1925 /// This will be \c false only if we may need the body of the function in
1926 /// order to parse the rest of the program (for instance, if it is
1927 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1928 bool canSkipFunctionBody(Decl *D);
1930 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1931 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1932 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1933 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1934 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1936 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1937 /// attribute for which parsing is delayed.
1938 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1940 /// \brief Diagnose any unused parameters in the given sequence of
1941 /// ParmVarDecl pointers.
1942 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1944 /// \brief Diagnose whether the size of parameters or return value of a
1945 /// function or obj-c method definition is pass-by-value and larger than a
1946 /// specified threshold.
1948 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1949 QualType ReturnTy, NamedDecl *D);
1951 void DiagnoseInvalidJumps(Stmt *Body);
1952 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1953 SourceLocation AsmLoc,
1954 SourceLocation RParenLoc);
1956 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1957 Decl *ActOnEmptyDeclaration(Scope *S,
1958 AttributeList *AttrList,
1959 SourceLocation SemiLoc);
1961 enum class ModuleDeclKind {
1962 Module, ///< 'module X;'
1963 Partition, ///< 'module partition X;'
1964 Implementation, ///< 'module implementation X;'
1967 /// The parser has processed a module-declaration that begins the definition
1968 /// of a module interface or implementation.
1969 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
1970 SourceLocation ModuleLoc, ModuleDeclKind MDK,
1973 /// \brief The parser has processed a module import declaration.
1975 /// \param AtLoc The location of the '@' symbol, if any.
1977 /// \param ImportLoc The location of the 'import' keyword.
1979 /// \param Path The module access path.
1980 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1983 /// \brief The parser has processed a module import translated from a
1984 /// #include or similar preprocessing directive.
1985 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1986 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1988 /// \brief The parsed has entered a submodule.
1989 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1990 /// \brief The parser has left a submodule.
1991 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1993 /// \brief Create an implicit import of the given module at the given
1994 /// source location, for error recovery, if possible.
1996 /// This routine is typically used when an entity found by name lookup
1997 /// is actually hidden within a module that we know about but the user
1998 /// has forgotten to import.
1999 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2002 /// Kinds of missing import. Note, the values of these enumerators correspond
2003 /// to %select values in diagnostics.
2004 enum class MissingImportKind {
2008 ExplicitSpecialization,
2009 PartialSpecialization
2012 /// \brief Diagnose that the specified declaration needs to be visible but
2013 /// isn't, and suggest a module import that would resolve the problem.
2014 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2015 MissingImportKind MIK, bool Recover = true);
2016 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2017 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2018 MissingImportKind MIK, bool Recover);
2020 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2021 SourceLocation LBraceLoc);
2022 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2023 SourceLocation RBraceLoc);
2025 /// \brief We've found a use of a templated declaration that would trigger an
2026 /// implicit instantiation. Check that any relevant explicit specializations
2027 /// and partial specializations are visible, and diagnose if not.
2028 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2030 /// \brief We've found a use of a template specialization that would select a
2031 /// partial specialization. Check that the partial specialization is visible,
2032 /// and diagnose if not.
2033 void checkPartialSpecializationVisibility(SourceLocation Loc,
2036 /// \brief Retrieve a suitable printing policy.
2037 PrintingPolicy getPrintingPolicy() const {
2038 return getPrintingPolicy(Context, PP);
2041 /// \brief Retrieve a suitable printing policy.
2042 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2043 const Preprocessor &PP);
2046 void ActOnPopScope(SourceLocation Loc, Scope *S);
2047 void ActOnTranslationUnitScope(Scope *S);
2049 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2050 RecordDecl *&AnonRecord);
2051 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2052 MultiTemplateParamsArg TemplateParams,
2053 bool IsExplicitInstantiation,
2054 RecordDecl *&AnonRecord);
2056 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2059 const PrintingPolicy &Policy);
2061 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2062 RecordDecl *Record);
2064 /// Common ways to introduce type names without a tag for use in diagnostics.
2065 /// Keep in sync with err_tag_reference_non_tag.
2074 NTK_TypeAliasTemplate,
2075 NTK_TemplateTemplateArgument,
2078 /// Given a non-tag type declaration, returns an enum useful for indicating
2079 /// what kind of non-tag type this is.
2080 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2082 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2083 TagTypeKind NewTag, bool isDefinition,
2084 SourceLocation NewTagLoc,
2085 const IdentifierInfo *Name);
2088 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2089 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2090 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2091 TUK_Friend // Friend declaration: 'friend struct foo;'
2094 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2095 SourceLocation KWLoc, CXXScopeSpec &SS,
2096 IdentifierInfo *Name, SourceLocation NameLoc,
2097 AttributeList *Attr, AccessSpecifier AS,
2098 SourceLocation ModulePrivateLoc,
2099 MultiTemplateParamsArg TemplateParameterLists,
2100 bool &OwnedDecl, bool &IsDependent,
2101 SourceLocation ScopedEnumKWLoc,
2102 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2103 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2105 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2106 unsigned TagSpec, SourceLocation TagLoc,
2108 IdentifierInfo *Name, SourceLocation NameLoc,
2109 AttributeList *Attr,
2110 MultiTemplateParamsArg TempParamLists);
2112 TypeResult ActOnDependentTag(Scope *S,
2115 const CXXScopeSpec &SS,
2116 IdentifierInfo *Name,
2117 SourceLocation TagLoc,
2118 SourceLocation NameLoc);
2120 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2121 IdentifierInfo *ClassName,
2122 SmallVectorImpl<Decl *> &Decls);
2123 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2124 Declarator &D, Expr *BitfieldWidth);
2126 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2127 Declarator &D, Expr *BitfieldWidth,
2128 InClassInitStyle InitStyle,
2129 AccessSpecifier AS);
2130 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2131 SourceLocation DeclStart,
2132 Declarator &D, Expr *BitfieldWidth,
2133 InClassInitStyle InitStyle,
2135 AttributeList *MSPropertyAttr);
2137 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2138 TypeSourceInfo *TInfo,
2139 RecordDecl *Record, SourceLocation Loc,
2140 bool Mutable, Expr *BitfieldWidth,
2141 InClassInitStyle InitStyle,
2142 SourceLocation TSSL,
2143 AccessSpecifier AS, NamedDecl *PrevDecl,
2144 Declarator *D = nullptr);
2146 bool CheckNontrivialField(FieldDecl *FD);
2147 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2148 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2149 bool Diagnose = false);
2150 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2151 void ActOnLastBitfield(SourceLocation DeclStart,
2152 SmallVectorImpl<Decl *> &AllIvarDecls);
2153 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2154 Declarator &D, Expr *BitfieldWidth,
2155 tok::ObjCKeywordKind visibility);
2157 // This is used for both record definitions and ObjC interface declarations.
2158 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2159 ArrayRef<Decl *> Fields,
2160 SourceLocation LBrac, SourceLocation RBrac,
2161 AttributeList *AttrList);
2163 /// ActOnTagStartDefinition - Invoked when we have entered the
2164 /// scope of a tag's definition (e.g., for an enumeration, class,
2165 /// struct, or union).
2166 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2168 typedef void *SkippedDefinitionContext;
2170 /// \brief Invoked when we enter a tag definition that we're skipping.
2171 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2173 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2175 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2176 /// C++ record definition's base-specifiers clause and are starting its
2177 /// member declarations.
2178 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2179 SourceLocation FinalLoc,
2180 bool IsFinalSpelledSealed,
2181 SourceLocation LBraceLoc);
2183 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2184 /// the definition of a tag (enumeration, class, struct, or union).
2185 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2186 SourceRange BraceRange);
2188 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2190 void ActOnObjCContainerFinishDefinition();
2192 /// \brief Invoked when we must temporarily exit the objective-c container
2193 /// scope for parsing/looking-up C constructs.
2195 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2196 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2197 void ActOnObjCReenterContainerContext(DeclContext *DC);
2199 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2200 /// error parsing the definition of a tag.
2201 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2203 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2204 EnumConstantDecl *LastEnumConst,
2205 SourceLocation IdLoc,
2208 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2209 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2210 QualType EnumUnderlyingTy,
2211 bool EnumUnderlyingIsImplicit,
2212 const EnumDecl *Prev);
2214 /// Determine whether the body of an anonymous enumeration should be skipped.
2215 /// \param II The name of the first enumerator.
2216 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2217 SourceLocation IILoc);
2219 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2220 SourceLocation IdLoc, IdentifierInfo *Id,
2221 AttributeList *Attrs,
2222 SourceLocation EqualLoc, Expr *Val);
2223 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2225 ArrayRef<Decl *> Elements,
2226 Scope *S, AttributeList *Attr);
2228 DeclContext *getContainingDC(DeclContext *DC);
2230 /// Set the current declaration context until it gets popped.
2231 void PushDeclContext(Scope *S, DeclContext *DC);
2232 void PopDeclContext();
2234 /// EnterDeclaratorContext - Used when we must lookup names in the context
2235 /// of a declarator's nested name specifier.
2236 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2237 void ExitDeclaratorContext(Scope *S);
2239 /// Push the parameters of D, which must be a function, into scope.
2240 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2241 void ActOnExitFunctionContext();
2243 DeclContext *getFunctionLevelDeclContext();
2245 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2246 /// to the function decl for the function being parsed. If we're currently
2247 /// in a 'block', this returns the containing context.
2248 FunctionDecl *getCurFunctionDecl();
2250 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2251 /// the method decl for the method being parsed. If we're currently
2252 /// in a 'block', this returns the containing context.
2253 ObjCMethodDecl *getCurMethodDecl();
2255 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2256 /// or C function we're in, otherwise return null. If we're currently
2257 /// in a 'block', this returns the containing context.
2258 NamedDecl *getCurFunctionOrMethodDecl();
2260 /// Add this decl to the scope shadowed decl chains.
2261 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2263 /// \brief Make the given externally-produced declaration visible at the
2264 /// top level scope.
2266 /// \param D The externally-produced declaration to push.
2268 /// \param Name The name of the externally-produced declaration.
2269 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2271 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2272 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2273 /// true if 'D' belongs to the given declaration context.
2275 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2276 /// enclosing namespace set of the context, rather than contained
2277 /// directly within it.
2278 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2279 bool AllowInlineNamespace = false);
2281 /// Finds the scope corresponding to the given decl context, if it
2282 /// happens to be an enclosing scope. Otherwise return NULL.
2283 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2285 /// Subroutines of ActOnDeclarator().
2286 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2287 TypeSourceInfo *TInfo);
2288 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2290 /// \brief Describes the kind of merge to perform for availability
2291 /// attributes (including "deprecated", "unavailable", and "availability").
2292 enum AvailabilityMergeKind {
2293 /// \brief Don't merge availability attributes at all.
2295 /// \brief Merge availability attributes for a redeclaration, which requires
2298 /// \brief Merge availability attributes for an override, which requires
2299 /// an exact match or a weakening of constraints.
2301 /// \brief Merge availability attributes for an implementation of
2302 /// a protocol requirement.
2303 AMK_ProtocolImplementation,
2306 /// Attribute merging methods. Return true if a new attribute was added.
2307 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2308 IdentifierInfo *Platform,
2310 VersionTuple Introduced,
2311 VersionTuple Deprecated,
2312 VersionTuple Obsoleted,
2315 bool IsStrict, StringRef Replacement,
2316 AvailabilityMergeKind AMK,
2317 unsigned AttrSpellingListIndex);
2318 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2319 TypeVisibilityAttr::VisibilityType Vis,
2320 unsigned AttrSpellingListIndex);
2321 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2322 VisibilityAttr::VisibilityType Vis,
2323 unsigned AttrSpellingListIndex);
2324 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2325 unsigned AttrSpellingListIndex, StringRef Uuid);
2326 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2327 unsigned AttrSpellingListIndex);
2328 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2329 unsigned AttrSpellingListIndex);
2331 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2332 unsigned AttrSpellingListIndex,
2333 MSInheritanceAttr::Spelling SemanticSpelling);
2334 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2335 IdentifierInfo *Format, int FormatIdx,
2336 int FirstArg, unsigned AttrSpellingListIndex);
2337 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2338 unsigned AttrSpellingListIndex);
2339 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2340 IdentifierInfo *Ident,
2341 unsigned AttrSpellingListIndex);
2342 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2343 unsigned AttrSpellingListIndex);
2344 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2345 unsigned AttrSpellingListIndex);
2346 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2347 IdentifierInfo *Ident,
2348 unsigned AttrSpellingListIndex);
2349 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2350 unsigned AttrSpellingListIndex);
2352 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2353 AvailabilityMergeKind AMK = AMK_Redeclaration);
2354 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2355 LookupResult &OldDecls);
2356 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2357 bool MergeTypeWithOld);
2358 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2359 Scope *S, bool MergeTypeWithOld);
2360 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2361 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2362 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2363 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2364 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2365 void notePreviousDefinition(SourceLocation Old, SourceLocation New);
2366 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2368 // AssignmentAction - This is used by all the assignment diagnostic functions
2369 // to represent what is actually causing the operation
2370 enum AssignmentAction {
2378 AA_Passing_CFAudited
2381 /// C++ Overloading.
2383 /// This is a legitimate overload: the existing declarations are
2384 /// functions or function templates with different signatures.
2387 /// This is not an overload because the signature exactly matches
2388 /// an existing declaration.
2391 /// This is not an overload because the lookup results contain a
2395 OverloadKind CheckOverload(Scope *S,
2397 const LookupResult &OldDecls,
2398 NamedDecl *&OldDecl,
2399 bool IsForUsingDecl);
2400 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2401 bool ConsiderCudaAttrs = true);
2403 /// \brief Checks availability of the function depending on the current
2404 /// function context.Inside an unavailable function,unavailability is ignored.
2406 /// \returns true if \p FD is unavailable and current context is inside
2407 /// an available function, false otherwise.
2408 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2410 ImplicitConversionSequence
2411 TryImplicitConversion(Expr *From, QualType ToType,
2412 bool SuppressUserConversions,
2414 bool InOverloadResolution,
2416 bool AllowObjCWritebackConversion);
2418 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2419 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2420 bool IsComplexPromotion(QualType FromType, QualType ToType);
2421 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2422 bool InOverloadResolution,
2423 QualType& ConvertedType, bool &IncompatibleObjC);
2424 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2425 QualType& ConvertedType, bool &IncompatibleObjC);
2426 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2427 QualType &ConvertedType);
2428 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2429 QualType& ConvertedType);
2430 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2431 const FunctionProtoType *NewType,
2432 unsigned *ArgPos = nullptr);
2433 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2434 QualType FromType, QualType ToType);
2436 void maybeExtendBlockObject(ExprResult &E);
2437 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2438 bool CheckPointerConversion(Expr *From, QualType ToType,
2440 CXXCastPath& BasePath,
2441 bool IgnoreBaseAccess,
2442 bool Diagnose = true);
2443 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2444 bool InOverloadResolution,
2445 QualType &ConvertedType);
2446 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2448 CXXCastPath &BasePath,
2449 bool IgnoreBaseAccess);
2450 bool IsQualificationConversion(QualType FromType, QualType ToType,
2451 bool CStyle, bool &ObjCLifetimeConversion);
2452 bool IsFunctionConversion(QualType FromType, QualType ToType,
2453 QualType &ResultTy);
2454 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2455 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2457 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2458 const VarDecl *NRVOCandidate,
2459 QualType ResultType,
2461 bool AllowNRVO = true);
2463 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2465 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2466 SourceLocation EqualLoc,
2468 bool TopLevelOfInitList = false,
2469 bool AllowExplicit = false);
2470 ExprResult PerformObjectArgumentInitialization(Expr *From,
2471 NestedNameSpecifier *Qualifier,
2472 NamedDecl *FoundDecl,
2473 CXXMethodDecl *Method);
2475 ExprResult PerformContextuallyConvertToBool(Expr *From);
2476 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2478 /// Contexts in which a converted constant expression is required.
2480 CCEK_CaseValue, ///< Expression in a case label.
2481 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2482 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2483 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2484 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2486 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2487 llvm::APSInt &Value, CCEKind CCE);
2488 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2489 APValue &Value, CCEKind CCE);
2491 /// \brief Abstract base class used to perform a contextual implicit
2492 /// conversion from an expression to any type passing a filter.
2493 class ContextualImplicitConverter {
2496 bool SuppressConversion;
2498 ContextualImplicitConverter(bool Suppress = false,
2499 bool SuppressConversion = false)
2500 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2502 /// \brief Determine whether the specified type is a valid destination type
2503 /// for this conversion.
2504 virtual bool match(QualType T) = 0;
2506 /// \brief Emits a diagnostic complaining that the expression does not have
2507 /// integral or enumeration type.
2508 virtual SemaDiagnosticBuilder
2509 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2511 /// \brief Emits a diagnostic when the expression has incomplete class type.
2512 virtual SemaDiagnosticBuilder
2513 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2515 /// \brief Emits a diagnostic when the only matching conversion function
2517 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2518 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2520 /// \brief Emits a note for the explicit conversion function.
2521 virtual SemaDiagnosticBuilder
2522 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2524 /// \brief Emits a diagnostic when there are multiple possible conversion
2526 virtual SemaDiagnosticBuilder
2527 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2529 /// \brief Emits a note for one of the candidate conversions.
2530 virtual SemaDiagnosticBuilder
2531 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2533 /// \brief Emits a diagnostic when we picked a conversion function
2534 /// (for cases when we are not allowed to pick a conversion function).
2535 virtual SemaDiagnosticBuilder diagnoseConversion(
2536 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2538 virtual ~ContextualImplicitConverter() {}
2541 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2542 bool AllowScopedEnumerations;
2545 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2546 bool Suppress, bool SuppressConversion)
2547 : ContextualImplicitConverter(Suppress, SuppressConversion),
2548 AllowScopedEnumerations(AllowScopedEnumerations) {}
2550 /// Match an integral or (possibly scoped) enumeration type.
2551 bool match(QualType T) override;
2553 SemaDiagnosticBuilder
2554 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2555 return diagnoseNotInt(S, Loc, T);
2558 /// \brief Emits a diagnostic complaining that the expression does not have
2559 /// integral or enumeration type.
2560 virtual SemaDiagnosticBuilder
2561 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2564 /// Perform a contextual implicit conversion.
2565 ExprResult PerformContextualImplicitConversion(
2566 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2569 enum ObjCSubscriptKind {
2574 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2576 // Note that LK_String is intentionally after the other literals, as
2577 // this is used for diagnostics logic.
2578 enum ObjCLiteralKind {
2587 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2589 ExprResult PerformObjectMemberConversion(Expr *From,
2590 NestedNameSpecifier *Qualifier,
2591 NamedDecl *FoundDecl,
2594 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2595 // TODO: make this is a typesafe union.
2596 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2597 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2599 void AddOverloadCandidate(FunctionDecl *Function,
2600 DeclAccessPair FoundDecl,
2601 ArrayRef<Expr *> Args,
2602 OverloadCandidateSet &CandidateSet,
2603 bool SuppressUserConversions = false,
2604 bool PartialOverloading = false,
2605 bool AllowExplicit = false,
2606 ConversionSequenceList EarlyConversions = None);
2607 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2608 ArrayRef<Expr *> Args,
2609 OverloadCandidateSet &CandidateSet,
2610 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2611 bool SuppressUserConversions = false,
2612 bool PartialOverloading = false);
2613 void AddMethodCandidate(DeclAccessPair FoundDecl,
2614 QualType ObjectType,
2615 Expr::Classification ObjectClassification,
2616 ArrayRef<Expr *> Args,
2617 OverloadCandidateSet& CandidateSet,
2618 bool SuppressUserConversion = false);
2619 void AddMethodCandidate(CXXMethodDecl *Method,
2620 DeclAccessPair FoundDecl,
2621 CXXRecordDecl *ActingContext, QualType ObjectType,
2622 Expr::Classification ObjectClassification,
2623 ArrayRef<Expr *> Args,
2624 OverloadCandidateSet& CandidateSet,
2625 bool SuppressUserConversions = false,
2626 bool PartialOverloading = false,
2627 ConversionSequenceList EarlyConversions = None);
2628 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2629 DeclAccessPair FoundDecl,
2630 CXXRecordDecl *ActingContext,
2631 TemplateArgumentListInfo *ExplicitTemplateArgs,
2632 QualType ObjectType,
2633 Expr::Classification ObjectClassification,
2634 ArrayRef<Expr *> Args,
2635 OverloadCandidateSet& CandidateSet,
2636 bool SuppressUserConversions = false,
2637 bool PartialOverloading = false);
2638 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2639 DeclAccessPair FoundDecl,
2640 TemplateArgumentListInfo *ExplicitTemplateArgs,
2641 ArrayRef<Expr *> Args,
2642 OverloadCandidateSet& CandidateSet,
2643 bool SuppressUserConversions = false,
2644 bool PartialOverloading = false);
2645 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2646 ArrayRef<QualType> ParamTypes,
2647 ArrayRef<Expr *> Args,
2648 OverloadCandidateSet &CandidateSet,
2649 ConversionSequenceList &Conversions,
2650 bool SuppressUserConversions,
2651 CXXRecordDecl *ActingContext = nullptr,
2652 QualType ObjectType = QualType(),
2653 Expr::Classification
2654 ObjectClassification = {});
2655 void AddConversionCandidate(CXXConversionDecl *Conversion,
2656 DeclAccessPair FoundDecl,
2657 CXXRecordDecl *ActingContext,
2658 Expr *From, QualType ToType,
2659 OverloadCandidateSet& CandidateSet,
2660 bool AllowObjCConversionOnExplicit);
2661 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2662 DeclAccessPair FoundDecl,
2663 CXXRecordDecl *ActingContext,
2664 Expr *From, QualType ToType,
2665 OverloadCandidateSet &CandidateSet,
2666 bool AllowObjCConversionOnExplicit);
2667 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2668 DeclAccessPair FoundDecl,
2669 CXXRecordDecl *ActingContext,
2670 const FunctionProtoType *Proto,
2671 Expr *Object, ArrayRef<Expr *> Args,
2672 OverloadCandidateSet& CandidateSet);
2673 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2674 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2675 OverloadCandidateSet& CandidateSet,
2676 SourceRange OpRange = SourceRange());
2677 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2678 ArrayRef<Expr *> Args,
2679 OverloadCandidateSet& CandidateSet,
2680 bool IsAssignmentOperator = false,
2681 unsigned NumContextualBoolArguments = 0);
2682 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2683 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2684 OverloadCandidateSet& CandidateSet);
2685 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2687 ArrayRef<Expr *> Args,
2688 TemplateArgumentListInfo *ExplicitTemplateArgs,
2689 OverloadCandidateSet& CandidateSet,
2690 bool PartialOverloading = false);
2692 // Emit as a 'note' the specific overload candidate
2693 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2694 QualType DestType = QualType(),
2695 bool TakingAddress = false);
2697 // Emit as a series of 'note's all template and non-templates identified by
2698 // the expression Expr
2699 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2700 bool TakingAddress = false);
2702 /// Check the enable_if expressions on the given function. Returns the first
2703 /// failing attribute, or NULL if they were all successful.
2704 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2705 bool MissingImplicitThis = false);
2707 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2708 /// non-ArgDependent DiagnoseIfAttrs.
2710 /// Argument-dependent diagnose_if attributes should be checked each time a
2711 /// function is used as a direct callee of a function call.
2713 /// Returns true if any errors were emitted.
2714 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2715 const Expr *ThisArg,
2716 ArrayRef<const Expr *> Args,
2717 SourceLocation Loc);
2719 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2720 /// ArgDependent DiagnoseIfAttrs.
2722 /// Argument-independent diagnose_if attributes should be checked on every use
2725 /// Returns true if any errors were emitted.
2726 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2727 SourceLocation Loc);
2729 /// Returns whether the given function's address can be taken or not,
2730 /// optionally emitting a diagnostic if the address can't be taken.
2732 /// Returns false if taking the address of the function is illegal.
2733 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2734 bool Complain = false,
2735 SourceLocation Loc = SourceLocation());
2737 // [PossiblyAFunctionType] --> [Return]
2738 // NonFunctionType --> NonFunctionType
2740 // R (*)(A) --> R (A)
2741 // R (&)(A) --> R (A)
2742 // R (S::*)(A) --> R (A)
2743 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2746 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2747 QualType TargetType,
2749 DeclAccessPair &Found,
2750 bool *pHadMultipleCandidates = nullptr);
2753 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2754 DeclAccessPair &FoundResult);
2756 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2757 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2760 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2761 bool Complain = false,
2762 DeclAccessPair *Found = nullptr);
2764 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2765 ExprResult &SrcExpr,
2766 bool DoFunctionPointerConverion = false,
2767 bool Complain = false,
2768 SourceRange OpRangeForComplaining = SourceRange(),
2769 QualType DestTypeForComplaining = QualType(),
2770 unsigned DiagIDForComplaining = 0);
2773 Expr *FixOverloadedFunctionReference(Expr *E,
2774 DeclAccessPair FoundDecl,
2776 ExprResult FixOverloadedFunctionReference(ExprResult,
2777 DeclAccessPair FoundDecl,
2780 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2781 ArrayRef<Expr *> Args,
2782 OverloadCandidateSet &CandidateSet,
2783 bool PartialOverloading = false);
2785 // An enum used to represent the different possible results of building a
2786 // range-based for loop.
2787 enum ForRangeStatus {
2789 FRS_NoViableFunction,
2790 FRS_DiagnosticIssued
2793 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2794 SourceLocation RangeLoc,
2795 const DeclarationNameInfo &NameInfo,
2796 LookupResult &MemberLookup,
2797 OverloadCandidateSet *CandidateSet,
2798 Expr *Range, ExprResult *CallExpr);
2800 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2801 UnresolvedLookupExpr *ULE,
2802 SourceLocation LParenLoc,
2804 SourceLocation RParenLoc,
2806 bool AllowTypoCorrection=true,
2807 bool CalleesAddressIsTaken=false);
2809 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2810 MultiExprArg Args, SourceLocation RParenLoc,
2811 OverloadCandidateSet *CandidateSet,
2812 ExprResult *Result);
2814 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2815 UnaryOperatorKind Opc,
2816 const UnresolvedSetImpl &Fns,
2819 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2820 BinaryOperatorKind Opc,
2821 const UnresolvedSetImpl &Fns,
2822 Expr *LHS, Expr *RHS);
2824 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2825 SourceLocation RLoc,
2826 Expr *Base,Expr *Idx);
2829 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2830 SourceLocation LParenLoc,
2832 SourceLocation RParenLoc);
2834 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2836 SourceLocation RParenLoc);
2838 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2839 SourceLocation OpLoc,
2840 bool *NoArrowOperatorFound = nullptr);
2842 /// CheckCallReturnType - Checks that a call expression's return type is
2843 /// complete. Returns true on failure. The location passed in is the location
2844 /// that best represents the call.
2845 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2846 CallExpr *CE, FunctionDecl *FD);
2848 /// Helpers for dealing with blocks and functions.
2849 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2850 bool CheckParameterNames);
2851 void CheckCXXDefaultArguments(FunctionDecl *FD);
2852 void CheckExtraCXXDefaultArguments(Declarator &D);
2853 Scope *getNonFieldDeclScope(Scope *S);
2855 /// \name Name lookup
2857 /// These routines provide name lookup that is used during semantic
2858 /// analysis to resolve the various kinds of names (identifiers,
2859 /// overloaded operator names, constructor names, etc.) into zero or
2860 /// more declarations within a particular scope. The major entry
2861 /// points are LookupName, which performs unqualified name lookup,
2862 /// and LookupQualifiedName, which performs qualified name lookup.
2864 /// All name lookup is performed based on some specific criteria,
2865 /// which specify what names will be visible to name lookup and how
2866 /// far name lookup should work. These criteria are important both
2867 /// for capturing language semantics (certain lookups will ignore
2868 /// certain names, for example) and for performance, since name
2869 /// lookup is often a bottleneck in the compilation of C++. Name
2870 /// lookup criteria is specified via the LookupCriteria enumeration.
2872 /// The results of name lookup can vary based on the kind of name
2873 /// lookup performed, the current language, and the translation
2874 /// unit. In C, for example, name lookup will either return nothing
2875 /// (no entity found) or a single declaration. In C++, name lookup
2876 /// can additionally refer to a set of overloaded functions or
2877 /// result in an ambiguity. All of the possible results of name
2878 /// lookup are captured by the LookupResult class, which provides
2879 /// the ability to distinguish among them.
2882 /// @brief Describes the kind of name lookup to perform.
2883 enum LookupNameKind {
2884 /// Ordinary name lookup, which finds ordinary names (functions,
2885 /// variables, typedefs, etc.) in C and most kinds of names
2886 /// (functions, variables, members, types, etc.) in C++.
2887 LookupOrdinaryName = 0,
2888 /// Tag name lookup, which finds the names of enums, classes,
2889 /// structs, and unions.
2891 /// Label name lookup.
2893 /// Member name lookup, which finds the names of
2894 /// class/struct/union members.
2896 /// Look up of an operator name (e.g., operator+) for use with
2897 /// operator overloading. This lookup is similar to ordinary name
2898 /// lookup, but will ignore any declarations that are class members.
2900 /// Look up of a name that precedes the '::' scope resolution
2901 /// operator in C++. This lookup completely ignores operator, object,
2902 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2903 LookupNestedNameSpecifierName,
2904 /// Look up a namespace name within a C++ using directive or
2905 /// namespace alias definition, ignoring non-namespace names (C++
2906 /// [basic.lookup.udir]p1).
2907 LookupNamespaceName,
2908 /// Look up all declarations in a scope with the given name,
2909 /// including resolved using declarations. This is appropriate
2910 /// for checking redeclarations for a using declaration.
2911 LookupUsingDeclName,
2912 /// Look up an ordinary name that is going to be redeclared as a
2913 /// name with linkage. This lookup ignores any declarations that
2914 /// are outside of the current scope unless they have linkage. See
2915 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2916 LookupRedeclarationWithLinkage,
2917 /// Look up a friend of a local class. This lookup does not look
2918 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2919 LookupLocalFriendName,
2920 /// Look up the name of an Objective-C protocol.
2921 LookupObjCProtocolName,
2922 /// Look up implicit 'self' parameter of an objective-c method.
2923 LookupObjCImplicitSelfParam,
2924 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2925 LookupOMPReductionName,
2926 /// \brief Look up any declaration with any name.
2930 /// \brief Specifies whether (or how) name lookup is being performed for a
2931 /// redeclaration (vs. a reference).
2932 enum RedeclarationKind {
2933 /// \brief The lookup is a reference to this name that is not for the
2934 /// purpose of redeclaring the name.
2935 NotForRedeclaration = 0,
2936 /// \brief The lookup results will be used for redeclaration of a name,
2937 /// if an entity by that name already exists.
2941 /// \brief The possible outcomes of name lookup for a literal operator.
2942 enum LiteralOperatorLookupResult {
2943 /// \brief The lookup resulted in an error.
2945 /// \brief The lookup found a single 'cooked' literal operator, which
2946 /// expects a normal literal to be built and passed to it.
2948 /// \brief The lookup found a single 'raw' literal operator, which expects
2949 /// a string literal containing the spelling of the literal token.
2951 /// \brief The lookup found an overload set of literal operator templates,
2952 /// which expect the characters of the spelling of the literal token to be
2953 /// passed as a non-type template argument pack.
2955 /// \brief The lookup found an overload set of literal operator templates,
2956 /// which expect the character type and characters of the spelling of the
2957 /// string literal token to be passed as template arguments.
2961 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2962 CXXSpecialMember SM,
2969 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2970 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2971 TypoRecoveryCallback;
2974 bool CppLookupName(LookupResult &R, Scope *S);
2976 struct TypoExprState {
2977 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2978 TypoDiagnosticGenerator DiagHandler;
2979 TypoRecoveryCallback RecoveryHandler;
2981 TypoExprState(TypoExprState &&other) noexcept;
2982 TypoExprState &operator=(TypoExprState &&other) noexcept;
2985 /// \brief The set of unhandled TypoExprs and their associated state.
2986 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2988 /// \brief Creates a new TypoExpr AST node.
2989 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2990 TypoDiagnosticGenerator TDG,
2991 TypoRecoveryCallback TRC);
2993 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2995 // The boolean value will be true to indicate that the namespace was loaded
2996 // from an AST/PCH file, or false otherwise.
2997 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2999 /// \brief Whether we have already loaded known namespaces from an extenal
3001 bool LoadedExternalKnownNamespaces;
3003 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3004 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3005 /// should be skipped entirely.
3006 std::unique_ptr<TypoCorrectionConsumer>
3007 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3008 Sema::LookupNameKind LookupKind, Scope *S,
3010 std::unique_ptr<CorrectionCandidateCallback> CCC,
3011 DeclContext *MemberContext, bool EnteringContext,
3012 const ObjCObjectPointerType *OPT,
3013 bool ErrorRecovery);
3016 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3018 /// \brief Clears the state of the given TypoExpr.
3019 void clearDelayedTypo(TypoExpr *TE);
3021 /// \brief Look up a name, looking for a single declaration. Return
3022 /// null if the results were absent, ambiguous, or overloaded.
3024 /// It is preferable to use the elaborated form and explicitly handle
3025 /// ambiguity and overloaded.
3026 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3028 LookupNameKind NameKind,
3029 RedeclarationKind Redecl
3030 = NotForRedeclaration);
3031 bool LookupName(LookupResult &R, Scope *S,
3032 bool AllowBuiltinCreation = false);
3033 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3034 bool InUnqualifiedLookup = false);
3035 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3037 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3038 bool AllowBuiltinCreation = false,
3039 bool EnteringContext = false);
3040 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3041 RedeclarationKind Redecl
3042 = NotForRedeclaration);
3043 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3045 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3046 QualType T1, QualType T2,
3047 UnresolvedSetImpl &Functions);
3049 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3050 SourceLocation GnuLabelLoc = SourceLocation());
3052 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3053 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3054 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3056 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3057 bool RValueThis, unsigned ThisQuals);
3058 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3060 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3061 bool RValueThis, unsigned ThisQuals);
3062 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3064 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3065 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3066 ArrayRef<QualType> ArgTys,
3069 bool AllowStringTemplate);
3070 bool isKnownName(StringRef name);
3072 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3073 ArrayRef<Expr *> Args, ADLResult &Functions);
3075 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3076 VisibleDeclConsumer &Consumer,
3077 bool IncludeGlobalScope = true);
3078 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3079 VisibleDeclConsumer &Consumer,
3080 bool IncludeGlobalScope = true,
3081 bool IncludeDependentBases = false);
3083 enum CorrectTypoKind {
3084 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3085 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3088 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3089 Sema::LookupNameKind LookupKind,
3090 Scope *S, CXXScopeSpec *SS,
3091 std::unique_ptr<CorrectionCandidateCallback> CCC,
3092 CorrectTypoKind Mode,
3093 DeclContext *MemberContext = nullptr,
3094 bool EnteringContext = false,
3095 const ObjCObjectPointerType *OPT = nullptr,
3096 bool RecordFailure = true);
3098 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3099 Sema::LookupNameKind LookupKind, Scope *S,
3101 std::unique_ptr<CorrectionCandidateCallback> CCC,
3102 TypoDiagnosticGenerator TDG,
3103 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3104 DeclContext *MemberContext = nullptr,
3105 bool EnteringContext = false,
3106 const ObjCObjectPointerType *OPT = nullptr);
3108 /// \brief Process any TypoExprs in the given Expr and its children,
3109 /// generating diagnostics as appropriate and returning a new Expr if there
3110 /// were typos that were all successfully corrected and ExprError if one or
3111 /// more typos could not be corrected.
3113 /// \param E The Expr to check for TypoExprs.
3115 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3118 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3119 /// it is an acceptable/usable result from a single combination of typo
3120 /// corrections. As long as the filter returns ExprError, different
3121 /// combinations of corrections will be tried until all are exhausted.
3123 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3124 llvm::function_ref<ExprResult(Expr *)> Filter =
3125 [](Expr *E) -> ExprResult { return E; });
3128 CorrectDelayedTyposInExpr(Expr *E,
3129 llvm::function_ref<ExprResult(Expr *)> Filter) {
3130 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3134 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3135 llvm::function_ref<ExprResult(Expr *)> Filter =
3136 [](Expr *E) -> ExprResult { return E; }) {
3137 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3141 CorrectDelayedTyposInExpr(ExprResult ER,
3142 llvm::function_ref<ExprResult(Expr *)> Filter) {
3143 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3146 void diagnoseTypo(const TypoCorrection &Correction,
3147 const PartialDiagnostic &TypoDiag,
3148 bool ErrorRecovery = true);
3150 void diagnoseTypo(const TypoCorrection &Correction,
3151 const PartialDiagnostic &TypoDiag,
3152 const PartialDiagnostic &PrevNote,
3153 bool ErrorRecovery = true);
3155 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3157 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3158 ArrayRef<Expr *> Args,
3159 AssociatedNamespaceSet &AssociatedNamespaces,
3160 AssociatedClassSet &AssociatedClasses);
3162 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3163 bool ConsiderLinkage, bool AllowInlineNamespace);
3165 void DiagnoseAmbiguousLookup(LookupResult &Result);
3168 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3169 SourceLocation IdLoc,
3170 bool TypoCorrection = false);
3171 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3172 Scope *S, bool ForRedeclaration,
3173 SourceLocation Loc);
3174 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3176 void AddKnownFunctionAttributes(FunctionDecl *FD);
3178 // More parsing and symbol table subroutines.
3180 void ProcessPragmaWeak(Scope *S, Decl *D);
3181 // Decl attributes - this routine is the top level dispatcher.
3182 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3183 // Helper for delayed proccessing of attributes.
3184 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3185 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3186 bool IncludeCXX11Attributes = true);
3187 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3188 const AttributeList *AttrList);
3190 void checkUnusedDeclAttributes(Declarator &D);
3192 /// Determine if type T is a valid subject for a nonnull and similar
3193 /// attributes. By default, we look through references (the behavior used by
3194 /// nonnull), but if the second parameter is true, then we treat a reference
3196 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3198 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3199 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3200 const FunctionDecl *FD = nullptr);
3201 bool CheckNoReturnAttr(const AttributeList &attr);
3202 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3203 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3204 unsigned ArgNum, StringRef &Str,
3205 SourceLocation *ArgLocation = nullptr);
3206 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3207 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3208 bool checkMSInheritanceAttrOnDefinition(
3209 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3210 MSInheritanceAttr::Spelling SemanticSpelling);
3212 void CheckAlignasUnderalignment(Decl *D);
3214 /// Adjust the calling convention of a method to be the ABI default if it
3215 /// wasn't specified explicitly. This handles method types formed from
3216 /// function type typedefs and typename template arguments.
3217 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3218 SourceLocation Loc);
3220 // Check if there is an explicit attribute, but only look through parens.
3221 // The intent is to look for an attribute on the current declarator, but not
3222 // one that came from a typedef.
3223 bool hasExplicitCallingConv(QualType &T);
3225 /// Get the outermost AttributedType node that sets a calling convention.
3226 /// Valid types should not have multiple attributes with different CCs.
3227 const AttributedType *getCallingConvAttributedType(QualType T) const;
3229 /// Check whether a nullability type specifier can be added to the given
3232 /// \param type The type to which the nullability specifier will be
3233 /// added. On success, this type will be updated appropriately.
3235 /// \param nullability The nullability specifier to add.
3237 /// \param nullabilityLoc The location of the nullability specifier.
3239 /// \param isContextSensitive Whether this nullability specifier was
3240 /// written as a context-sensitive keyword (in an Objective-C
3241 /// method) or an Objective-C property attribute, rather than as an
3242 /// underscored type specifier.
3244 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3245 /// array type (e.g., because it will decay to a pointer).
3247 /// \returns true if nullability cannot be applied, false otherwise.
3248 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3249 SourceLocation nullabilityLoc,
3250 bool isContextSensitive,
3251 bool allowArrayTypes);
3253 /// \brief Stmt attributes - this routine is the top level dispatcher.
3254 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3257 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3258 ObjCMethodDecl *MethodDecl,
3259 bool IsProtocolMethodDecl);
3261 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3262 ObjCMethodDecl *Overridden,
3263 bool IsProtocolMethodDecl);
3265 /// WarnExactTypedMethods - This routine issues a warning if method
3266 /// implementation declaration matches exactly that of its declaration.
3267 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3268 ObjCMethodDecl *MethodDecl,
3269 bool IsProtocolMethodDecl);
3271 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3273 /// CheckImplementationIvars - This routine checks if the instance variables
3274 /// listed in the implelementation match those listed in the interface.
3275 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3276 ObjCIvarDecl **Fields, unsigned nIvars,
3277 SourceLocation Loc);
3279 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3280 /// remains unimplemented in the class or category \@implementation.
3281 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3282 ObjCContainerDecl* IDecl,
3283 bool IncompleteImpl = false);
3285 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3286 /// which must be implemented by this implementation.
3287 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3288 ObjCContainerDecl *CDecl,
3289 bool SynthesizeProperties);
3291 /// Diagnose any null-resettable synthesized setters.
3292 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3294 /// DefaultSynthesizeProperties - This routine default synthesizes all
3295 /// properties which must be synthesized in the class's \@implementation.
3296 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3297 ObjCInterfaceDecl *IDecl);
3298 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3300 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3301 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3302 /// declared in class 'IFace'.
3303 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3304 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3306 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3307 /// backs the property is not used in the property's accessor.
3308 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3309 const ObjCImplementationDecl *ImplD);
3311 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3312 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3313 /// It also returns ivar's property on success.
3314 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3315 const ObjCPropertyDecl *&PDecl) const;
3317 /// Called by ActOnProperty to handle \@property declarations in
3318 /// class extensions.
3319 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3320 SourceLocation AtLoc,
3321 SourceLocation LParenLoc,
3322 FieldDeclarator &FD,
3324 SourceLocation GetterNameLoc,
3326 SourceLocation SetterNameLoc,
3327 const bool isReadWrite,
3328 unsigned &Attributes,
3329 const unsigned AttributesAsWritten,
3331 TypeSourceInfo *TSI,
3332 tok::ObjCKeywordKind MethodImplKind);
3334 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3335 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3336 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3337 ObjCContainerDecl *CDecl,
3338 SourceLocation AtLoc,
3339 SourceLocation LParenLoc,
3340 FieldDeclarator &FD,
3342 SourceLocation GetterNameLoc,
3344 SourceLocation SetterNameLoc,
3345 const bool isReadWrite,
3346 const unsigned Attributes,
3347 const unsigned AttributesAsWritten,
3349 TypeSourceInfo *TSI,
3350 tok::ObjCKeywordKind MethodImplKind,
3351 DeclContext *lexicalDC = nullptr);
3353 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3354 /// warning) when atomic property has one but not the other user-declared
3355 /// setter or getter.
3356 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3357 ObjCInterfaceDecl* IDecl);
3359 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3361 void DiagnoseMissingDesignatedInitOverrides(
3362 const ObjCImplementationDecl *ImplD,
3363 const ObjCInterfaceDecl *IFD);
3365 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3367 enum MethodMatchStrategy {
3372 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3373 /// true, or false, accordingly.
3374 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3375 const ObjCMethodDecl *PrevMethod,
3376 MethodMatchStrategy strategy = MMS_strict);
3378 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3379 /// or protocol against those declared in their implementations.
3380 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3381 const SelectorSet &ClsMap,
3382 SelectorSet &InsMapSeen,
3383 SelectorSet &ClsMapSeen,
3384 ObjCImplDecl* IMPDecl,
3385 ObjCContainerDecl* IDecl,
3386 bool &IncompleteImpl,
3387 bool ImmediateClass,
3388 bool WarnCategoryMethodImpl=false);
3390 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3391 /// category matches with those implemented in its primary class and
3392 /// warns each time an exact match is found.
3393 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3395 /// \brief Add the given method to the list of globally-known methods.
3396 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3399 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3400 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3401 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3403 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3404 /// optionally warns if there are multiple signatures.
3405 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3406 bool receiverIdOrClass,
3410 /// \brief - Returns instance or factory methods in global method pool for
3411 /// given selector. It checks the desired kind first, if none is found, and
3412 /// parameter checkTheOther is set, it then checks the other kind. If no such
3413 /// method or only one method is found, function returns false; otherwise, it
3416 CollectMultipleMethodsInGlobalPool(Selector Sel,
3417 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3418 bool InstanceFirst, bool CheckTheOther,
3419 const ObjCObjectType *TypeBound = nullptr);
3422 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3423 SourceRange R, bool receiverIdOrClass,
3424 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3427 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3428 Selector Sel, SourceRange R,
3429 bool receiverIdOrClass);
3432 /// \brief - Returns a selector which best matches given argument list or
3433 /// nullptr if none could be found
3434 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3436 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3439 /// \brief Record the typo correction failure and return an empty correction.
3440 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3441 bool RecordFailure = true) {
3443 TypoCorrectionFailures[Typo].insert(TypoLoc);
3444 return TypoCorrection();
3448 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3449 /// unit are added to a global pool. This allows us to efficiently associate
3450 /// a selector with a method declaraation for purposes of typechecking
3451 /// messages sent to "id" (where the class of the object is unknown).
3452 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3453 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3456 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3457 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3458 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3461 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3463 void AddAnyMethodToGlobalPool(Decl *D);
3465 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3466 /// there are multiple signatures.
3467 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3468 bool receiverIdOrClass=false) {
3469 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3473 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3474 /// there are multiple signatures.
3475 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3476 bool receiverIdOrClass=false) {
3477 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3481 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3482 QualType ObjectType=QualType());
3483 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3485 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3487 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3489 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3490 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3492 //===--------------------------------------------------------------------===//
3493 // Statement Parsing Callbacks: SemaStmt.cpp.
3497 FullExprArg() : E(nullptr) { }
3498 FullExprArg(Sema &actions) : E(nullptr) { }
3500 ExprResult release() {
3504 Expr *get() const { return E; }
3506 Expr *operator->() {
3511 // FIXME: No need to make the entire Sema class a friend when it's just
3512 // Sema::MakeFullExpr that needs access to the constructor below.
3515 explicit FullExprArg(Expr *expr) : E(expr) {}
3520 FullExprArg MakeFullExpr(Expr *Arg) {
3521 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3523 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3524 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3526 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3528 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3529 /*DiscardedValue*/ true);
3530 return FullExprArg(FE.get());
3533 StmtResult ActOnExprStmt(ExprResult Arg);
3534 StmtResult ActOnExprStmtError();
3536 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3537 bool HasLeadingEmptyMacro = false);
3539 void ActOnStartOfCompoundStmt();
3540 void ActOnFinishOfCompoundStmt();
3541 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3542 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3544 /// \brief A RAII object to enter scope of a compound statement.
3545 class CompoundScopeRAII {
3547 CompoundScopeRAII(Sema &S): S(S) {
3548 S.ActOnStartOfCompoundStmt();
3551 ~CompoundScopeRAII() {
3552 S.ActOnFinishOfCompoundStmt();
3559 /// An RAII helper that pops function a function scope on exit.
3560 struct FunctionScopeRAII {
3563 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3564 ~FunctionScopeRAII() {
3566 S.PopFunctionScopeInfo();
3568 void disable() { Active = false; }
3571 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3572 SourceLocation StartLoc,
3573 SourceLocation EndLoc);
3574 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3575 StmtResult ActOnForEachLValueExpr(Expr *E);
3576 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3577 SourceLocation DotDotDotLoc, Expr *RHSVal,
3578 SourceLocation ColonLoc);
3579 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3581 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3582 SourceLocation ColonLoc,
3583 Stmt *SubStmt, Scope *CurScope);
3584 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3585 SourceLocation ColonLoc, Stmt *SubStmt);
3587 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3588 ArrayRef<const Attr*> Attrs,
3591 class ConditionResult;
3592 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3594 ConditionResult Cond, Stmt *ThenVal,
3595 SourceLocation ElseLoc, Stmt *ElseVal);
3596 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3598 ConditionResult Cond, Stmt *ThenVal,
3599 SourceLocation ElseLoc, Stmt *ElseVal);
3600 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3602 ConditionResult Cond);
3603 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3604 Stmt *Switch, Stmt *Body);
3605 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3607 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3608 SourceLocation WhileLoc, SourceLocation CondLParen,
3609 Expr *Cond, SourceLocation CondRParen);
3611 StmtResult ActOnForStmt(SourceLocation ForLoc,
3612 SourceLocation LParenLoc,
3614 ConditionResult Second,
3616 SourceLocation RParenLoc,
3618 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3620 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3621 Stmt *First, Expr *collection,
3622 SourceLocation RParenLoc);
3623 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3625 enum BuildForRangeKind {
3626 /// Initial building of a for-range statement.
3628 /// Instantiation or recovery rebuild of a for-range statement. Don't
3629 /// attempt any typo-correction.
3631 /// Determining whether a for-range statement could be built. Avoid any
3632 /// unnecessary or irreversible actions.
3636 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3637 SourceLocation CoawaitLoc,
3639 SourceLocation ColonLoc, Expr *Collection,
3640 SourceLocation RParenLoc,
3641 BuildForRangeKind Kind);
3642 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3643 SourceLocation CoawaitLoc,
3644 SourceLocation ColonLoc,
3645 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3646 Expr *Cond, Expr *Inc,
3648 SourceLocation RParenLoc,
3649 BuildForRangeKind Kind);
3650 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3652 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3653 SourceLocation LabelLoc,
3654 LabelDecl *TheDecl);
3655 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3656 SourceLocation StarLoc,
3658 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3659 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3661 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3662 CapturedRegionKind Kind, unsigned NumParams);
3663 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3664 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3665 CapturedRegionKind Kind,
3666 ArrayRef<CapturedParamNameType> Params);
3667 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3668 void ActOnCapturedRegionError();
3669 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3671 unsigned NumParams);
3672 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3673 bool AllowParamOrMoveConstructible);
3674 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3675 bool AllowParamOrMoveConstructible);
3677 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3679 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3680 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3682 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3683 bool IsVolatile, unsigned NumOutputs,
3684 unsigned NumInputs, IdentifierInfo **Names,
3685 MultiExprArg Constraints, MultiExprArg Exprs,
3686 Expr *AsmString, MultiExprArg Clobbers,
3687 SourceLocation RParenLoc);
3689 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3690 SourceLocation TemplateKWLoc,
3692 llvm::InlineAsmIdentifierInfo &Info,
3693 bool IsUnevaluatedContext);
3694 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3695 unsigned &Offset, SourceLocation AsmLoc);
3696 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3697 llvm::InlineAsmIdentifierInfo &Info,
3698 SourceLocation AsmLoc);
3699 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3700 ArrayRef<Token> AsmToks,
3701 StringRef AsmString,
3702 unsigned NumOutputs, unsigned NumInputs,
3703 ArrayRef<StringRef> Constraints,
3704 ArrayRef<StringRef> Clobbers,
3705 ArrayRef<Expr*> Exprs,
3706 SourceLocation EndLoc);
3707 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3708 SourceLocation Location,
3711 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3712 SourceLocation StartLoc,
3713 SourceLocation IdLoc, IdentifierInfo *Id,
3714 bool Invalid = false);
3716 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3718 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3719 Decl *Parm, Stmt *Body);
3721 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3723 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3724 MultiStmtArg Catch, Stmt *Finally);
3726 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3727 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3729 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3731 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3735 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3737 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3738 SourceLocation StartLoc,
3739 SourceLocation IdLoc,
3740 IdentifierInfo *Id);
3742 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3744 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3745 Decl *ExDecl, Stmt *HandlerBlock);
3746 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3747 ArrayRef<Stmt *> Handlers);
3749 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3750 SourceLocation TryLoc, Stmt *TryBlock,
3752 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3755 void ActOnStartSEHFinallyBlock();
3756 void ActOnAbortSEHFinallyBlock();
3757 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3758 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3760 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3762 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3764 /// \brief If it's a file scoped decl that must warn if not used, keep track
3766 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3768 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3769 /// whose result is unused, warn.
3770 void DiagnoseUnusedExprResult(const Stmt *S);
3771 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3772 void DiagnoseUnusedDecl(const NamedDecl *ND);
3774 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3775 /// statement as a \p Body, and it is located on the same line.
3777 /// This helps prevent bugs due to typos, such as:
3780 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3784 /// Warn if a for/while loop statement \p S, which is followed by
3785 /// \p PossibleBody, has a suspicious null statement as a body.
3786 void DiagnoseEmptyLoopBody(const Stmt *S,
3787 const Stmt *PossibleBody);
3789 /// Warn if a value is moved to itself.
3790 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3791 SourceLocation OpLoc);
3793 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3795 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3796 SourceLocation Loc);
3798 /// Warn when implicitly casting 0 to nullptr.
3799 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3801 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3802 return DelayedDiagnostics.push(pool);
3804 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3806 typedef ProcessingContextState ParsingClassState;
3807 ParsingClassState PushParsingClass() {
3808 return DelayedDiagnostics.pushUndelayed();
3810 void PopParsingClass(ParsingClassState state) {
3811 DelayedDiagnostics.popUndelayed(state);
3814 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3816 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3817 StringRef Message, SourceLocation Loc,
3818 const ObjCInterfaceDecl *UnknownObjCClass,
3819 const ObjCPropertyDecl *ObjCProperty,
3820 bool ObjCPropertyAccess);
3822 bool makeUnavailableInSystemHeader(SourceLocation loc,
3823 UnavailableAttr::ImplicitReason reason);
3825 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3826 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3828 //===--------------------------------------------------------------------===//
3829 // Expression Parsing Callbacks: SemaExpr.cpp.
3831 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3832 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3833 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3834 bool ObjCPropertyAccess=false);
3835 void NoteDeletedFunction(FunctionDecl *FD);
3836 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3837 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3838 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3839 ObjCMethodDecl *Getter,
3840 SourceLocation Loc);
3841 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3842 ArrayRef<Expr *> Args);
3844 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3845 Decl *LambdaContextDecl = nullptr,
3846 bool IsDecltype = false);
3847 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3848 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3849 ReuseLambdaContextDecl_t,
3850 bool IsDecltype = false);
3851 void PopExpressionEvaluationContext();
3853 void DiscardCleanupsInEvaluationContext();
3855 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3856 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3858 ExprResult ActOnConstantExpression(ExprResult Res);
3860 // Functions for marking a declaration referenced. These functions also
3861 // contain the relevant logic for marking if a reference to a function or
3862 // variable is an odr-use (in the C++11 sense). There are separate variants
3863 // for expressions referring to a decl; these exist because odr-use marking
3864 // needs to be delayed for some constant variables when we build one of the
3865 // named expressions.
3867 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3868 // should usually be true. This only needs to be set to false if the lack of
3869 // odr-use cannot be determined from the current context (for instance,
3870 // because the name denotes a virtual function and was written without an
3871 // explicit nested-name-specifier).
3872 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3873 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3874 bool MightBeOdrUse = true);
3875 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3876 void MarkDeclRefReferenced(DeclRefExpr *E);
3877 void MarkMemberReferenced(MemberExpr *E);
3879 void UpdateMarkingForLValueToRValue(Expr *E);
3880 void CleanupVarDeclMarking();
3882 enum TryCaptureKind {
3883 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3886 /// \brief Try to capture the given variable.
3888 /// \param Var The variable to capture.
3890 /// \param Loc The location at which the capture occurs.
3892 /// \param Kind The kind of capture, which may be implicit (for either a
3893 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3895 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3896 /// an explicit lambda capture.
3898 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3899 /// captures or diagnose errors. If false, this routine merely check whether
3900 /// the capture can occur without performing the capture itself or complaining
3901 /// if the variable cannot be captured.
3903 /// \param CaptureType Will be set to the type of the field used to capture
3904 /// this variable in the innermost block or lambda. Only valid when the
3905 /// variable can be captured.
3907 /// \param DeclRefType Will be set to the type of a reference to the capture
3908 /// from within the current scope. Only valid when the variable can be
3911 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3912 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3913 /// This is useful when enclosing lambdas must speculatively capture
3914 /// variables that may or may not be used in certain specializations of
3915 /// a nested generic lambda.
3917 /// \returns true if an error occurred (i.e., the variable cannot be
3918 /// captured) and false if the capture succeeded.
3919 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3920 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3921 QualType &CaptureType,
3922 QualType &DeclRefType,
3923 const unsigned *const FunctionScopeIndexToStopAt);
3925 /// \brief Try to capture the given variable.
3926 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3927 TryCaptureKind Kind = TryCapture_Implicit,
3928 SourceLocation EllipsisLoc = SourceLocation());
3930 /// \brief Checks if the variable must be captured.
3931 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3933 /// \brief Given a variable, determine the type that a reference to that
3934 /// variable will have in the given scope.
3935 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3937 /// Mark all of the declarations referenced within a particular AST node as
3938 /// referenced. Used when template instantiation instantiates a non-dependent
3939 /// type -- entities referenced by the type are now referenced.
3940 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3941 void MarkDeclarationsReferencedInExpr(Expr *E,
3942 bool SkipLocalVariables = false);
3944 /// \brief Try to recover by turning the given expression into a
3945 /// call. Returns true if recovery was attempted or an error was
3946 /// emitted; this may also leave the ExprResult invalid.
3947 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3948 bool ForceComplain = false,
3949 bool (*IsPlausibleResult)(QualType) = nullptr);
3951 /// \brief Figure out if an expression could be turned into a call.
3952 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3953 UnresolvedSetImpl &NonTemplateOverloads);
3955 /// \brief Conditionally issue a diagnostic based on the current
3956 /// evaluation context.
3958 /// \param Statement If Statement is non-null, delay reporting the
3959 /// diagnostic until the function body is parsed, and then do a basic
3960 /// reachability analysis to determine if the statement is reachable.
3961 /// If it is unreachable, the diagnostic will not be emitted.
3962 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3963 const PartialDiagnostic &PD);
3965 // Primary Expressions.
3966 SourceRange getExprRange(Expr *E) const;
3968 ExprResult ActOnIdExpression(
3969 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3970 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3971 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3972 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3974 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3975 TemplateArgumentListInfo &Buffer,
3976 DeclarationNameInfo &NameInfo,
3977 const TemplateArgumentListInfo *&TemplateArgs);
3980 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3981 std::unique_ptr<CorrectionCandidateCallback> CCC,
3982 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3983 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3985 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3987 bool AllowBuiltinCreation=false);
3989 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3990 SourceLocation TemplateKWLoc,
3991 const DeclarationNameInfo &NameInfo,
3992 bool isAddressOfOperand,
3993 const TemplateArgumentListInfo *TemplateArgs);
3995 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3998 const CXXScopeSpec *SS = nullptr);
4000 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4001 const DeclarationNameInfo &NameInfo,
4002 const CXXScopeSpec *SS = nullptr,
4003 NamedDecl *FoundD = nullptr,
4004 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4006 BuildAnonymousStructUnionMemberReference(
4007 const CXXScopeSpec &SS,
4008 SourceLocation nameLoc,
4009 IndirectFieldDecl *indirectField,
4010 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4011 Expr *baseObjectExpr = nullptr,
4012 SourceLocation opLoc = SourceLocation());
4014 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4015 SourceLocation TemplateKWLoc,
4017 const TemplateArgumentListInfo *TemplateArgs,
4019 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4020 SourceLocation TemplateKWLoc,
4022 const TemplateArgumentListInfo *TemplateArgs,
4023 bool IsDefiniteInstance,
4025 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4026 const LookupResult &R,
4027 bool HasTrailingLParen);
4030 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4031 const DeclarationNameInfo &NameInfo,
4032 bool IsAddressOfOperand, const Scope *S,
4033 TypeSourceInfo **RecoveryTSI = nullptr);
4035 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4036 SourceLocation TemplateKWLoc,
4037 const DeclarationNameInfo &NameInfo,
4038 const TemplateArgumentListInfo *TemplateArgs);
4040 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4043 bool AcceptInvalidDecl = false);
4044 ExprResult BuildDeclarationNameExpr(
4045 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4046 NamedDecl *FoundD = nullptr,
4047 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4048 bool AcceptInvalidDecl = false);
4050 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4051 DeclarationNameInfo &SuffixInfo,
4052 ArrayRef<Expr *> Args,
4053 SourceLocation LitEndLoc,
4054 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4056 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4057 PredefinedExpr::IdentType IT);
4058 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4059 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4061 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4063 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4064 ExprResult ActOnCharacterConstant(const Token &Tok,
4065 Scope *UDLScope = nullptr);
4066 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4067 ExprResult ActOnParenListExpr(SourceLocation L,
4071 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4072 /// fragments (e.g. "foo" "bar" L"baz").
4073 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4074 Scope *UDLScope = nullptr);
4076 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4077 SourceLocation DefaultLoc,
4078 SourceLocation RParenLoc,
4079 Expr *ControllingExpr,
4080 ArrayRef<ParsedType> ArgTypes,
4081 ArrayRef<Expr *> ArgExprs);
4082 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4083 SourceLocation DefaultLoc,
4084 SourceLocation RParenLoc,
4085 Expr *ControllingExpr,
4086 ArrayRef<TypeSourceInfo *> Types,
4087 ArrayRef<Expr *> Exprs);
4089 // Binary/Unary Operators. 'Tok' is the token for the operator.
4090 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4092 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4093 UnaryOperatorKind Opc, Expr *Input);
4094 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4095 tok::TokenKind Op, Expr *Input);
4097 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4099 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4100 SourceLocation OpLoc,
4101 UnaryExprOrTypeTrait ExprKind,
4103 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4104 UnaryExprOrTypeTrait ExprKind);
4106 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4107 UnaryExprOrTypeTrait ExprKind,
4108 bool IsType, void *TyOrEx,
4109 SourceRange ArgRange);
4111 ExprResult CheckPlaceholderExpr(Expr *E);
4112 bool CheckVecStepExpr(Expr *E);
4114 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4115 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4116 SourceRange ExprRange,
4117 UnaryExprOrTypeTrait ExprKind);
4118 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4119 SourceLocation OpLoc,
4120 IdentifierInfo &Name,
4121 SourceLocation NameLoc,
4122 SourceLocation RParenLoc);
4123 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4124 tok::TokenKind Kind, Expr *Input);
4126 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4127 Expr *Idx, SourceLocation RLoc);
4128 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4129 Expr *Idx, SourceLocation RLoc);
4130 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4131 Expr *LowerBound, SourceLocation ColonLoc,
4132 Expr *Length, SourceLocation RBLoc);
4134 // This struct is for use by ActOnMemberAccess to allow
4135 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4136 // changing the access operator from a '.' to a '->' (to see if that is the
4137 // change needed to fix an error about an unknown member, e.g. when the class
4138 // defines a custom operator->).
4139 struct ActOnMemberAccessExtraArgs {
4145 ExprResult BuildMemberReferenceExpr(
4146 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4147 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4148 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4149 const TemplateArgumentListInfo *TemplateArgs,
4151 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4154 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4155 bool IsArrow, const CXXScopeSpec &SS,
4156 SourceLocation TemplateKWLoc,
4157 NamedDecl *FirstQualifierInScope, LookupResult &R,
4158 const TemplateArgumentListInfo *TemplateArgs,
4160 bool SuppressQualifierCheck = false,
4161 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4163 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4164 SourceLocation OpLoc,
4165 const CXXScopeSpec &SS, FieldDecl *Field,
4166 DeclAccessPair FoundDecl,
4167 const DeclarationNameInfo &MemberNameInfo);
4169 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4171 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4172 const CXXScopeSpec &SS,
4173 const LookupResult &R);
4175 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4176 bool IsArrow, SourceLocation OpLoc,
4177 const CXXScopeSpec &SS,
4178 SourceLocation TemplateKWLoc,
4179 NamedDecl *FirstQualifierInScope,
4180 const DeclarationNameInfo &NameInfo,
4181 const TemplateArgumentListInfo *TemplateArgs);
4183 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4184 SourceLocation OpLoc,
4185 tok::TokenKind OpKind,
4187 SourceLocation TemplateKWLoc,
4188 UnqualifiedId &Member,
4191 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4192 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4193 FunctionDecl *FDecl,
4194 const FunctionProtoType *Proto,
4195 ArrayRef<Expr *> Args,
4196 SourceLocation RParenLoc,
4197 bool ExecConfig = false);
4198 void CheckStaticArrayArgument(SourceLocation CallLoc,
4200 const Expr *ArgExpr);
4202 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4203 /// This provides the location of the left/right parens and a list of comma
4205 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4206 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4207 Expr *ExecConfig = nullptr,
4208 bool IsExecConfig = false);
4209 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4210 SourceLocation LParenLoc,
4211 ArrayRef<Expr *> Arg,
4212 SourceLocation RParenLoc,
4213 Expr *Config = nullptr,
4214 bool IsExecConfig = false);
4216 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4217 MultiExprArg ExecConfig,
4218 SourceLocation GGGLoc);
4220 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4221 Declarator &D, ParsedType &Ty,
4222 SourceLocation RParenLoc, Expr *CastExpr);
4223 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4225 SourceLocation RParenLoc,
4227 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4229 /// \brief Build an altivec or OpenCL literal.
4230 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4231 SourceLocation RParenLoc, Expr *E,
4232 TypeSourceInfo *TInfo);
4234 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4236 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4238 SourceLocation RParenLoc,
4241 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4242 TypeSourceInfo *TInfo,
4243 SourceLocation RParenLoc,
4246 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4247 MultiExprArg InitArgList,
4248 SourceLocation RBraceLoc);
4250 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4256 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4259 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4260 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4261 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4262 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4263 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4264 Expr *LHSExpr, Expr *RHSExpr);
4266 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4268 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4269 /// in the case of a the GNU conditional expr extension.
4270 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4271 SourceLocation ColonLoc,
4272 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4274 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4275 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4276 LabelDecl *TheDecl);
4278 void ActOnStartStmtExpr();
4279 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4280 SourceLocation RPLoc); // "({..})"
4281 void ActOnStmtExprError();
4283 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4284 struct OffsetOfComponent {
4285 SourceLocation LocStart, LocEnd;
4286 bool isBrackets; // true if [expr], false if .ident
4288 IdentifierInfo *IdentInfo;
4293 /// __builtin_offsetof(type, a.b[123][456].c)
4294 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4295 TypeSourceInfo *TInfo,
4296 ArrayRef<OffsetOfComponent> Components,
4297 SourceLocation RParenLoc);
4298 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4299 SourceLocation BuiltinLoc,
4300 SourceLocation TypeLoc,
4301 ParsedType ParsedArgTy,
4302 ArrayRef<OffsetOfComponent> Components,
4303 SourceLocation RParenLoc);
4305 // __builtin_choose_expr(constExpr, expr1, expr2)
4306 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4307 Expr *CondExpr, Expr *LHSExpr,
4308 Expr *RHSExpr, SourceLocation RPLoc);
4310 // __builtin_va_arg(expr, type)
4311 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4312 SourceLocation RPLoc);
4313 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4314 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4317 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4319 bool CheckCaseExpression(Expr *E);
4321 /// \brief Describes the result of an "if-exists" condition check.
4322 enum IfExistsResult {
4323 /// \brief The symbol exists.
4326 /// \brief The symbol does not exist.
4329 /// \brief The name is a dependent name, so the results will differ
4330 /// from one instantiation to the next.
4333 /// \brief An error occurred.
4338 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4339 const DeclarationNameInfo &TargetNameInfo);
4342 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4343 bool IsIfExists, CXXScopeSpec &SS,
4344 UnqualifiedId &Name);
4346 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4348 NestedNameSpecifierLoc QualifierLoc,
4349 DeclarationNameInfo NameInfo,
4351 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4353 CXXScopeSpec &SS, UnqualifiedId &Name,
4356 //===------------------------- "Block" Extension ------------------------===//
4358 /// ActOnBlockStart - This callback is invoked when a block literal is
4360 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4362 /// ActOnBlockArguments - This callback allows processing of block arguments.
4363 /// If there are no arguments, this is still invoked.
4364 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4367 /// ActOnBlockError - If there is an error parsing a block, this callback
4368 /// is invoked to pop the information about the block from the action impl.
4369 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4371 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4372 /// literal was successfully completed. ^(int x){...}
4373 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4376 //===---------------------------- Clang Extensions ----------------------===//
4378 /// __builtin_convertvector(...)
4379 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4380 SourceLocation BuiltinLoc,
4381 SourceLocation RParenLoc);
4383 //===---------------------------- OpenCL Features -----------------------===//
4385 /// __builtin_astype(...)
4386 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4387 SourceLocation BuiltinLoc,
4388 SourceLocation RParenLoc);
4390 //===---------------------------- C++ Features --------------------------===//
4392 // Act on C++ namespaces
4393 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4394 SourceLocation NamespaceLoc,
4395 SourceLocation IdentLoc,
4396 IdentifierInfo *Ident,
4397 SourceLocation LBrace,
4398 AttributeList *AttrList,
4399 UsingDirectiveDecl * &UsingDecl);
4400 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4402 NamespaceDecl *getStdNamespace() const;
4403 NamespaceDecl *getOrCreateStdNamespace();
4405 NamespaceDecl *lookupStdExperimentalNamespace();
4407 CXXRecordDecl *getStdBadAlloc() const;
4408 EnumDecl *getStdAlignValT() const;
4410 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4411 /// it is and Element is not NULL, assigns the element type to Element.
4412 bool isStdInitializerList(QualType Ty, QualType *Element);
4414 /// \brief Looks for the std::initializer_list template and instantiates it
4415 /// with Element, or emits an error if it's not found.
4417 /// \returns The instantiated template, or null on error.
4418 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4420 /// \brief Determine whether Ctor is an initializer-list constructor, as
4421 /// defined in [dcl.init.list]p2.
4422 bool isInitListConstructor(const FunctionDecl *Ctor);
4424 Decl *ActOnUsingDirective(Scope *CurScope,
4425 SourceLocation UsingLoc,
4426 SourceLocation NamespcLoc,
4428 SourceLocation IdentLoc,
4429 IdentifierInfo *NamespcName,
4430 AttributeList *AttrList);
4432 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4434 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4435 SourceLocation NamespaceLoc,
4436 SourceLocation AliasLoc,
4437 IdentifierInfo *Alias,
4439 SourceLocation IdentLoc,
4440 IdentifierInfo *Ident);
4442 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4443 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4444 const LookupResult &PreviousDecls,
4445 UsingShadowDecl *&PrevShadow);
4446 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4448 UsingShadowDecl *PrevDecl);
4450 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4451 bool HasTypenameKeyword,
4452 const CXXScopeSpec &SS,
4453 SourceLocation NameLoc,
4454 const LookupResult &Previous);
4455 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4457 const CXXScopeSpec &SS,
4458 const DeclarationNameInfo &NameInfo,
4459 SourceLocation NameLoc);
4461 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4462 SourceLocation UsingLoc,
4463 bool HasTypenameKeyword,
4464 SourceLocation TypenameLoc,
4466 DeclarationNameInfo NameInfo,
4467 SourceLocation EllipsisLoc,
4468 AttributeList *AttrList,
4469 bool IsInstantiation);
4470 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4471 ArrayRef<NamedDecl *> Expansions);
4473 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4475 /// Given a derived-class using shadow declaration for a constructor and the
4476 /// correspnding base class constructor, find or create the implicit
4477 /// synthesized derived class constructor to use for this initialization.
4478 CXXConstructorDecl *
4479 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4480 ConstructorUsingShadowDecl *DerivedShadow);
4482 Decl *ActOnUsingDeclaration(Scope *CurScope,
4484 SourceLocation UsingLoc,
4485 SourceLocation TypenameLoc,
4487 UnqualifiedId &Name,
4488 SourceLocation EllipsisLoc,
4489 AttributeList *AttrList);
4490 Decl *ActOnAliasDeclaration(Scope *CurScope,
4492 MultiTemplateParamsArg TemplateParams,
4493 SourceLocation UsingLoc,
4494 UnqualifiedId &Name,
4495 AttributeList *AttrList,
4497 Decl *DeclFromDeclSpec);
4499 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4500 /// including handling of its default argument expressions.
4502 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4504 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4505 NamedDecl *FoundDecl,
4506 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4507 bool HadMultipleCandidates, bool IsListInitialization,
4508 bool IsStdInitListInitialization,
4509 bool RequiresZeroInit, unsigned ConstructKind,
4510 SourceRange ParenRange);
4512 /// Build a CXXConstructExpr whose constructor has already been resolved if
4513 /// it denotes an inherited constructor.
4515 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4516 CXXConstructorDecl *Constructor, bool Elidable,
4518 bool HadMultipleCandidates, bool IsListInitialization,
4519 bool IsStdInitListInitialization,
4520 bool RequiresZeroInit, unsigned ConstructKind,
4521 SourceRange ParenRange);
4523 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4524 // the constructor can be elidable?
4526 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4527 NamedDecl *FoundDecl,
4528 CXXConstructorDecl *Constructor, bool Elidable,
4529 MultiExprArg Exprs, bool HadMultipleCandidates,
4530 bool IsListInitialization,
4531 bool IsStdInitListInitialization, bool RequiresZeroInit,
4532 unsigned ConstructKind, SourceRange ParenRange);
4534 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4537 /// Instantiate or parse a C++ default argument expression as necessary.
4538 /// Return true on error.
4539 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4540 ParmVarDecl *Param);
4542 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4543 /// the default expr if needed.
4544 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4546 ParmVarDecl *Param);
4548 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4549 /// constructed variable.
4550 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4552 /// \brief Helper class that collects exception specifications for
4553 /// implicitly-declared special member functions.
4554 class ImplicitExceptionSpecification {
4555 // Pointer to allow copying
4557 // We order exception specifications thus:
4558 // noexcept is the most restrictive, but is only used in C++11.
4559 // throw() comes next.
4560 // Then a throw(collected exceptions)
4561 // Finally no specification, which is expressed as noexcept(false).
4562 // throw(...) is used instead if any called function uses it.
4563 ExceptionSpecificationType ComputedEST;
4564 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4565 SmallVector<QualType, 4> Exceptions;
4567 void ClearExceptions() {
4568 ExceptionsSeen.clear();
4573 explicit ImplicitExceptionSpecification(Sema &Self)
4574 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4575 if (!Self.getLangOpts().CPlusPlus11)
4576 ComputedEST = EST_DynamicNone;
4579 /// \brief Get the computed exception specification type.
4580 ExceptionSpecificationType getExceptionSpecType() const {
4581 assert(ComputedEST != EST_ComputedNoexcept &&
4582 "noexcept(expr) should not be a possible result");
4586 /// \brief The number of exceptions in the exception specification.
4587 unsigned size() const { return Exceptions.size(); }
4589 /// \brief The set of exceptions in the exception specification.
4590 const QualType *data() const { return Exceptions.data(); }
4592 /// \brief Integrate another called method into the collected data.
4593 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4595 /// \brief Integrate an invoked expression into the collected data.
4596 void CalledExpr(Expr *E);
4598 /// \brief Overwrite an EPI's exception specification with this
4599 /// computed exception specification.
4600 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4601 FunctionProtoType::ExceptionSpecInfo ESI;
4602 ESI.Type = getExceptionSpecType();
4603 if (ESI.Type == EST_Dynamic) {
4604 ESI.Exceptions = Exceptions;
4605 } else if (ESI.Type == EST_None) {
4606 /// C++11 [except.spec]p14:
4607 /// The exception-specification is noexcept(false) if the set of
4608 /// potential exceptions of the special member function contains "any"
4609 ESI.Type = EST_ComputedNoexcept;
4610 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4611 tok::kw_false).get();
4617 /// \brief Determine what sort of exception specification a defaulted
4618 /// copy constructor of a class will have.
4619 ImplicitExceptionSpecification
4620 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4623 /// \brief Determine what sort of exception specification a defaulted
4624 /// default constructor of a class will have, and whether the parameter
4626 ImplicitExceptionSpecification
4627 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4629 /// \brief Determine what sort of exception specification a defautled
4630 /// copy assignment operator of a class will have, and whether the
4631 /// parameter will be const.
4632 ImplicitExceptionSpecification
4633 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4635 /// \brief Determine what sort of exception specification a defaulted move
4636 /// constructor of a class will have.
4637 ImplicitExceptionSpecification
4638 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4640 /// \brief Determine what sort of exception specification a defaulted move
4641 /// assignment operator of a class will have.
4642 ImplicitExceptionSpecification
4643 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4645 /// \brief Determine what sort of exception specification a defaulted
4646 /// destructor of a class will have.
4647 ImplicitExceptionSpecification
4648 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4650 /// \brief Determine what sort of exception specification an inheriting
4651 /// constructor of a class will have.
4652 ImplicitExceptionSpecification
4653 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4654 CXXConstructorDecl *CD);
4656 /// \brief Evaluate the implicit exception specification for a defaulted
4657 /// special member function.
4658 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4660 /// \brief Check the given exception-specification and update the
4661 /// exception specification information with the results.
4662 void checkExceptionSpecification(bool IsTopLevel,
4663 ExceptionSpecificationType EST,
4664 ArrayRef<ParsedType> DynamicExceptions,
4665 ArrayRef<SourceRange> DynamicExceptionRanges,
4667 SmallVectorImpl<QualType> &Exceptions,
4668 FunctionProtoType::ExceptionSpecInfo &ESI);
4670 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4671 /// parse an exception specification to work around a libstdc++ bug.
4672 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4674 /// \brief Add an exception-specification to the given member function
4675 /// (or member function template). The exception-specification was parsed
4676 /// after the method itself was declared.
4677 void actOnDelayedExceptionSpecification(Decl *Method,
4678 ExceptionSpecificationType EST,
4679 SourceRange SpecificationRange,
4680 ArrayRef<ParsedType> DynamicExceptions,
4681 ArrayRef<SourceRange> DynamicExceptionRanges,
4682 Expr *NoexceptExpr);
4684 class InheritedConstructorInfo;
4686 /// \brief Determine if a special member function should have a deleted
4687 /// definition when it is defaulted.
4688 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4689 InheritedConstructorInfo *ICI = nullptr,
4690 bool Diagnose = false);
4692 /// \brief Declare the implicit default constructor for the given class.
4694 /// \param ClassDecl The class declaration into which the implicit
4695 /// default constructor will be added.
4697 /// \returns The implicitly-declared default constructor.
4698 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4699 CXXRecordDecl *ClassDecl);
4701 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4702 /// defining this constructor as the default constructor.
4703 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4704 CXXConstructorDecl *Constructor);
4706 /// \brief Declare the implicit destructor for the given class.
4708 /// \param ClassDecl The class declaration into which the implicit
4709 /// destructor will be added.
4711 /// \returns The implicitly-declared destructor.
4712 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4714 /// DefineImplicitDestructor - Checks for feasibility of
4715 /// defining this destructor as the default destructor.
4716 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4717 CXXDestructorDecl *Destructor);
4719 /// \brief Build an exception spec for destructors that don't have one.
4721 /// C++11 says that user-defined destructors with no exception spec get one
4722 /// that looks as if the destructor was implicitly declared.
4723 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4724 CXXDestructorDecl *Destructor);
4726 /// \brief Define the specified inheriting constructor.
4727 void DefineInheritingConstructor(SourceLocation UseLoc,
4728 CXXConstructorDecl *Constructor);
4730 /// \brief Declare the implicit copy constructor for the given class.
4732 /// \param ClassDecl The class declaration into which the implicit
4733 /// copy constructor will be added.
4735 /// \returns The implicitly-declared copy constructor.
4736 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4738 /// DefineImplicitCopyConstructor - Checks for feasibility of
4739 /// defining this constructor as the copy constructor.
4740 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4741 CXXConstructorDecl *Constructor);
4743 /// \brief Declare the implicit move constructor for the given class.
4745 /// \param ClassDecl The Class declaration into which the implicit
4746 /// move constructor will be added.
4748 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4750 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4752 /// DefineImplicitMoveConstructor - Checks for feasibility of
4753 /// defining this constructor as the move constructor.
4754 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4755 CXXConstructorDecl *Constructor);
4757 /// \brief Declare the implicit copy assignment operator for the given class.
4759 /// \param ClassDecl The class declaration into which the implicit
4760 /// copy assignment operator will be added.
4762 /// \returns The implicitly-declared copy assignment operator.
4763 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4765 /// \brief Defines an implicitly-declared copy assignment operator.
4766 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4767 CXXMethodDecl *MethodDecl);
4769 /// \brief Declare the implicit move assignment operator for the given class.
4771 /// \param ClassDecl The Class declaration into which the implicit
4772 /// move assignment operator will be added.
4774 /// \returns The implicitly-declared move assignment operator, or NULL if it
4775 /// wasn't declared.
4776 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4778 /// \brief Defines an implicitly-declared move assignment operator.
4779 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4780 CXXMethodDecl *MethodDecl);
4782 /// \brief Force the declaration of any implicitly-declared members of this
4784 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4786 /// \brief Check a completed declaration of an implicit special member.
4787 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4789 /// \brief Determine whether the given function is an implicitly-deleted
4790 /// special member function.
4791 bool isImplicitlyDeleted(FunctionDecl *FD);
4793 /// \brief Check whether 'this' shows up in the type of a static member
4794 /// function after the (naturally empty) cv-qualifier-seq would be.
4796 /// \returns true if an error occurred.
4797 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4799 /// \brief Whether this' shows up in the exception specification of a static
4800 /// member function.
4801 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4803 /// \brief Check whether 'this' shows up in the attributes of the given
4804 /// static member function.
4806 /// \returns true if an error occurred.
4807 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4809 /// MaybeBindToTemporary - If the passed in expression has a record type with
4810 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4811 /// it simply returns the passed in expression.
4812 ExprResult MaybeBindToTemporary(Expr *E);
4814 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4815 MultiExprArg ArgsPtr,
4817 SmallVectorImpl<Expr*> &ConvertedArgs,
4818 bool AllowExplicit = false,
4819 bool IsListInitialization = false);
4821 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4822 SourceLocation NameLoc,
4823 IdentifierInfo &Name);
4825 ParsedType getDestructorName(SourceLocation TildeLoc,
4826 IdentifierInfo &II, SourceLocation NameLoc,
4827 Scope *S, CXXScopeSpec &SS,
4828 ParsedType ObjectType,
4829 bool EnteringContext);
4831 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4832 ParsedType ObjectType);
4834 // Checks that reinterpret casts don't have undefined behavior.
4835 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4836 bool IsDereference, SourceRange Range);
4838 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4839 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4840 tok::TokenKind Kind,
4841 SourceLocation LAngleBracketLoc,
4843 SourceLocation RAngleBracketLoc,
4844 SourceLocation LParenLoc,
4846 SourceLocation RParenLoc);
4848 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4849 tok::TokenKind Kind,
4852 SourceRange AngleBrackets,
4853 SourceRange Parens);
4855 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4856 SourceLocation TypeidLoc,
4857 TypeSourceInfo *Operand,
4858 SourceLocation RParenLoc);
4859 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4860 SourceLocation TypeidLoc,
4862 SourceLocation RParenLoc);
4864 /// ActOnCXXTypeid - Parse typeid( something ).
4865 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4866 SourceLocation LParenLoc, bool isType,
4868 SourceLocation RParenLoc);
4870 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4871 SourceLocation TypeidLoc,
4872 TypeSourceInfo *Operand,
4873 SourceLocation RParenLoc);
4874 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4875 SourceLocation TypeidLoc,
4877 SourceLocation RParenLoc);
4879 /// ActOnCXXUuidof - Parse __uuidof( something ).
4880 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4881 SourceLocation LParenLoc, bool isType,
4883 SourceLocation RParenLoc);
4885 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4886 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4887 tok::TokenKind Operator,
4888 SourceLocation EllipsisLoc, Expr *RHS,
4889 SourceLocation RParenLoc);
4890 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4891 BinaryOperatorKind Operator,
4892 SourceLocation EllipsisLoc, Expr *RHS,
4893 SourceLocation RParenLoc);
4894 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4895 BinaryOperatorKind Operator);
4897 //// ActOnCXXThis - Parse 'this' pointer.
4898 ExprResult ActOnCXXThis(SourceLocation loc);
4900 /// \brief Try to retrieve the type of the 'this' pointer.
4902 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4903 QualType getCurrentThisType();
4905 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4906 /// current context not being a non-static member function. In such cases,
4907 /// this provides the type used for 'this'.
4908 QualType CXXThisTypeOverride;
4910 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4911 /// to be used, with the given qualifiers on the current class type.
4912 class CXXThisScopeRAII {
4914 QualType OldCXXThisTypeOverride;
4918 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4919 /// using the given declaration (which is either a class template or a
4920 /// class) along with the given qualifiers.
4921 /// along with the qualifiers placed on '*this'.
4922 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4923 bool Enabled = true);
4925 ~CXXThisScopeRAII();
4928 /// \brief Make sure the value of 'this' is actually available in the current
4929 /// context, if it is a potentially evaluated context.
4931 /// \param Loc The location at which the capture of 'this' occurs.
4933 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4936 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4937 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4938 /// This is useful when enclosing lambdas must speculatively capture
4939 /// 'this' that may or may not be used in certain specializations of
4940 /// a nested generic lambda (depending on whether the name resolves to
4941 /// a non-static member function or a static function).
4942 /// \return returns 'true' if failed, 'false' if success.
4943 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4944 bool BuildAndDiagnose = true,
4945 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4946 bool ByCopy = false);
4948 /// \brief Determine whether the given type is the type of *this that is used
4949 /// outside of the body of a member function for a type that is currently
4951 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4953 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4954 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4957 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4958 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4961 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4962 SourceLocation AtLoc, SourceLocation RParen);
4964 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4965 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4967 //// ActOnCXXThrow - Parse throw expressions.
4968 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4969 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4970 bool IsThrownVarInScope);
4971 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4973 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4974 /// Can be interpreted either as function-style casting ("int(x)")
4975 /// or class type construction ("ClassType(x,y,z)")
4976 /// or creation of a value-initialized type ("int()").
4977 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4978 SourceLocation LParenLoc,
4980 SourceLocation RParenLoc);
4982 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4983 SourceLocation LParenLoc,
4985 SourceLocation RParenLoc);
4987 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4988 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4989 SourceLocation PlacementLParen,
4990 MultiExprArg PlacementArgs,
4991 SourceLocation PlacementRParen,
4992 SourceRange TypeIdParens, Declarator &D,
4994 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4995 SourceLocation PlacementLParen,
4996 MultiExprArg PlacementArgs,
4997 SourceLocation PlacementRParen,
4998 SourceRange TypeIdParens,
5000 TypeSourceInfo *AllocTypeInfo,
5002 SourceRange DirectInitRange,
5005 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5007 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5008 bool UseGlobal, QualType AllocType, bool IsArray,
5009 bool &PassAlignment, MultiExprArg PlaceArgs,
5010 FunctionDecl *&OperatorNew,
5011 FunctionDecl *&OperatorDelete);
5012 void DeclareGlobalNewDelete();
5013 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5014 ArrayRef<QualType> Params);
5016 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5017 DeclarationName Name, FunctionDecl* &Operator,
5018 bool Diagnose = true);
5019 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5020 bool CanProvideSize,
5022 DeclarationName Name);
5023 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5026 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5027 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5028 bool UseGlobal, bool ArrayForm,
5030 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5031 bool IsDelete, bool CallCanBeVirtual,
5032 bool WarnOnNonAbstractTypes,
5033 SourceLocation DtorLoc);
5035 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5036 Expr *Operand, SourceLocation RParen);
5037 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5038 SourceLocation RParen);
5040 /// \brief Parsed one of the type trait support pseudo-functions.
5041 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5042 ArrayRef<ParsedType> Args,
5043 SourceLocation RParenLoc);
5044 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5045 ArrayRef<TypeSourceInfo *> Args,
5046 SourceLocation RParenLoc);
5048 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5049 /// pseudo-functions.
5050 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5051 SourceLocation KWLoc,
5054 SourceLocation RParen);
5056 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5057 SourceLocation KWLoc,
5058 TypeSourceInfo *TSInfo,
5060 SourceLocation RParen);
5062 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5063 /// pseudo-functions.
5064 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5065 SourceLocation KWLoc,
5067 SourceLocation RParen);
5069 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5070 SourceLocation KWLoc,
5072 SourceLocation RParen);
5074 ExprResult ActOnStartCXXMemberReference(Scope *S,
5076 SourceLocation OpLoc,
5077 tok::TokenKind OpKind,
5078 ParsedType &ObjectType,
5079 bool &MayBePseudoDestructor);
5081 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5082 SourceLocation OpLoc,
5083 tok::TokenKind OpKind,
5084 const CXXScopeSpec &SS,
5085 TypeSourceInfo *ScopeType,
5086 SourceLocation CCLoc,
5087 SourceLocation TildeLoc,
5088 PseudoDestructorTypeStorage DestroyedType);
5090 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5091 SourceLocation OpLoc,
5092 tok::TokenKind OpKind,
5094 UnqualifiedId &FirstTypeName,
5095 SourceLocation CCLoc,
5096 SourceLocation TildeLoc,
5097 UnqualifiedId &SecondTypeName);
5099 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5100 SourceLocation OpLoc,
5101 tok::TokenKind OpKind,
5102 SourceLocation TildeLoc,
5103 const DeclSpec& DS);
5105 /// MaybeCreateExprWithCleanups - If the current full-expression
5106 /// requires any cleanups, surround it with a ExprWithCleanups node.
5107 /// Otherwise, just returns the passed-in expression.
5108 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5109 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5110 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5112 MaterializeTemporaryExpr *
5113 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5114 bool BoundToLvalueReference);
5116 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5117 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5118 : SourceLocation());
5120 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5121 bool DiscardedValue = false,
5122 bool IsConstexpr = false,
5123 bool IsLambdaInitCaptureInitializer = false);
5124 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5126 // Marks SS invalid if it represents an incomplete type.
5127 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5129 DeclContext *computeDeclContext(QualType T);
5130 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5131 bool EnteringContext = false);
5132 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5133 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5135 /// \brief The parser has parsed a global nested-name-specifier '::'.
5137 /// \param CCLoc The location of the '::'.
5139 /// \param SS The nested-name-specifier, which will be updated in-place
5140 /// to reflect the parsed nested-name-specifier.
5142 /// \returns true if an error occurred, false otherwise.
5143 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5145 /// \brief The parser has parsed a '__super' nested-name-specifier.
5147 /// \param SuperLoc The location of the '__super' keyword.
5149 /// \param ColonColonLoc The location of the '::'.
5151 /// \param SS The nested-name-specifier, which will be updated in-place
5152 /// to reflect the parsed nested-name-specifier.
5154 /// \returns true if an error occurred, false otherwise.
5155 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5156 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5158 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5159 bool *CanCorrect = nullptr);
5160 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5162 /// \brief Keeps information about an identifier in a nested-name-spec.
5164 struct NestedNameSpecInfo {
5165 /// \brief The type of the object, if we're parsing nested-name-specifier in
5166 /// a member access expression.
5167 ParsedType ObjectType;
5169 /// \brief The identifier preceding the '::'.
5170 IdentifierInfo *Identifier;
5172 /// \brief The location of the identifier.
5173 SourceLocation IdentifierLoc;
5175 /// \brief The location of the '::'.
5176 SourceLocation CCLoc;
5178 /// \brief Creates info object for the most typical case.
5179 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5180 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5181 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5182 CCLoc(ColonColonLoc) {
5185 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5186 SourceLocation ColonColonLoc, QualType ObjectType)
5187 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5188 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5192 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5193 NestedNameSpecInfo &IdInfo);
5195 bool BuildCXXNestedNameSpecifier(Scope *S,
5196 NestedNameSpecInfo &IdInfo,
5197 bool EnteringContext,
5199 NamedDecl *ScopeLookupResult,
5200 bool ErrorRecoveryLookup,
5201 bool *IsCorrectedToColon = nullptr,
5202 bool OnlyNamespace = false);
5204 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5206 /// \param S The scope in which this nested-name-specifier occurs.
5208 /// \param IdInfo Parser information about an identifier in the
5209 /// nested-name-spec.
5211 /// \param EnteringContext Whether we're entering the context nominated by
5212 /// this nested-name-specifier.
5214 /// \param SS The nested-name-specifier, which is both an input
5215 /// parameter (the nested-name-specifier before this type) and an
5216 /// output parameter (containing the full nested-name-specifier,
5217 /// including this new type).
5219 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5220 /// error recovery. In this case do not emit error message.
5222 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5223 /// are allowed. The bool value pointed by this parameter is set to 'true'
5224 /// if the identifier is treated as if it was followed by ':', not '::'.
5226 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5228 /// \returns true if an error occurred, false otherwise.
5229 bool ActOnCXXNestedNameSpecifier(Scope *S,
5230 NestedNameSpecInfo &IdInfo,
5231 bool EnteringContext,
5233 bool ErrorRecoveryLookup = false,
5234 bool *IsCorrectedToColon = nullptr,
5235 bool OnlyNamespace = false);
5237 ExprResult ActOnDecltypeExpression(Expr *E);
5239 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5241 SourceLocation ColonColonLoc);
5243 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5244 NestedNameSpecInfo &IdInfo,
5245 bool EnteringContext);
5247 /// \brief The parser has parsed a nested-name-specifier
5248 /// 'template[opt] template-name < template-args >::'.
5250 /// \param S The scope in which this nested-name-specifier occurs.
5252 /// \param SS The nested-name-specifier, which is both an input
5253 /// parameter (the nested-name-specifier before this type) and an
5254 /// output parameter (containing the full nested-name-specifier,
5255 /// including this new type).
5257 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5258 /// \param TemplateName the template name.
5259 /// \param TemplateNameLoc The location of the template name.
5260 /// \param LAngleLoc The location of the opening angle bracket ('<').
5261 /// \param TemplateArgs The template arguments.
5262 /// \param RAngleLoc The location of the closing angle bracket ('>').
5263 /// \param CCLoc The location of the '::'.
5265 /// \param EnteringContext Whether we're entering the context of the
5266 /// nested-name-specifier.
5269 /// \returns true if an error occurred, false otherwise.
5270 bool ActOnCXXNestedNameSpecifier(Scope *S,
5272 SourceLocation TemplateKWLoc,
5273 TemplateTy TemplateName,
5274 SourceLocation TemplateNameLoc,
5275 SourceLocation LAngleLoc,
5276 ASTTemplateArgsPtr TemplateArgs,
5277 SourceLocation RAngleLoc,
5278 SourceLocation CCLoc,
5279 bool EnteringContext);
5281 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5282 /// that the parser can use later to reconstruct the given
5283 /// nested-name-specifier.
5285 /// \param SS A nested-name-specifier.
5287 /// \returns A pointer containing all of the information in the
5288 /// nested-name-specifier \p SS.
5289 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5291 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5292 /// the nested-name-specifier structure.
5294 /// \param Annotation The annotation pointer, produced by
5295 /// \c SaveNestedNameSpecifierAnnotation().
5297 /// \param AnnotationRange The source range corresponding to the annotation.
5299 /// \param SS The nested-name-specifier that will be updated with the contents
5300 /// of the annotation pointer.
5301 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5302 SourceRange AnnotationRange,
5305 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5307 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5308 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5309 /// After this method is called, according to [C++ 3.4.3p3], names should be
5310 /// looked up in the declarator-id's scope, until the declarator is parsed and
5311 /// ActOnCXXExitDeclaratorScope is called.
5312 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5313 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5315 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5316 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5317 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5318 /// Used to indicate that names should revert to being looked up in the
5320 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5322 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5323 /// initializer for the declaration 'Dcl'.
5324 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5325 /// static data member of class X, names should be looked up in the scope of
5327 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5329 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5330 /// initializer for the declaration 'Dcl'.
5331 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5333 /// \brief Create a new lambda closure type.
5334 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5335 TypeSourceInfo *Info,
5336 bool KnownDependent,
5337 LambdaCaptureDefault CaptureDefault);
5339 /// \brief Start the definition of a lambda expression.
5340 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5341 SourceRange IntroducerRange,
5342 TypeSourceInfo *MethodType,
5343 SourceLocation EndLoc,
5344 ArrayRef<ParmVarDecl *> Params,
5345 bool IsConstexprSpecified);
5347 /// \brief Endow the lambda scope info with the relevant properties.
5348 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5349 CXXMethodDecl *CallOperator,
5350 SourceRange IntroducerRange,
5351 LambdaCaptureDefault CaptureDefault,
5352 SourceLocation CaptureDefaultLoc,
5353 bool ExplicitParams,
5354 bool ExplicitResultType,
5357 /// \brief Perform initialization analysis of the init-capture and perform
5358 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5359 /// not being used to initialize a reference.
5360 ParsedType actOnLambdaInitCaptureInitialization(
5361 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5362 LambdaCaptureInitKind InitKind, Expr *&Init) {
5363 return ParsedType::make(buildLambdaInitCaptureInitialization(
5364 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5366 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5368 bool DirectInit, Expr *&Init);
5370 /// \brief Create a dummy variable within the declcontext of the lambda's
5371 /// call operator, for name lookup purposes for a lambda init capture.
5373 /// CodeGen handles emission of lambda captures, ignoring these dummy
5374 /// variables appropriately.
5375 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5376 QualType InitCaptureType,
5378 unsigned InitStyle, Expr *Init);
5380 /// \brief Build the implicit field for an init-capture.
5381 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5383 /// \brief Note that we have finished the explicit captures for the
5385 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5387 /// \brief Introduce the lambda parameters into scope.
5388 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5390 /// \brief Deduce a block or lambda's return type based on the return
5391 /// statements present in the body.
5392 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5394 /// ActOnStartOfLambdaDefinition - This is called just before we start
5395 /// parsing the body of a lambda; it analyzes the explicit captures and
5396 /// arguments, and sets up various data-structures for the body of the
5398 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5399 Declarator &ParamInfo, Scope *CurScope);
5401 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5402 /// is invoked to pop the information about the lambda.
5403 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5404 bool IsInstantiation = false);
5406 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5407 /// was successfully completed.
5408 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5411 /// \brief Does copying/destroying the captured variable have side effects?
5412 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5414 /// \brief Diagnose if an explicit lambda capture is unused.
5415 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5417 /// \brief Complete a lambda-expression having processed and attached the
5419 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5420 sema::LambdaScopeInfo *LSI);
5422 /// \brief Define the "body" of the conversion from a lambda object to a
5423 /// function pointer.
5425 /// This routine doesn't actually define a sensible body; rather, it fills
5426 /// in the initialization expression needed to copy the lambda object into
5427 /// the block, and IR generation actually generates the real body of the
5428 /// block pointer conversion.
5429 void DefineImplicitLambdaToFunctionPointerConversion(
5430 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5432 /// \brief Define the "body" of the conversion from a lambda object to a
5435 /// This routine doesn't actually define a sensible body; rather, it fills
5436 /// in the initialization expression needed to copy the lambda object into
5437 /// the block, and IR generation actually generates the real body of the
5438 /// block pointer conversion.
5439 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5440 CXXConversionDecl *Conv);
5442 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5443 SourceLocation ConvLocation,
5444 CXXConversionDecl *Conv,
5447 // ParseObjCStringLiteral - Parse Objective-C string literals.
5448 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5449 ArrayRef<Expr *> Strings);
5451 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5453 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5454 /// numeric literal expression. Type of the expression will be "NSNumber *"
5455 /// or "id" if NSNumber is unavailable.
5456 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5457 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5459 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5461 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5462 /// '@' prefixed parenthesized expression. The type of the expression will
5463 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5464 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5465 /// "const char *" or C structure with attribute 'objc_boxable'.
5466 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5468 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5470 ObjCMethodDecl *getterMethod,
5471 ObjCMethodDecl *setterMethod);
5473 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5474 MutableArrayRef<ObjCDictionaryElement> Elements);
5476 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5477 TypeSourceInfo *EncodedTypeInfo,
5478 SourceLocation RParenLoc);
5479 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5480 CXXConversionDecl *Method,
5481 bool HadMultipleCandidates);
5483 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5484 SourceLocation EncodeLoc,
5485 SourceLocation LParenLoc,
5487 SourceLocation RParenLoc);
5489 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5490 ExprResult ParseObjCSelectorExpression(Selector Sel,
5491 SourceLocation AtLoc,
5492 SourceLocation SelLoc,
5493 SourceLocation LParenLoc,
5494 SourceLocation RParenLoc,
5495 bool WarnMultipleSelectors);
5497 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5498 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5499 SourceLocation AtLoc,
5500 SourceLocation ProtoLoc,
5501 SourceLocation LParenLoc,
5502 SourceLocation ProtoIdLoc,
5503 SourceLocation RParenLoc);
5505 //===--------------------------------------------------------------------===//
5508 Decl *ActOnStartLinkageSpecification(Scope *S,
5509 SourceLocation ExternLoc,
5511 SourceLocation LBraceLoc);
5512 Decl *ActOnFinishLinkageSpecification(Scope *S,
5514 SourceLocation RBraceLoc);
5517 //===--------------------------------------------------------------------===//
5520 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5521 const CXXScopeSpec *SS = nullptr);
5522 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5524 bool ActOnAccessSpecifier(AccessSpecifier Access,
5525 SourceLocation ASLoc,
5526 SourceLocation ColonLoc,
5527 AttributeList *Attrs = nullptr);
5529 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5531 MultiTemplateParamsArg TemplateParameterLists,
5532 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5533 InClassInitStyle InitStyle);
5535 void ActOnStartCXXInClassMemberInitializer();
5536 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5537 SourceLocation EqualLoc,
5540 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5543 IdentifierInfo *MemberOrBase,
5544 ParsedType TemplateTypeTy,
5546 SourceLocation IdLoc,
5547 SourceLocation LParenLoc,
5548 ArrayRef<Expr *> Args,
5549 SourceLocation RParenLoc,
5550 SourceLocation EllipsisLoc);
5552 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5555 IdentifierInfo *MemberOrBase,
5556 ParsedType TemplateTypeTy,
5558 SourceLocation IdLoc,
5560 SourceLocation EllipsisLoc);
5562 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5565 IdentifierInfo *MemberOrBase,
5566 ParsedType TemplateTypeTy,
5568 SourceLocation IdLoc,
5570 SourceLocation EllipsisLoc);
5572 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5574 SourceLocation IdLoc);
5576 MemInitResult BuildBaseInitializer(QualType BaseType,
5577 TypeSourceInfo *BaseTInfo,
5579 CXXRecordDecl *ClassDecl,
5580 SourceLocation EllipsisLoc);
5582 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5584 CXXRecordDecl *ClassDecl);
5586 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5587 CXXCtorInitializer *Initializer);
5589 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5590 ArrayRef<CXXCtorInitializer *> Initializers = None);
5592 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5595 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5596 /// mark all the non-trivial destructors of its members and bases as
5598 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5599 CXXRecordDecl *Record);
5601 /// \brief The list of classes whose vtables have been used within
5602 /// this translation unit, and the source locations at which the
5603 /// first use occurred.
5604 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5606 /// \brief The list of vtables that are required but have not yet been
5608 SmallVector<VTableUse, 16> VTableUses;
5610 /// \brief The set of classes whose vtables have been used within
5611 /// this translation unit, and a bit that will be true if the vtable is
5612 /// required to be emitted (otherwise, it should be emitted only if needed
5613 /// by code generation).
5614 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5616 /// \brief Load any externally-stored vtable uses.
5617 void LoadExternalVTableUses();
5619 /// \brief Note that the vtable for the given class was used at the
5621 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5622 bool DefinitionRequired = false);
5624 /// \brief Mark the exception specifications of all virtual member functions
5625 /// in the given class as needed.
5626 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5627 const CXXRecordDecl *RD);
5629 /// MarkVirtualMembersReferenced - Will mark all members of the given
5630 /// CXXRecordDecl referenced.
5631 void MarkVirtualMembersReferenced(SourceLocation Loc,
5632 const CXXRecordDecl *RD);
5634 /// \brief Define all of the vtables that have been used in this
5635 /// translation unit and reference any virtual members used by those
5638 /// \returns true if any work was done, false otherwise.
5639 bool DefineUsedVTables();
5641 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5643 void ActOnMemInitializers(Decl *ConstructorDecl,
5644 SourceLocation ColonLoc,
5645 ArrayRef<CXXCtorInitializer*> MemInits,
5648 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5649 /// ensure that referenceDLLExportedClassMethods is called some point later
5650 /// when all outer classes of Class are complete.
5651 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5653 void referenceDLLExportedClassMethods();
5655 void propagateDLLAttrToBaseClassTemplate(
5656 CXXRecordDecl *Class, Attr *ClassAttr,
5657 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5658 SourceLocation BaseLoc);
5660 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5661 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5663 SourceLocation LBrac,
5664 SourceLocation RBrac,
5665 AttributeList *AttrList);
5666 void ActOnFinishCXXMemberDecls();
5667 void ActOnFinishCXXNonNestedClass(Decl *D);
5669 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5670 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5671 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5672 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5673 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5674 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5675 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5676 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5677 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5678 CachedTokens &Toks);
5679 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5680 bool IsInsideALocalClassWithinATemplateFunction();
5682 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5684 Expr *AssertMessageExpr,
5685 SourceLocation RParenLoc);
5686 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5688 StringLiteral *AssertMessageExpr,
5689 SourceLocation RParenLoc,
5692 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5693 SourceLocation FriendLoc,
5694 TypeSourceInfo *TSInfo);
5695 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5696 MultiTemplateParamsArg TemplateParams);
5697 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5698 MultiTemplateParamsArg TemplateParams);
5700 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5702 void CheckConstructor(CXXConstructorDecl *Constructor);
5703 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5705 bool CheckDestructor(CXXDestructorDecl *Destructor);
5706 void CheckConversionDeclarator(Declarator &D, QualType &R,
5708 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5709 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5711 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5713 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5714 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5715 const FunctionProtoType *T);
5716 void CheckDelayedMemberExceptionSpecs();
5718 //===--------------------------------------------------------------------===//
5719 // C++ Derived Classes
5722 /// ActOnBaseSpecifier - Parsed a base specifier
5723 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5724 SourceRange SpecifierRange,
5725 bool Virtual, AccessSpecifier Access,
5726 TypeSourceInfo *TInfo,
5727 SourceLocation EllipsisLoc);
5729 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5730 SourceRange SpecifierRange,
5731 ParsedAttributes &Attrs,
5732 bool Virtual, AccessSpecifier Access,
5733 ParsedType basetype,
5734 SourceLocation BaseLoc,
5735 SourceLocation EllipsisLoc);
5737 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5738 MutableArrayRef<CXXBaseSpecifier *> Bases);
5739 void ActOnBaseSpecifiers(Decl *ClassDecl,
5740 MutableArrayRef<CXXBaseSpecifier *> Bases);
5742 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5743 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5744 CXXBasePaths &Paths);
5746 // FIXME: I don't like this name.
5747 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5749 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5750 SourceLocation Loc, SourceRange Range,
5751 CXXCastPath *BasePath = nullptr,
5752 bool IgnoreAccess = false);
5753 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5754 unsigned InaccessibleBaseID,
5755 unsigned AmbigiousBaseConvID,
5756 SourceLocation Loc, SourceRange Range,
5757 DeclarationName Name,
5758 CXXCastPath *BasePath,
5759 bool IgnoreAccess = false);
5761 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5763 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5764 const CXXMethodDecl *Old);
5766 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5767 /// covariant, according to C++ [class.virtual]p5.
5768 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5769 const CXXMethodDecl *Old);
5771 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5772 /// spec is a subset of base spec.
5773 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5774 const CXXMethodDecl *Old);
5776 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5778 /// CheckOverrideControl - Check C++11 override control semantics.
5779 void CheckOverrideControl(NamedDecl *D);
5781 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5782 /// not used in the declaration of an overriding method.
5783 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5785 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5786 /// overrides a virtual member function marked 'final', according to
5787 /// C++11 [class.virtual]p4.
5788 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5789 const CXXMethodDecl *Old);
5792 //===--------------------------------------------------------------------===//
5793 // C++ Access Control
5803 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5804 NamedDecl *PrevMemberDecl,
5805 AccessSpecifier LexicalAS);
5807 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5808 DeclAccessPair FoundDecl);
5809 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5810 DeclAccessPair FoundDecl);
5811 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5812 SourceRange PlacementRange,
5813 CXXRecordDecl *NamingClass,
5814 DeclAccessPair FoundDecl,
5815 bool Diagnose = true);
5816 AccessResult CheckConstructorAccess(SourceLocation Loc,
5817 CXXConstructorDecl *D,
5818 DeclAccessPair FoundDecl,
5819 const InitializedEntity &Entity,
5820 bool IsCopyBindingRefToTemp = false);
5821 AccessResult CheckConstructorAccess(SourceLocation Loc,
5822 CXXConstructorDecl *D,
5823 DeclAccessPair FoundDecl,
5824 const InitializedEntity &Entity,
5825 const PartialDiagnostic &PDiag);
5826 AccessResult CheckDestructorAccess(SourceLocation Loc,
5827 CXXDestructorDecl *Dtor,
5828 const PartialDiagnostic &PDiag,
5829 QualType objectType = QualType());
5830 AccessResult CheckFriendAccess(NamedDecl *D);
5831 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5832 CXXRecordDecl *NamingClass,
5833 DeclAccessPair Found);
5834 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5837 DeclAccessPair FoundDecl);
5838 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5839 DeclAccessPair FoundDecl);
5840 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5841 QualType Base, QualType Derived,
5842 const CXXBasePath &Path,
5844 bool ForceCheck = false,
5845 bool ForceUnprivileged = false);
5846 void CheckLookupAccess(const LookupResult &R);
5847 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5848 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5849 AccessSpecifier access,
5850 QualType objectType);
5852 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5853 const MultiLevelTemplateArgumentList &TemplateArgs);
5854 void PerformDependentDiagnostics(const DeclContext *Pattern,
5855 const MultiLevelTemplateArgumentList &TemplateArgs);
5857 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5859 /// \brief When true, access checking violations are treated as SFINAE
5860 /// failures rather than hard errors.
5861 bool AccessCheckingSFINAE;
5863 enum AbstractDiagSelID {
5867 AbstractVariableType,
5870 AbstractSynthesizedIvarType,
5874 bool isAbstractType(SourceLocation Loc, QualType T);
5875 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5876 TypeDiagnoser &Diagnoser);
5877 template <typename... Ts>
5878 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5879 const Ts &...Args) {
5880 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5881 return RequireNonAbstractType(Loc, T, Diagnoser);
5884 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5886 //===--------------------------------------------------------------------===//
5887 // C++ Overloaded Operators [C++ 13.5]
5890 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5892 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5894 //===--------------------------------------------------------------------===//
5895 // C++ Templates [C++ 14]
5897 void FilterAcceptableTemplateNames(LookupResult &R,
5898 bool AllowFunctionTemplates = true);
5899 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5900 bool AllowFunctionTemplates = true);
5902 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5903 QualType ObjectType, bool EnteringContext,
5904 bool &MemberOfUnknownSpecialization);
5906 TemplateNameKind isTemplateName(Scope *S,
5908 bool hasTemplateKeyword,
5909 UnqualifiedId &Name,
5910 ParsedType ObjectType,
5911 bool EnteringContext,
5912 TemplateTy &Template,
5913 bool &MemberOfUnknownSpecialization);
5915 /// Determine whether a particular identifier might be the name in a C++1z
5916 /// deduction-guide declaration.
5917 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5918 SourceLocation NameLoc,
5919 ParsedTemplateTy *Template = nullptr);
5921 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5922 SourceLocation IILoc,
5924 const CXXScopeSpec *SS,
5925 TemplateTy &SuggestedTemplate,
5926 TemplateNameKind &SuggestedKind);
5928 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5929 NamedDecl *Instantiation,
5930 bool InstantiatedFromMember,
5931 const NamedDecl *Pattern,
5932 const NamedDecl *PatternDef,
5933 TemplateSpecializationKind TSK,
5934 bool Complain = true);
5936 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5937 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5939 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5940 SourceLocation EllipsisLoc,
5941 SourceLocation KeyLoc,
5942 IdentifierInfo *ParamName,
5943 SourceLocation ParamNameLoc,
5944 unsigned Depth, unsigned Position,
5945 SourceLocation EqualLoc,
5946 ParsedType DefaultArg);
5948 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5949 SourceLocation Loc);
5950 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5952 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5955 SourceLocation EqualLoc,
5957 Decl *ActOnTemplateTemplateParameter(Scope *S,
5958 SourceLocation TmpLoc,
5959 TemplateParameterList *Params,
5960 SourceLocation EllipsisLoc,
5961 IdentifierInfo *ParamName,
5962 SourceLocation ParamNameLoc,
5965 SourceLocation EqualLoc,
5966 ParsedTemplateArgument DefaultArg);
5968 TemplateParameterList *
5969 ActOnTemplateParameterList(unsigned Depth,
5970 SourceLocation ExportLoc,
5971 SourceLocation TemplateLoc,
5972 SourceLocation LAngleLoc,
5973 ArrayRef<Decl *> Params,
5974 SourceLocation RAngleLoc,
5975 Expr *RequiresClause);
5977 /// \brief The context in which we are checking a template parameter list.
5978 enum TemplateParamListContext {
5981 TPC_FunctionTemplate,
5982 TPC_ClassTemplateMember,
5983 TPC_FriendClassTemplate,
5984 TPC_FriendFunctionTemplate,
5985 TPC_FriendFunctionTemplateDefinition,
5986 TPC_TypeAliasTemplate
5989 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5990 TemplateParameterList *OldParams,
5991 TemplateParamListContext TPC);
5992 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5993 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5994 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5995 ArrayRef<TemplateParameterList *> ParamLists,
5996 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5998 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5999 SourceLocation KWLoc, CXXScopeSpec &SS,
6000 IdentifierInfo *Name, SourceLocation NameLoc,
6001 AttributeList *Attr,
6002 TemplateParameterList *TemplateParams,
6004 SourceLocation ModulePrivateLoc,
6005 SourceLocation FriendLoc,
6006 unsigned NumOuterTemplateParamLists,
6007 TemplateParameterList **OuterTemplateParamLists,
6008 SkipBodyInfo *SkipBody = nullptr);
6010 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6012 SourceLocation Loc);
6014 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6015 TemplateArgumentListInfo &Out);
6017 void NoteAllFoundTemplates(TemplateName Name);
6019 QualType CheckTemplateIdType(TemplateName Template,
6020 SourceLocation TemplateLoc,
6021 TemplateArgumentListInfo &TemplateArgs);
6024 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6025 TemplateTy Template, IdentifierInfo *TemplateII,
6026 SourceLocation TemplateIILoc,
6027 SourceLocation LAngleLoc,
6028 ASTTemplateArgsPtr TemplateArgs,
6029 SourceLocation RAngleLoc,
6030 bool IsCtorOrDtorName = false,
6031 bool IsClassName = false);
6033 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6034 /// such as \c class T::template apply<U>.
6035 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6036 TypeSpecifierType TagSpec,
6037 SourceLocation TagLoc,
6039 SourceLocation TemplateKWLoc,
6040 TemplateTy TemplateD,
6041 SourceLocation TemplateLoc,
6042 SourceLocation LAngleLoc,
6043 ASTTemplateArgsPtr TemplateArgsIn,
6044 SourceLocation RAngleLoc);
6046 DeclResult ActOnVarTemplateSpecialization(
6047 Scope *S, Declarator &D, TypeSourceInfo *DI,
6048 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6049 StorageClass SC, bool IsPartialSpecialization);
6051 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6052 SourceLocation TemplateLoc,
6053 SourceLocation TemplateNameLoc,
6054 const TemplateArgumentListInfo &TemplateArgs);
6056 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6057 const DeclarationNameInfo &NameInfo,
6058 VarTemplateDecl *Template,
6059 SourceLocation TemplateLoc,
6060 const TemplateArgumentListInfo *TemplateArgs);
6062 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6063 SourceLocation TemplateKWLoc,
6066 const TemplateArgumentListInfo *TemplateArgs);
6068 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6069 SourceLocation TemplateKWLoc,
6070 const DeclarationNameInfo &NameInfo,
6071 const TemplateArgumentListInfo *TemplateArgs);
6073 TemplateNameKind ActOnDependentTemplateName(
6074 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6075 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6076 TemplateTy &Template, bool AllowInjectedClassName = false);
6079 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6080 SourceLocation KWLoc,
6081 SourceLocation ModulePrivateLoc,
6082 TemplateIdAnnotation &TemplateId,
6083 AttributeList *Attr,
6084 MultiTemplateParamsArg TemplateParameterLists,
6085 SkipBodyInfo *SkipBody = nullptr);
6087 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6088 TemplateDecl *PrimaryTemplate,
6089 unsigned NumExplicitArgs,
6090 ArrayRef<TemplateArgument> Args);
6091 void CheckTemplatePartialSpecialization(
6092 ClassTemplatePartialSpecializationDecl *Partial);
6093 void CheckTemplatePartialSpecialization(
6094 VarTemplatePartialSpecializationDecl *Partial);
6096 Decl *ActOnTemplateDeclarator(Scope *S,
6097 MultiTemplateParamsArg TemplateParameterLists,
6101 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6102 TemplateSpecializationKind NewTSK,
6103 NamedDecl *PrevDecl,
6104 TemplateSpecializationKind PrevTSK,
6105 SourceLocation PrevPtOfInstantiation,
6108 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6109 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6110 LookupResult &Previous);
6112 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6113 TemplateArgumentListInfo *ExplicitTemplateArgs,
6114 LookupResult &Previous);
6115 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6116 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6119 ActOnExplicitInstantiation(Scope *S,
6120 SourceLocation ExternLoc,
6121 SourceLocation TemplateLoc,
6123 SourceLocation KWLoc,
6124 const CXXScopeSpec &SS,
6125 TemplateTy Template,
6126 SourceLocation TemplateNameLoc,
6127 SourceLocation LAngleLoc,
6128 ASTTemplateArgsPtr TemplateArgs,
6129 SourceLocation RAngleLoc,
6130 AttributeList *Attr);
6133 ActOnExplicitInstantiation(Scope *S,
6134 SourceLocation ExternLoc,
6135 SourceLocation TemplateLoc,
6137 SourceLocation KWLoc,
6139 IdentifierInfo *Name,
6140 SourceLocation NameLoc,
6141 AttributeList *Attr);
6143 DeclResult ActOnExplicitInstantiation(Scope *S,
6144 SourceLocation ExternLoc,
6145 SourceLocation TemplateLoc,
6149 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6150 SourceLocation TemplateLoc,
6151 SourceLocation RAngleLoc,
6153 SmallVectorImpl<TemplateArgument>
6155 bool &HasDefaultArg);
6157 /// \brief Specifies the context in which a particular template
6158 /// argument is being checked.
6159 enum CheckTemplateArgumentKind {
6160 /// \brief The template argument was specified in the code or was
6161 /// instantiated with some deduced template arguments.
6164 /// \brief The template argument was deduced via template argument
6168 /// \brief The template argument was deduced from an array bound
6169 /// via template argument deduction.
6170 CTAK_DeducedFromArrayBound
6173 bool CheckTemplateArgument(NamedDecl *Param,
6174 TemplateArgumentLoc &Arg,
6175 NamedDecl *Template,
6176 SourceLocation TemplateLoc,
6177 SourceLocation RAngleLoc,
6178 unsigned ArgumentPackIndex,
6179 SmallVectorImpl<TemplateArgument> &Converted,
6180 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6182 /// \brief Check that the given template arguments can be be provided to
6183 /// the given template, converting the arguments along the way.
6185 /// \param Template The template to which the template arguments are being
6188 /// \param TemplateLoc The location of the template name in the source.
6190 /// \param TemplateArgs The list of template arguments. If the template is
6191 /// a template template parameter, this function may extend the set of
6192 /// template arguments to also include substituted, defaulted template
6195 /// \param PartialTemplateArgs True if the list of template arguments is
6196 /// intentionally partial, e.g., because we're checking just the initial
6197 /// set of template arguments.
6199 /// \param Converted Will receive the converted, canonicalized template
6202 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6203 /// contain the converted forms of the template arguments as written.
6204 /// Otherwise, \p TemplateArgs will not be modified.
6206 /// \returns true if an error occurred, false otherwise.
6207 bool CheckTemplateArgumentList(TemplateDecl *Template,
6208 SourceLocation TemplateLoc,
6209 TemplateArgumentListInfo &TemplateArgs,
6210 bool PartialTemplateArgs,
6211 SmallVectorImpl<TemplateArgument> &Converted,
6212 bool UpdateArgsWithConversions = true);
6214 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6215 TemplateArgumentLoc &Arg,
6216 SmallVectorImpl<TemplateArgument> &Converted);
6218 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6219 TypeSourceInfo *Arg);
6220 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6221 QualType InstantiatedParamType, Expr *Arg,
6222 TemplateArgument &Converted,
6223 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6224 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6225 TemplateArgumentLoc &Arg,
6226 unsigned ArgumentPackIndex);
6229 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6231 SourceLocation Loc);
6233 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6234 SourceLocation Loc);
6236 /// \brief Enumeration describing how template parameter lists are compared
6238 enum TemplateParameterListEqualKind {
6239 /// \brief We are matching the template parameter lists of two templates
6240 /// that might be redeclarations.
6243 /// template<typename T> struct X;
6244 /// template<typename T> struct X;
6248 /// \brief We are matching the template parameter lists of two template
6249 /// template parameters as part of matching the template parameter lists
6250 /// of two templates that might be redeclarations.
6253 /// template<template<int I> class TT> struct X;
6254 /// template<template<int Value> class Other> struct X;
6256 TPL_TemplateTemplateParmMatch,
6258 /// \brief We are matching the template parameter lists of a template
6259 /// template argument against the template parameter lists of a template
6260 /// template parameter.
6263 /// template<template<int Value> class Metafun> struct X;
6264 /// template<int Value> struct integer_c;
6265 /// X<integer_c> xic;
6267 TPL_TemplateTemplateArgumentMatch
6270 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6271 TemplateParameterList *Old,
6273 TemplateParameterListEqualKind Kind,
6274 SourceLocation TemplateArgLoc
6275 = SourceLocation());
6277 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6279 /// \brief Called when the parser has parsed a C++ typename
6280 /// specifier, e.g., "typename T::type".
6282 /// \param S The scope in which this typename type occurs.
6283 /// \param TypenameLoc the location of the 'typename' keyword
6284 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6285 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6286 /// \param IdLoc the location of the identifier.
6288 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6289 const CXXScopeSpec &SS, const IdentifierInfo &II,
6290 SourceLocation IdLoc);
6292 /// \brief Called when the parser has parsed a C++ typename
6293 /// specifier that ends in a template-id, e.g.,
6294 /// "typename MetaFun::template apply<T1, T2>".
6296 /// \param S The scope in which this typename type occurs.
6297 /// \param TypenameLoc the location of the 'typename' keyword
6298 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6299 /// \param TemplateLoc the location of the 'template' keyword, if any.
6300 /// \param TemplateName The template name.
6301 /// \param TemplateII The identifier used to name the template.
6302 /// \param TemplateIILoc The location of the template name.
6303 /// \param LAngleLoc The location of the opening angle bracket ('<').
6304 /// \param TemplateArgs The template arguments.
6305 /// \param RAngleLoc The location of the closing angle bracket ('>').
6307 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6308 const CXXScopeSpec &SS,
6309 SourceLocation TemplateLoc,
6310 TemplateTy TemplateName,
6311 IdentifierInfo *TemplateII,
6312 SourceLocation TemplateIILoc,
6313 SourceLocation LAngleLoc,
6314 ASTTemplateArgsPtr TemplateArgs,
6315 SourceLocation RAngleLoc);
6317 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6318 SourceLocation KeywordLoc,
6319 NestedNameSpecifierLoc QualifierLoc,
6320 const IdentifierInfo &II,
6321 SourceLocation IILoc);
6323 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6325 DeclarationName Name);
6326 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6328 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6329 bool RebuildTemplateParamsInCurrentInstantiation(
6330 TemplateParameterList *Params);
6333 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6334 const TemplateArgumentList &Args);
6337 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6338 const TemplateArgument *Args,
6341 //===--------------------------------------------------------------------===//
6342 // C++ Variadic Templates (C++0x [temp.variadic])
6343 //===--------------------------------------------------------------------===//
6345 /// Determine whether an unexpanded parameter pack might be permitted in this
6346 /// location. Useful for error recovery.
6347 bool isUnexpandedParameterPackPermitted();
6349 /// \brief The context in which an unexpanded parameter pack is
6350 /// being diagnosed.
6352 /// Note that the values of this enumeration line up with the first
6353 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6354 enum UnexpandedParameterPackContext {
6355 /// \brief An arbitrary expression.
6356 UPPC_Expression = 0,
6358 /// \brief The base type of a class type.
6361 /// \brief The type of an arbitrary declaration.
6362 UPPC_DeclarationType,
6364 /// \brief The type of a data member.
6365 UPPC_DataMemberType,
6367 /// \brief The size of a bit-field.
6370 /// \brief The expression in a static assertion.
6371 UPPC_StaticAssertExpression,
6373 /// \brief The fixed underlying type of an enumeration.
6374 UPPC_FixedUnderlyingType,
6376 /// \brief The enumerator value.
6377 UPPC_EnumeratorValue,
6379 /// \brief A using declaration.
6380 UPPC_UsingDeclaration,
6382 /// \brief A friend declaration.
6383 UPPC_FriendDeclaration,
6385 /// \brief A declaration qualifier.
6386 UPPC_DeclarationQualifier,
6388 /// \brief An initializer.
6391 /// \brief A default argument.
6392 UPPC_DefaultArgument,
6394 /// \brief The type of a non-type template parameter.
6395 UPPC_NonTypeTemplateParameterType,
6397 /// \brief The type of an exception.
6400 /// \brief Partial specialization.
6401 UPPC_PartialSpecialization,
6403 /// \brief Microsoft __if_exists.
6406 /// \brief Microsoft __if_not_exists.
6409 /// \brief Lambda expression.
6412 /// \brief Block expression,
6416 /// \brief Diagnose unexpanded parameter packs.
6418 /// \param Loc The location at which we should emit the diagnostic.
6420 /// \param UPPC The context in which we are diagnosing unexpanded
6421 /// parameter packs.
6423 /// \param Unexpanded the set of unexpanded parameter packs.
6425 /// \returns true if an error occurred, false otherwise.
6426 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6427 UnexpandedParameterPackContext UPPC,
6428 ArrayRef<UnexpandedParameterPack> Unexpanded);
6430 /// \brief If the given type contains an unexpanded parameter pack,
6431 /// diagnose the error.
6433 /// \param Loc The source location where a diagnostc should be emitted.
6435 /// \param T The type that is being checked for unexpanded parameter
6438 /// \returns true if an error occurred, false otherwise.
6439 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6440 UnexpandedParameterPackContext UPPC);
6442 /// \brief If the given expression contains an unexpanded parameter
6443 /// pack, diagnose the error.
6445 /// \param E The expression that is being checked for unexpanded
6446 /// parameter packs.
6448 /// \returns true if an error occurred, false otherwise.
6449 bool DiagnoseUnexpandedParameterPack(Expr *E,
6450 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6452 /// \brief If the given nested-name-specifier contains an unexpanded
6453 /// parameter pack, diagnose the error.
6455 /// \param SS The nested-name-specifier that is being checked for
6456 /// unexpanded parameter packs.
6458 /// \returns true if an error occurred, false otherwise.
6459 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6460 UnexpandedParameterPackContext UPPC);
6462 /// \brief If the given name contains an unexpanded parameter pack,
6463 /// diagnose the error.
6465 /// \param NameInfo The name (with source location information) that
6466 /// is being checked for unexpanded parameter packs.
6468 /// \returns true if an error occurred, false otherwise.
6469 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6470 UnexpandedParameterPackContext UPPC);
6472 /// \brief If the given template name contains an unexpanded parameter pack,
6473 /// diagnose the error.
6475 /// \param Loc The location of the template name.
6477 /// \param Template The template name that is being checked for unexpanded
6478 /// parameter packs.
6480 /// \returns true if an error occurred, false otherwise.
6481 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6482 TemplateName Template,
6483 UnexpandedParameterPackContext UPPC);
6485 /// \brief If the given template argument contains an unexpanded parameter
6486 /// pack, diagnose the error.
6488 /// \param Arg The template argument that is being checked for unexpanded
6489 /// parameter packs.
6491 /// \returns true if an error occurred, false otherwise.
6492 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6493 UnexpandedParameterPackContext UPPC);
6495 /// \brief Collect the set of unexpanded parameter packs within the given
6496 /// template argument.
6498 /// \param Arg The template argument that will be traversed to find
6499 /// unexpanded parameter packs.
6500 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6501 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6503 /// \brief Collect the set of unexpanded parameter packs within the given
6504 /// template argument.
6506 /// \param Arg The template argument that will be traversed to find
6507 /// unexpanded parameter packs.
6508 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6509 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6511 /// \brief Collect the set of unexpanded parameter packs within the given
6514 /// \param T The type that will be traversed to find
6515 /// unexpanded parameter packs.
6516 void collectUnexpandedParameterPacks(QualType T,
6517 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6519 /// \brief Collect the set of unexpanded parameter packs within the given
6522 /// \param TL The type that will be traversed to find
6523 /// unexpanded parameter packs.
6524 void collectUnexpandedParameterPacks(TypeLoc TL,
6525 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6527 /// \brief Collect the set of unexpanded parameter packs within the given
6528 /// nested-name-specifier.
6530 /// \param NNS The nested-name-specifier that will be traversed to find
6531 /// unexpanded parameter packs.
6532 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6533 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6535 /// \brief Collect the set of unexpanded parameter packs within the given
6538 /// \param NameInfo The name that will be traversed to find
6539 /// unexpanded parameter packs.
6540 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6541 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6543 /// \brief Invoked when parsing a template argument followed by an
6544 /// ellipsis, which creates a pack expansion.
6546 /// \param Arg The template argument preceding the ellipsis, which
6547 /// may already be invalid.
6549 /// \param EllipsisLoc The location of the ellipsis.
6550 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6551 SourceLocation EllipsisLoc);
6553 /// \brief Invoked when parsing a type followed by an ellipsis, which
6554 /// creates a pack expansion.
6556 /// \param Type The type preceding the ellipsis, which will become
6557 /// the pattern of the pack expansion.
6559 /// \param EllipsisLoc The location of the ellipsis.
6560 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6562 /// \brief Construct a pack expansion type from the pattern of the pack
6564 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6565 SourceLocation EllipsisLoc,
6566 Optional<unsigned> NumExpansions);
6568 /// \brief Construct a pack expansion type from the pattern of the pack
6570 QualType CheckPackExpansion(QualType Pattern,
6571 SourceRange PatternRange,
6572 SourceLocation EllipsisLoc,
6573 Optional<unsigned> NumExpansions);
6575 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6576 /// creates a pack expansion.
6578 /// \param Pattern The expression preceding the ellipsis, which will become
6579 /// the pattern of the pack expansion.
6581 /// \param EllipsisLoc The location of the ellipsis.
6582 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6584 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6585 /// creates a pack expansion.
6587 /// \param Pattern The expression preceding the ellipsis, which will become
6588 /// the pattern of the pack expansion.
6590 /// \param EllipsisLoc The location of the ellipsis.
6591 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6592 Optional<unsigned> NumExpansions);
6594 /// \brief Determine whether we could expand a pack expansion with the
6595 /// given set of parameter packs into separate arguments by repeatedly
6596 /// transforming the pattern.
6598 /// \param EllipsisLoc The location of the ellipsis that identifies the
6601 /// \param PatternRange The source range that covers the entire pattern of
6602 /// the pack expansion.
6604 /// \param Unexpanded The set of unexpanded parameter packs within the
6607 /// \param ShouldExpand Will be set to \c true if the transformer should
6608 /// expand the corresponding pack expansions into separate arguments. When
6609 /// set, \c NumExpansions must also be set.
6611 /// \param RetainExpansion Whether the caller should add an unexpanded
6612 /// pack expansion after all of the expanded arguments. This is used
6613 /// when extending explicitly-specified template argument packs per
6614 /// C++0x [temp.arg.explicit]p9.
6616 /// \param NumExpansions The number of separate arguments that will be in
6617 /// the expanded form of the corresponding pack expansion. This is both an
6618 /// input and an output parameter, which can be set by the caller if the
6619 /// number of expansions is known a priori (e.g., due to a prior substitution)
6620 /// and will be set by the callee when the number of expansions is known.
6621 /// The callee must set this value when \c ShouldExpand is \c true; it may
6622 /// set this value in other cases.
6624 /// \returns true if an error occurred (e.g., because the parameter packs
6625 /// are to be instantiated with arguments of different lengths), false
6626 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6628 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6629 SourceRange PatternRange,
6630 ArrayRef<UnexpandedParameterPack> Unexpanded,
6631 const MultiLevelTemplateArgumentList &TemplateArgs,
6633 bool &RetainExpansion,
6634 Optional<unsigned> &NumExpansions);
6636 /// \brief Determine the number of arguments in the given pack expansion
6639 /// This routine assumes that the number of arguments in the expansion is
6640 /// consistent across all of the unexpanded parameter packs in its pattern.
6642 /// Returns an empty Optional if the type can't be expanded.
6643 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6644 const MultiLevelTemplateArgumentList &TemplateArgs);
6646 /// \brief Determine whether the given declarator contains any unexpanded
6647 /// parameter packs.
6649 /// This routine is used by the parser to disambiguate function declarators
6650 /// with an ellipsis prior to the ')', e.g.,
6656 /// To determine whether we have an (unnamed) function parameter pack or
6657 /// a variadic function.
6659 /// \returns true if the declarator contains any unexpanded parameter packs,
6660 /// false otherwise.
6661 bool containsUnexpandedParameterPacks(Declarator &D);
6663 /// \brief Returns the pattern of the pack expansion for a template argument.
6665 /// \param OrigLoc The template argument to expand.
6667 /// \param Ellipsis Will be set to the location of the ellipsis.
6669 /// \param NumExpansions Will be set to the number of expansions that will
6670 /// be generated from this pack expansion, if known a priori.
6671 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6672 TemplateArgumentLoc OrigLoc,
6673 SourceLocation &Ellipsis,
6674 Optional<unsigned> &NumExpansions) const;
6676 /// Given a template argument that contains an unexpanded parameter pack, but
6677 /// which has already been substituted, attempt to determine the number of
6678 /// elements that will be produced once this argument is fully-expanded.
6680 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6681 /// avoid actually expanding the pack where possible.
6682 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6684 //===--------------------------------------------------------------------===//
6685 // C++ Template Argument Deduction (C++ [temp.deduct])
6686 //===--------------------------------------------------------------------===//
6688 /// Adjust the type \p ArgFunctionType to match the calling convention,
6689 /// noreturn, and optionally the exception specification of \p FunctionType.
6690 /// Deduction often wants to ignore these properties when matching function
6692 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6693 bool AdjustExceptionSpec = false);
6695 /// \brief Describes the result of template argument deduction.
6697 /// The TemplateDeductionResult enumeration describes the result of
6698 /// template argument deduction, as returned from
6699 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6700 /// structure provides additional information about the results of
6701 /// template argument deduction, e.g., the deduced template argument
6702 /// list (if successful) or the specific template parameters or
6703 /// deduced arguments that were involved in the failure.
6704 enum TemplateDeductionResult {
6705 /// \brief Template argument deduction was successful.
6707 /// \brief The declaration was invalid; do nothing.
6709 /// \brief Template argument deduction exceeded the maximum template
6710 /// instantiation depth (which has already been diagnosed).
6711 TDK_InstantiationDepth,
6712 /// \brief Template argument deduction did not deduce a value
6713 /// for every template parameter.
6715 /// \brief Template argument deduction produced inconsistent
6716 /// deduced values for the given template parameter.
6718 /// \brief Template argument deduction failed due to inconsistent
6719 /// cv-qualifiers on a template parameter type that would
6720 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6721 /// but were given a non-const "X".
6723 /// \brief Substitution of the deduced template argument values
6724 /// resulted in an error.
6725 TDK_SubstitutionFailure,
6726 /// \brief After substituting deduced template arguments, a dependent
6727 /// parameter type did not match the corresponding argument.
6728 TDK_DeducedMismatch,
6729 /// \brief After substituting deduced template arguments, an element of
6730 /// a dependent parameter type did not match the corresponding element
6731 /// of the corresponding argument (when deducing from an initializer list).
6732 TDK_DeducedMismatchNested,
6733 /// \brief A non-depnedent component of the parameter did not match the
6734 /// corresponding component of the argument.
6735 TDK_NonDeducedMismatch,
6736 /// \brief When performing template argument deduction for a function
6737 /// template, there were too many call arguments.
6738 TDK_TooManyArguments,
6739 /// \brief When performing template argument deduction for a function
6740 /// template, there were too few call arguments.
6741 TDK_TooFewArguments,
6742 /// \brief The explicitly-specified template arguments were not valid
6743 /// template arguments for the given template.
6744 TDK_InvalidExplicitArguments,
6745 /// \brief Checking non-dependent argument conversions failed.
6746 TDK_NonDependentConversionFailure,
6747 /// \brief Deduction failed; that's all we know.
6748 TDK_MiscellaneousDeductionFailure,
6749 /// \brief CUDA Target attributes do not match.
6750 TDK_CUDATargetMismatch
6753 TemplateDeductionResult
6754 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6755 const TemplateArgumentList &TemplateArgs,
6756 sema::TemplateDeductionInfo &Info);
6758 TemplateDeductionResult
6759 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6760 const TemplateArgumentList &TemplateArgs,
6761 sema::TemplateDeductionInfo &Info);
6763 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6764 FunctionTemplateDecl *FunctionTemplate,
6765 TemplateArgumentListInfo &ExplicitTemplateArgs,
6766 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6767 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6768 sema::TemplateDeductionInfo &Info);
6770 /// brief A function argument from which we performed template argument
6771 // deduction for a call.
6772 struct OriginalCallArg {
6773 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6774 unsigned ArgIdx, QualType OriginalArgType)
6775 : OriginalParamType(OriginalParamType),
6776 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6777 OriginalArgType(OriginalArgType) {}
6779 QualType OriginalParamType;
6780 bool DecomposedParam;
6782 QualType OriginalArgType;
6785 TemplateDeductionResult FinishTemplateArgumentDeduction(
6786 FunctionTemplateDecl *FunctionTemplate,
6787 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6788 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6789 sema::TemplateDeductionInfo &Info,
6790 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6791 bool PartialOverloading = false,
6792 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6794 TemplateDeductionResult DeduceTemplateArguments(
6795 FunctionTemplateDecl *FunctionTemplate,
6796 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6797 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6798 bool PartialOverloading,
6799 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6801 TemplateDeductionResult
6802 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6803 TemplateArgumentListInfo *ExplicitTemplateArgs,
6804 QualType ArgFunctionType,
6805 FunctionDecl *&Specialization,
6806 sema::TemplateDeductionInfo &Info,
6807 bool IsAddressOfFunction = false);
6809 TemplateDeductionResult
6810 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6812 CXXConversionDecl *&Specialization,
6813 sema::TemplateDeductionInfo &Info);
6815 TemplateDeductionResult
6816 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6817 TemplateArgumentListInfo *ExplicitTemplateArgs,
6818 FunctionDecl *&Specialization,
6819 sema::TemplateDeductionInfo &Info,
6820 bool IsAddressOfFunction = false);
6822 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6823 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6824 /// \brief Substitute Replacement for auto in TypeWithAuto
6825 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6826 QualType Replacement);
6827 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6828 /// \p Replacement. This does not retain any \c auto type sugar.
6829 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6831 /// \brief Result type of DeduceAutoType.
6832 enum DeduceAutoResult {
6835 DAR_FailedAlreadyDiagnosed
6839 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6840 Optional<unsigned> DependentDeductionDepth = None);
6842 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6843 Optional<unsigned> DependentDeductionDepth = None);
6844 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6845 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6846 bool Diagnose = true);
6848 /// \brief Declare implicit deduction guides for a class template if we've
6849 /// not already done so.
6850 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6851 SourceLocation Loc);
6853 QualType DeduceTemplateSpecializationFromInitializer(
6854 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6855 const InitializationKind &Kind, MultiExprArg Init);
6857 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6858 QualType Type, TypeSourceInfo *TSI,
6859 SourceRange Range, bool DirectInit,
6862 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6864 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6865 SourceLocation ReturnLoc,
6866 Expr *&RetExpr, AutoType *AT);
6868 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6869 FunctionTemplateDecl *FT2,
6871 TemplatePartialOrderingContext TPOC,
6872 unsigned NumCallArguments1,
6873 unsigned NumCallArguments2);
6874 UnresolvedSetIterator
6875 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6876 TemplateSpecCandidateSet &FailedCandidates,
6878 const PartialDiagnostic &NoneDiag,
6879 const PartialDiagnostic &AmbigDiag,
6880 const PartialDiagnostic &CandidateDiag,
6881 bool Complain = true, QualType TargetType = QualType());
6883 ClassTemplatePartialSpecializationDecl *
6884 getMoreSpecializedPartialSpecialization(
6885 ClassTemplatePartialSpecializationDecl *PS1,
6886 ClassTemplatePartialSpecializationDecl *PS2,
6887 SourceLocation Loc);
6889 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6890 sema::TemplateDeductionInfo &Info);
6892 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6893 VarTemplatePartialSpecializationDecl *PS1,
6894 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6896 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6897 sema::TemplateDeductionInfo &Info);
6899 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6900 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6902 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6905 llvm::SmallBitVector &Used);
6906 void MarkDeducedTemplateParameters(
6907 const FunctionTemplateDecl *FunctionTemplate,
6908 llvm::SmallBitVector &Deduced) {
6909 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6911 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6912 const FunctionTemplateDecl *FunctionTemplate,
6913 llvm::SmallBitVector &Deduced);
6915 //===--------------------------------------------------------------------===//
6916 // C++ Template Instantiation
6919 MultiLevelTemplateArgumentList
6920 getTemplateInstantiationArgs(NamedDecl *D,
6921 const TemplateArgumentList *Innermost = nullptr,
6922 bool RelativeToPrimary = false,
6923 const FunctionDecl *Pattern = nullptr);
6925 /// A context in which code is being synthesized (where a source location
6926 /// alone is not sufficient to identify the context). This covers template
6927 /// instantiation and various forms of implicitly-generated functions.
6928 struct CodeSynthesisContext {
6929 /// \brief The kind of template instantiation we are performing
6930 enum SynthesisKind {
6931 /// We are instantiating a template declaration. The entity is
6932 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6933 TemplateInstantiation,
6935 /// We are instantiating a default argument for a template
6936 /// parameter. The Entity is the template parameter whose argument is
6937 /// being instantiated, the Template is the template, and the
6938 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6940 DefaultTemplateArgumentInstantiation,
6942 /// We are instantiating a default argument for a function.
6943 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6944 /// provides the template arguments as specified.
6945 DefaultFunctionArgumentInstantiation,
6947 /// We are substituting explicit template arguments provided for
6948 /// a function template. The entity is a FunctionTemplateDecl.
6949 ExplicitTemplateArgumentSubstitution,
6951 /// We are substituting template argument determined as part of
6952 /// template argument deduction for either a class template
6953 /// partial specialization or a function template. The
6954 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6956 DeducedTemplateArgumentSubstitution,
6958 /// We are substituting prior template arguments into a new
6959 /// template parameter. The template parameter itself is either a
6960 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6961 PriorTemplateArgumentSubstitution,
6963 /// We are checking the validity of a default template argument that
6964 /// has been used when naming a template-id.
6965 DefaultTemplateArgumentChecking,
6967 /// We are instantiating the exception specification for a function
6968 /// template which was deferred until it was needed.
6969 ExceptionSpecInstantiation,
6971 /// We are declaring an implicit special member function.
6972 DeclaringSpecialMember,
6975 /// \brief Was the enclosing context a non-instantiation SFINAE context?
6976 bool SavedInNonInstantiationSFINAEContext;
6978 /// \brief The point of instantiation or synthesis within the source code.
6979 SourceLocation PointOfInstantiation;
6981 /// \brief The entity that is being synthesized.
6984 /// \brief The template (or partial specialization) in which we are
6985 /// performing the instantiation, for substitutions of prior template
6987 NamedDecl *Template;
6989 /// \brief The list of template arguments we are substituting, if they
6990 /// are not part of the entity.
6991 const TemplateArgument *TemplateArgs;
6993 // FIXME: Wrap this union around more members, or perhaps store the
6994 // kind-specific members in the RAII object owning the context.
6996 /// \brief The number of template arguments in TemplateArgs.
6997 unsigned NumTemplateArgs;
6999 /// \brief The special member being declared or defined.
7000 CXXSpecialMember SpecialMember;
7003 ArrayRef<TemplateArgument> template_arguments() const {
7004 assert(Kind != DeclaringSpecialMember);
7005 return {TemplateArgs, NumTemplateArgs};
7008 /// \brief The template deduction info object associated with the
7009 /// substitution or checking of explicit or deduced template arguments.
7010 sema::TemplateDeductionInfo *DeductionInfo;
7012 /// \brief The source range that covers the construct that cause
7013 /// the instantiation, e.g., the template-id that causes a class
7014 /// template instantiation.
7015 SourceRange InstantiationRange;
7017 CodeSynthesisContext()
7018 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7019 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7021 /// \brief Determines whether this template is an actual instantiation
7022 /// that should be counted toward the maximum instantiation depth.
7023 bool isInstantiationRecord() const;
7026 /// \brief List of active code synthesis contexts.
7028 /// This vector is treated as a stack. As synthesis of one entity requires
7029 /// synthesis of another, additional contexts are pushed onto the stack.
7030 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7032 /// Specializations whose definitions are currently being instantiated.
7033 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7035 /// Non-dependent types used in templates that have already been instantiated
7036 /// by some template instantiation.
7037 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7039 /// \brief Extra modules inspected when performing a lookup during a template
7040 /// instantiation. Computed lazily.
7041 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7043 /// \brief Cache of additional modules that should be used for name lookup
7044 /// within the current template instantiation. Computed lazily; use
7045 /// getLookupModules() to get a complete set.
7046 llvm::DenseSet<Module*> LookupModulesCache;
7048 /// \brief Get the set of additional modules that should be checked during
7049 /// name lookup. A module and its imports become visible when instanting a
7050 /// template defined within it.
7051 llvm::DenseSet<Module*> &getLookupModules();
7053 /// \brief Map from the most recent declaration of a namespace to the most
7054 /// recent visible declaration of that namespace.
7055 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7057 /// \brief Whether we are in a SFINAE context that is not associated with
7058 /// template instantiation.
7060 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7061 /// of a template instantiation or template argument deduction.
7062 bool InNonInstantiationSFINAEContext;
7064 /// \brief The number of \p CodeSynthesisContexts that are not template
7065 /// instantiations and, therefore, should not be counted as part of the
7066 /// instantiation depth.
7068 /// When the instantiation depth reaches the user-configurable limit
7069 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7070 // FIXME: Should we have a similar limit for other forms of synthesis?
7071 unsigned NonInstantiationEntries;
7073 /// \brief The depth of the context stack at the point when the most recent
7074 /// error or warning was produced.
7076 /// This value is used to suppress printing of redundant context stacks
7077 /// when there are multiple errors or warnings in the same instantiation.
7078 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7079 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7081 /// \brief The current index into pack expansion arguments that will be
7082 /// used for substitution of parameter packs.
7084 /// The pack expansion index will be -1 to indicate that parameter packs
7085 /// should be instantiated as themselves. Otherwise, the index specifies
7086 /// which argument within the parameter pack will be used for substitution.
7087 int ArgumentPackSubstitutionIndex;
7089 /// \brief RAII object used to change the argument pack substitution index
7090 /// within a \c Sema object.
7092 /// See \c ArgumentPackSubstitutionIndex for more information.
7093 class ArgumentPackSubstitutionIndexRAII {
7095 int OldSubstitutionIndex;
7098 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7099 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7100 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7103 ~ArgumentPackSubstitutionIndexRAII() {
7104 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7108 friend class ArgumentPackSubstitutionRAII;
7110 /// \brief For each declaration that involved template argument deduction, the
7111 /// set of diagnostics that were suppressed during that template argument
7114 /// FIXME: Serialize this structure to the AST file.
7115 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7116 SuppressedDiagnosticsMap;
7117 SuppressedDiagnosticsMap SuppressedDiagnostics;
7119 /// \brief A stack object to be created when performing template
7122 /// Construction of an object of type \c InstantiatingTemplate
7123 /// pushes the current instantiation onto the stack of active
7124 /// instantiations. If the size of this stack exceeds the maximum
7125 /// number of recursive template instantiations, construction
7126 /// produces an error and evaluates true.
7128 /// Destruction of this object will pop the named instantiation off
7130 struct InstantiatingTemplate {
7131 /// \brief Note that we are instantiating a class template,
7132 /// function template, variable template, alias template,
7133 /// or a member thereof.
7134 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7136 SourceRange InstantiationRange = SourceRange());
7138 struct ExceptionSpecification {};
7139 /// \brief Note that we are instantiating an exception specification
7140 /// of a function template.
7141 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7142 FunctionDecl *Entity, ExceptionSpecification,
7143 SourceRange InstantiationRange = SourceRange());
7145 /// \brief Note that we are instantiating a default argument in a
7147 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7148 TemplateParameter Param, TemplateDecl *Template,
7149 ArrayRef<TemplateArgument> TemplateArgs,
7150 SourceRange InstantiationRange = SourceRange());
7152 /// \brief Note that we are substituting either explicitly-specified or
7153 /// deduced template arguments during function template argument deduction.
7154 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7155 FunctionTemplateDecl *FunctionTemplate,
7156 ArrayRef<TemplateArgument> TemplateArgs,
7157 CodeSynthesisContext::SynthesisKind Kind,
7158 sema::TemplateDeductionInfo &DeductionInfo,
7159 SourceRange InstantiationRange = SourceRange());
7161 /// \brief Note that we are instantiating as part of template
7162 /// argument deduction for a class template declaration.
7163 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7164 TemplateDecl *Template,
7165 ArrayRef<TemplateArgument> TemplateArgs,
7166 sema::TemplateDeductionInfo &DeductionInfo,
7167 SourceRange InstantiationRange = SourceRange());
7169 /// \brief Note that we are instantiating as part of template
7170 /// argument deduction for a class template partial
7172 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7173 ClassTemplatePartialSpecializationDecl *PartialSpec,
7174 ArrayRef<TemplateArgument> TemplateArgs,
7175 sema::TemplateDeductionInfo &DeductionInfo,
7176 SourceRange InstantiationRange = SourceRange());
7178 /// \brief Note that we are instantiating as part of template
7179 /// argument deduction for a variable template partial
7181 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7182 VarTemplatePartialSpecializationDecl *PartialSpec,
7183 ArrayRef<TemplateArgument> TemplateArgs,
7184 sema::TemplateDeductionInfo &DeductionInfo,
7185 SourceRange InstantiationRange = SourceRange());
7187 /// \brief Note that we are instantiating a default argument for a function
7189 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7191 ArrayRef<TemplateArgument> TemplateArgs,
7192 SourceRange InstantiationRange = SourceRange());
7194 /// \brief Note that we are substituting prior template arguments into a
7195 /// non-type parameter.
7196 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7197 NamedDecl *Template,
7198 NonTypeTemplateParmDecl *Param,
7199 ArrayRef<TemplateArgument> TemplateArgs,
7200 SourceRange InstantiationRange);
7202 /// \brief Note that we are substituting prior template arguments into a
7203 /// template template parameter.
7204 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7205 NamedDecl *Template,
7206 TemplateTemplateParmDecl *Param,
7207 ArrayRef<TemplateArgument> TemplateArgs,
7208 SourceRange InstantiationRange);
7210 /// \brief Note that we are checking the default template argument
7211 /// against the template parameter for a given template-id.
7212 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7213 TemplateDecl *Template,
7215 ArrayRef<TemplateArgument> TemplateArgs,
7216 SourceRange InstantiationRange);
7219 /// \brief Note that we have finished instantiating this template.
7222 ~InstantiatingTemplate() { Clear(); }
7224 /// \brief Determines whether we have exceeded the maximum
7225 /// recursive template instantiations.
7226 bool isInvalid() const { return Invalid; }
7228 /// \brief Determine whether we are already instantiating this
7229 /// specialization in some surrounding active instantiation.
7230 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7235 bool AlreadyInstantiating;
7236 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7237 SourceRange InstantiationRange);
7239 InstantiatingTemplate(
7240 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7241 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7242 Decl *Entity, NamedDecl *Template = nullptr,
7243 ArrayRef<TemplateArgument> TemplateArgs = None,
7244 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7246 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7248 InstantiatingTemplate&
7249 operator=(const InstantiatingTemplate&) = delete;
7252 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7253 void popCodeSynthesisContext();
7255 /// Determine whether we are currently performing template instantiation.
7256 bool inTemplateInstantiation() const {
7257 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7260 void PrintContextStack() {
7261 if (!CodeSynthesisContexts.empty() &&
7262 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7263 PrintInstantiationStack();
7264 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7266 if (PragmaAttributeCurrentTargetDecl)
7267 PrintPragmaAttributeInstantiationPoint();
7269 void PrintInstantiationStack();
7271 void PrintPragmaAttributeInstantiationPoint();
7273 /// \brief Determines whether we are currently in a context where
7274 /// template argument substitution failures are not considered
7277 /// \returns An empty \c Optional if we're not in a SFINAE context.
7278 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7279 /// template-deduction context object, which can be used to capture
7280 /// diagnostics that will be suppressed.
7281 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7283 /// \brief Determines whether we are currently in a context that
7284 /// is not evaluated as per C++ [expr] p5.
7285 bool isUnevaluatedContext() const {
7286 assert(!ExprEvalContexts.empty() &&
7287 "Must be in an expression evaluation context");
7288 return ExprEvalContexts.back().isUnevaluated();
7291 /// \brief RAII class used to determine whether SFINAE has
7292 /// trapped any errors that occur during template argument
7296 unsigned PrevSFINAEErrors;
7297 bool PrevInNonInstantiationSFINAEContext;
7298 bool PrevAccessCheckingSFINAE;
7301 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7302 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7303 PrevInNonInstantiationSFINAEContext(
7304 SemaRef.InNonInstantiationSFINAEContext),
7305 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7307 if (!SemaRef.isSFINAEContext())
7308 SemaRef.InNonInstantiationSFINAEContext = true;
7309 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7313 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7314 SemaRef.InNonInstantiationSFINAEContext
7315 = PrevInNonInstantiationSFINAEContext;
7316 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7319 /// \brief Determine whether any SFINAE errors have been trapped.
7320 bool hasErrorOccurred() const {
7321 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7325 /// \brief RAII class used to indicate that we are performing provisional
7326 /// semantic analysis to determine the validity of a construct, so
7327 /// typo-correction and diagnostics in the immediate context (not within
7328 /// implicitly-instantiated templates) should be suppressed.
7329 class TentativeAnalysisScope {
7331 // FIXME: Using a SFINAETrap for this is a hack.
7333 bool PrevDisableTypoCorrection;
7335 explicit TentativeAnalysisScope(Sema &SemaRef)
7336 : SemaRef(SemaRef), Trap(SemaRef, true),
7337 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7338 SemaRef.DisableTypoCorrection = true;
7340 ~TentativeAnalysisScope() {
7341 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7345 /// \brief The current instantiation scope used to store local
7347 LocalInstantiationScope *CurrentInstantiationScope;
7349 /// \brief Tracks whether we are in a context where typo correction is
7351 bool DisableTypoCorrection;
7353 /// \brief The number of typos corrected by CorrectTypo.
7354 unsigned TyposCorrected;
7356 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7357 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7359 /// \brief A cache containing identifiers for which typo correction failed and
7360 /// their locations, so that repeated attempts to correct an identifier in a
7361 /// given location are ignored if typo correction already failed for it.
7362 IdentifierSourceLocations TypoCorrectionFailures;
7364 /// \brief Worker object for performing CFG-based warnings.
7365 sema::AnalysisBasedWarnings AnalysisWarnings;
7366 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7368 /// \brief An entity for which implicit template instantiation is required.
7370 /// The source location associated with the declaration is the first place in
7371 /// the source code where the declaration was "used". It is not necessarily
7372 /// the point of instantiation (which will be either before or after the
7373 /// namespace-scope declaration that triggered this implicit instantiation),
7374 /// However, it is the location that diagnostics should generally refer to,
7375 /// because users will need to know what code triggered the instantiation.
7376 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7378 /// \brief The queue of implicit template instantiations that are required
7379 /// but have not yet been performed.
7380 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7382 class SavePendingInstantiationsAndVTableUsesRAII {
7384 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7385 : S(S), Enabled(Enabled) {
7386 if (!Enabled) return;
7388 SavedPendingInstantiations.swap(S.PendingInstantiations);
7389 SavedVTableUses.swap(S.VTableUses);
7392 ~SavePendingInstantiationsAndVTableUsesRAII() {
7393 if (!Enabled) return;
7395 // Restore the set of pending vtables.
7396 assert(S.VTableUses.empty() &&
7397 "VTableUses should be empty before it is discarded.");
7398 S.VTableUses.swap(SavedVTableUses);
7400 // Restore the set of pending implicit instantiations.
7401 assert(S.PendingInstantiations.empty() &&
7402 "PendingInstantiations should be empty before it is discarded.");
7403 S.PendingInstantiations.swap(SavedPendingInstantiations);
7408 SmallVector<VTableUse, 16> SavedVTableUses;
7409 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7413 /// \brief The queue of implicit template instantiations that are required
7414 /// and must be performed within the current local scope.
7416 /// This queue is only used for member functions of local classes in
7417 /// templates, which must be instantiated in the same scope as their
7418 /// enclosing function, so that they can reference function-local
7419 /// types, static variables, enumerators, etc.
7420 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7422 class SavePendingLocalImplicitInstantiationsRAII {
7424 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7425 SavedPendingLocalImplicitInstantiations.swap(
7426 S.PendingLocalImplicitInstantiations);
7429 ~SavePendingLocalImplicitInstantiationsRAII() {
7430 assert(S.PendingLocalImplicitInstantiations.empty() &&
7431 "there shouldn't be any pending local implicit instantiations");
7432 SavedPendingLocalImplicitInstantiations.swap(
7433 S.PendingLocalImplicitInstantiations);
7438 std::deque<PendingImplicitInstantiation>
7439 SavedPendingLocalImplicitInstantiations;
7442 /// A helper class for building up ExtParameterInfos.
7443 class ExtParameterInfoBuilder {
7444 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7445 bool HasInteresting = false;
7448 /// Set the ExtParameterInfo for the parameter at the given index,
7450 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7451 assert(Infos.size() <= index);
7452 Infos.resize(index);
7453 Infos.push_back(info);
7455 if (!HasInteresting)
7456 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7459 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7460 /// ExtParameterInfo array we've built up.
7461 const FunctionProtoType::ExtParameterInfo *
7462 getPointerOrNull(unsigned numParams) {
7463 if (!HasInteresting) return nullptr;
7464 Infos.resize(numParams);
7465 return Infos.data();
7469 void PerformPendingInstantiations(bool LocalOnly = false);
7471 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7472 const MultiLevelTemplateArgumentList &TemplateArgs,
7473 SourceLocation Loc, DeclarationName Entity,
7474 bool AllowDeducedTST = false);
7476 QualType SubstType(QualType T,
7477 const MultiLevelTemplateArgumentList &TemplateArgs,
7478 SourceLocation Loc, DeclarationName Entity);
7480 TypeSourceInfo *SubstType(TypeLoc TL,
7481 const MultiLevelTemplateArgumentList &TemplateArgs,
7482 SourceLocation Loc, DeclarationName Entity);
7484 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7485 const MultiLevelTemplateArgumentList &TemplateArgs,
7487 DeclarationName Entity,
7488 CXXRecordDecl *ThisContext,
7489 unsigned ThisTypeQuals);
7490 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7491 const MultiLevelTemplateArgumentList &Args);
7492 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7493 const MultiLevelTemplateArgumentList &TemplateArgs,
7494 int indexAdjustment,
7495 Optional<unsigned> NumExpansions,
7496 bool ExpectParameterPack);
7497 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7498 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7499 const MultiLevelTemplateArgumentList &TemplateArgs,
7500 SmallVectorImpl<QualType> &ParamTypes,
7501 SmallVectorImpl<ParmVarDecl *> *OutParams,
7502 ExtParameterInfoBuilder &ParamInfos);
7503 ExprResult SubstExpr(Expr *E,
7504 const MultiLevelTemplateArgumentList &TemplateArgs);
7506 /// \brief Substitute the given template arguments into a list of
7507 /// expressions, expanding pack expansions if required.
7509 /// \param Exprs The list of expressions to substitute into.
7511 /// \param IsCall Whether this is some form of call, in which case
7512 /// default arguments will be dropped.
7514 /// \param TemplateArgs The set of template arguments to substitute.
7516 /// \param Outputs Will receive all of the substituted arguments.
7518 /// \returns true if an error occurred, false otherwise.
7519 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7520 const MultiLevelTemplateArgumentList &TemplateArgs,
7521 SmallVectorImpl<Expr *> &Outputs);
7523 StmtResult SubstStmt(Stmt *S,
7524 const MultiLevelTemplateArgumentList &TemplateArgs);
7526 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7527 const MultiLevelTemplateArgumentList &TemplateArgs);
7529 ExprResult SubstInitializer(Expr *E,
7530 const MultiLevelTemplateArgumentList &TemplateArgs,
7531 bool CXXDirectInit);
7534 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7535 CXXRecordDecl *Pattern,
7536 const MultiLevelTemplateArgumentList &TemplateArgs);
7539 InstantiateClass(SourceLocation PointOfInstantiation,
7540 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7541 const MultiLevelTemplateArgumentList &TemplateArgs,
7542 TemplateSpecializationKind TSK,
7543 bool Complain = true);
7545 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7546 EnumDecl *Instantiation, EnumDecl *Pattern,
7547 const MultiLevelTemplateArgumentList &TemplateArgs,
7548 TemplateSpecializationKind TSK);
7550 bool InstantiateInClassInitializer(
7551 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7552 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7554 struct LateInstantiatedAttribute {
7555 const Attr *TmplAttr;
7556 LocalInstantiationScope *Scope;
7559 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7561 : TmplAttr(A), Scope(S), NewDecl(D)
7564 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7566 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7567 const Decl *Pattern, Decl *Inst,
7568 LateInstantiatedAttrVec *LateAttrs = nullptr,
7569 LocalInstantiationScope *OuterMostScope = nullptr);
7572 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7573 const Decl *Pattern, Decl *Inst,
7574 LateInstantiatedAttrVec *LateAttrs = nullptr,
7575 LocalInstantiationScope *OuterMostScope = nullptr);
7578 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7579 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7580 TemplateSpecializationKind TSK,
7581 bool Complain = true);
7583 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7584 CXXRecordDecl *Instantiation,
7585 const MultiLevelTemplateArgumentList &TemplateArgs,
7586 TemplateSpecializationKind TSK);
7588 void InstantiateClassTemplateSpecializationMembers(
7589 SourceLocation PointOfInstantiation,
7590 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7591 TemplateSpecializationKind TSK);
7593 NestedNameSpecifierLoc
7594 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7595 const MultiLevelTemplateArgumentList &TemplateArgs);
7598 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7599 const MultiLevelTemplateArgumentList &TemplateArgs);
7601 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7603 const MultiLevelTemplateArgumentList &TemplateArgs);
7604 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7605 TemplateArgumentListInfo &Result,
7606 const MultiLevelTemplateArgumentList &TemplateArgs);
7608 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7609 FunctionDecl *Function);
7610 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7611 FunctionDecl *Function,
7612 bool Recursive = false,
7613 bool DefinitionRequired = false,
7614 bool AtEndOfTU = false);
7615 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7616 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7617 const TemplateArgumentList &TemplateArgList,
7618 const TemplateArgumentListInfo &TemplateArgsInfo,
7619 SmallVectorImpl<TemplateArgument> &Converted,
7620 SourceLocation PointOfInstantiation, void *InsertPos,
7621 LateInstantiatedAttrVec *LateAttrs = nullptr,
7622 LocalInstantiationScope *StartingScope = nullptr);
7623 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7624 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7625 const MultiLevelTemplateArgumentList &TemplateArgs);
7627 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7628 const MultiLevelTemplateArgumentList &TemplateArgs,
7629 LateInstantiatedAttrVec *LateAttrs,
7631 LocalInstantiationScope *StartingScope,
7632 bool InstantiatingVarTemplate = false);
7633 void InstantiateVariableInitializer(
7634 VarDecl *Var, VarDecl *OldVar,
7635 const MultiLevelTemplateArgumentList &TemplateArgs);
7636 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7637 VarDecl *Var, bool Recursive = false,
7638 bool DefinitionRequired = false,
7639 bool AtEndOfTU = false);
7640 void InstantiateStaticDataMemberDefinition(
7641 SourceLocation PointOfInstantiation,
7643 bool Recursive = false,
7644 bool DefinitionRequired = false);
7646 void InstantiateMemInitializers(CXXConstructorDecl *New,
7647 const CXXConstructorDecl *Tmpl,
7648 const MultiLevelTemplateArgumentList &TemplateArgs);
7650 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7651 const MultiLevelTemplateArgumentList &TemplateArgs);
7652 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7653 const MultiLevelTemplateArgumentList &TemplateArgs);
7655 // Objective-C declarations.
7656 enum ObjCContainerKind {
7663 OCK_CategoryImplementation
7665 ObjCContainerKind getObjCContainerKind() const;
7667 DeclResult actOnObjCTypeParam(Scope *S,
7668 ObjCTypeParamVariance variance,
7669 SourceLocation varianceLoc,
7671 IdentifierInfo *paramName,
7672 SourceLocation paramLoc,
7673 SourceLocation colonLoc,
7674 ParsedType typeBound);
7676 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7677 ArrayRef<Decl *> typeParams,
7678 SourceLocation rAngleLoc);
7679 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7681 Decl *ActOnStartClassInterface(Scope *S,
7682 SourceLocation AtInterfaceLoc,
7683 IdentifierInfo *ClassName,
7684 SourceLocation ClassLoc,
7685 ObjCTypeParamList *typeParamList,
7686 IdentifierInfo *SuperName,
7687 SourceLocation SuperLoc,
7688 ArrayRef<ParsedType> SuperTypeArgs,
7689 SourceRange SuperTypeArgsRange,
7690 Decl * const *ProtoRefs,
7691 unsigned NumProtoRefs,
7692 const SourceLocation *ProtoLocs,
7693 SourceLocation EndProtoLoc,
7694 AttributeList *AttrList);
7696 void ActOnSuperClassOfClassInterface(Scope *S,
7697 SourceLocation AtInterfaceLoc,
7698 ObjCInterfaceDecl *IDecl,
7699 IdentifierInfo *ClassName,
7700 SourceLocation ClassLoc,
7701 IdentifierInfo *SuperName,
7702 SourceLocation SuperLoc,
7703 ArrayRef<ParsedType> SuperTypeArgs,
7704 SourceRange SuperTypeArgsRange);
7706 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7707 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7708 IdentifierInfo *SuperName,
7709 SourceLocation SuperLoc);
7711 Decl *ActOnCompatibilityAlias(
7712 SourceLocation AtCompatibilityAliasLoc,
7713 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7714 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7716 bool CheckForwardProtocolDeclarationForCircularDependency(
7717 IdentifierInfo *PName,
7718 SourceLocation &PLoc, SourceLocation PrevLoc,
7719 const ObjCList<ObjCProtocolDecl> &PList);
7721 Decl *ActOnStartProtocolInterface(
7722 SourceLocation AtProtoInterfaceLoc,
7723 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7724 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7725 const SourceLocation *ProtoLocs,
7726 SourceLocation EndProtoLoc,
7727 AttributeList *AttrList);
7729 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7730 IdentifierInfo *ClassName,
7731 SourceLocation ClassLoc,
7732 ObjCTypeParamList *typeParamList,
7733 IdentifierInfo *CategoryName,
7734 SourceLocation CategoryLoc,
7735 Decl * const *ProtoRefs,
7736 unsigned NumProtoRefs,
7737 const SourceLocation *ProtoLocs,
7738 SourceLocation EndProtoLoc,
7739 AttributeList *AttrList);
7741 Decl *ActOnStartClassImplementation(
7742 SourceLocation AtClassImplLoc,
7743 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7744 IdentifierInfo *SuperClassname,
7745 SourceLocation SuperClassLoc);
7747 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7748 IdentifierInfo *ClassName,
7749 SourceLocation ClassLoc,
7750 IdentifierInfo *CatName,
7751 SourceLocation CatLoc);
7753 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7754 ArrayRef<Decl *> Decls);
7756 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7757 IdentifierInfo **IdentList,
7758 SourceLocation *IdentLocs,
7759 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7762 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7763 ArrayRef<IdentifierLocPair> IdentList,
7764 AttributeList *attrList);
7766 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7767 ArrayRef<IdentifierLocPair> ProtocolId,
7768 SmallVectorImpl<Decl *> &Protocols);
7770 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7771 SourceLocation ProtocolLoc,
7772 IdentifierInfo *TypeArgId,
7773 SourceLocation TypeArgLoc,
7774 bool SelectProtocolFirst = false);
7776 /// Given a list of identifiers (and their locations), resolve the
7777 /// names to either Objective-C protocol qualifiers or type
7778 /// arguments, as appropriate.
7779 void actOnObjCTypeArgsOrProtocolQualifiers(
7781 ParsedType baseType,
7782 SourceLocation lAngleLoc,
7783 ArrayRef<IdentifierInfo *> identifiers,
7784 ArrayRef<SourceLocation> identifierLocs,
7785 SourceLocation rAngleLoc,
7786 SourceLocation &typeArgsLAngleLoc,
7787 SmallVectorImpl<ParsedType> &typeArgs,
7788 SourceLocation &typeArgsRAngleLoc,
7789 SourceLocation &protocolLAngleLoc,
7790 SmallVectorImpl<Decl *> &protocols,
7791 SourceLocation &protocolRAngleLoc,
7792 bool warnOnIncompleteProtocols);
7794 /// Build a an Objective-C protocol-qualified 'id' type where no
7795 /// base type was specified.
7796 TypeResult actOnObjCProtocolQualifierType(
7797 SourceLocation lAngleLoc,
7798 ArrayRef<Decl *> protocols,
7799 ArrayRef<SourceLocation> protocolLocs,
7800 SourceLocation rAngleLoc);
7802 /// Build a specialized and/or protocol-qualified Objective-C type.
7803 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7806 ParsedType BaseType,
7807 SourceLocation TypeArgsLAngleLoc,
7808 ArrayRef<ParsedType> TypeArgs,
7809 SourceLocation TypeArgsRAngleLoc,
7810 SourceLocation ProtocolLAngleLoc,
7811 ArrayRef<Decl *> Protocols,
7812 ArrayRef<SourceLocation> ProtocolLocs,
7813 SourceLocation ProtocolRAngleLoc);
7815 /// Build an Objective-C type parameter type.
7816 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7817 SourceLocation ProtocolLAngleLoc,
7818 ArrayRef<ObjCProtocolDecl *> Protocols,
7819 ArrayRef<SourceLocation> ProtocolLocs,
7820 SourceLocation ProtocolRAngleLoc,
7821 bool FailOnError = false);
7823 /// Build an Objective-C object pointer type.
7824 QualType BuildObjCObjectType(QualType BaseType,
7826 SourceLocation TypeArgsLAngleLoc,
7827 ArrayRef<TypeSourceInfo *> TypeArgs,
7828 SourceLocation TypeArgsRAngleLoc,
7829 SourceLocation ProtocolLAngleLoc,
7830 ArrayRef<ObjCProtocolDecl *> Protocols,
7831 ArrayRef<SourceLocation> ProtocolLocs,
7832 SourceLocation ProtocolRAngleLoc,
7833 bool FailOnError = false);
7835 /// Check the application of the Objective-C '__kindof' qualifier to
7837 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7839 /// Ensure attributes are consistent with type.
7840 /// \param [in, out] Attributes The attributes to check; they will
7841 /// be modified to be consistent with \p PropertyTy.
7842 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7844 unsigned &Attributes,
7845 bool propertyInPrimaryClass);
7847 /// Process the specified property declaration and create decls for the
7848 /// setters and getters as needed.
7849 /// \param property The property declaration being processed
7850 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7853 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7854 ObjCPropertyDecl *SuperProperty,
7855 const IdentifierInfo *Name,
7856 bool OverridingProtocolProperty);
7858 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7859 ObjCInterfaceDecl *ID);
7861 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7862 ArrayRef<Decl *> allMethods = None,
7863 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7865 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7866 SourceLocation LParenLoc,
7867 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7868 Selector GetterSel, Selector SetterSel,
7869 tok::ObjCKeywordKind MethodImplKind,
7870 DeclContext *lexicalDC = nullptr);
7872 Decl *ActOnPropertyImplDecl(Scope *S,
7873 SourceLocation AtLoc,
7874 SourceLocation PropertyLoc,
7876 IdentifierInfo *PropertyId,
7877 IdentifierInfo *PropertyIvar,
7878 SourceLocation PropertyIvarLoc,
7879 ObjCPropertyQueryKind QueryKind);
7881 enum ObjCSpecialMethodKind {
7887 OSMK_NonRetainingInit
7890 struct ObjCArgInfo {
7891 IdentifierInfo *Name;
7892 SourceLocation NameLoc;
7893 // The Type is null if no type was specified, and the DeclSpec is invalid
7896 ObjCDeclSpec DeclSpec;
7898 /// ArgAttrs - Attribute list for this argument.
7899 AttributeList *ArgAttrs;
7902 Decl *ActOnMethodDeclaration(
7904 SourceLocation BeginLoc, // location of the + or -.
7905 SourceLocation EndLoc, // location of the ; or {.
7906 tok::TokenKind MethodType,
7907 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7908 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7909 // optional arguments. The number of types/arguments is obtained
7910 // from the Sel.getNumArgs().
7911 ObjCArgInfo *ArgInfo,
7912 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7913 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7914 bool isVariadic, bool MethodDefinition);
7916 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7917 const ObjCObjectPointerType *OPT,
7919 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7922 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7923 bool inferObjCARCLifetime(ValueDecl *decl);
7926 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7928 SourceLocation OpLoc,
7929 DeclarationName MemberName,
7930 SourceLocation MemberLoc,
7931 SourceLocation SuperLoc, QualType SuperType,
7935 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7936 IdentifierInfo &propertyName,
7937 SourceLocation receiverNameLoc,
7938 SourceLocation propertyNameLoc);
7940 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7942 /// \brief Describes the kind of message expression indicated by a message
7943 /// send that starts with an identifier.
7944 enum ObjCMessageKind {
7945 /// \brief The message is sent to 'super'.
7947 /// \brief The message is an instance message.
7948 ObjCInstanceMessage,
7949 /// \brief The message is a class message, and the identifier is a type
7954 ObjCMessageKind getObjCMessageKind(Scope *S,
7955 IdentifierInfo *Name,
7956 SourceLocation NameLoc,
7958 bool HasTrailingDot,
7959 ParsedType &ReceiverType);
7961 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7963 SourceLocation LBracLoc,
7964 ArrayRef<SourceLocation> SelectorLocs,
7965 SourceLocation RBracLoc,
7968 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7969 QualType ReceiverType,
7970 SourceLocation SuperLoc,
7972 ObjCMethodDecl *Method,
7973 SourceLocation LBracLoc,
7974 ArrayRef<SourceLocation> SelectorLocs,
7975 SourceLocation RBracLoc,
7977 bool isImplicit = false);
7979 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7980 bool isSuperReceiver,
7983 ObjCMethodDecl *Method,
7986 ExprResult ActOnClassMessage(Scope *S,
7987 ParsedType Receiver,
7989 SourceLocation LBracLoc,
7990 ArrayRef<SourceLocation> SelectorLocs,
7991 SourceLocation RBracLoc,
7994 ExprResult BuildInstanceMessage(Expr *Receiver,
7995 QualType ReceiverType,
7996 SourceLocation SuperLoc,
7998 ObjCMethodDecl *Method,
7999 SourceLocation LBracLoc,
8000 ArrayRef<SourceLocation> SelectorLocs,
8001 SourceLocation RBracLoc,
8003 bool isImplicit = false);
8005 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8006 QualType ReceiverType,
8009 ObjCMethodDecl *Method,
8012 ExprResult ActOnInstanceMessage(Scope *S,
8015 SourceLocation LBracLoc,
8016 ArrayRef<SourceLocation> SelectorLocs,
8017 SourceLocation RBracLoc,
8020 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8021 ObjCBridgeCastKind Kind,
8022 SourceLocation BridgeKeywordLoc,
8023 TypeSourceInfo *TSInfo,
8026 ExprResult ActOnObjCBridgedCast(Scope *S,
8027 SourceLocation LParenLoc,
8028 ObjCBridgeCastKind Kind,
8029 SourceLocation BridgeKeywordLoc,
8031 SourceLocation RParenLoc,
8034 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8036 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8038 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8041 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8042 QualType DestType, QualType SrcType,
8043 ObjCInterfaceDecl *&RelatedClass,
8044 ObjCMethodDecl *&ClassMethod,
8045 ObjCMethodDecl *&InstanceMethod,
8046 TypedefNameDecl *&TDNDecl,
8047 bool CfToNs, bool Diagnose = true);
8049 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8050 QualType DestType, QualType SrcType,
8051 Expr *&SrcExpr, bool Diagnose = true);
8053 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8054 bool Diagnose = true);
8056 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8058 /// \brief Check whether the given new method is a valid override of the
8059 /// given overridden method, and set any properties that should be inherited.
8060 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8061 const ObjCMethodDecl *Overridden);
8063 /// \brief Describes the compatibility of a result type with its method.
8064 enum ResultTypeCompatibilityKind {
8070 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8071 ObjCInterfaceDecl *CurrentClass,
8072 ResultTypeCompatibilityKind RTC);
8074 enum PragmaOptionsAlignKind {
8075 POAK_Native, // #pragma options align=native
8076 POAK_Natural, // #pragma options align=natural
8077 POAK_Packed, // #pragma options align=packed
8078 POAK_Power, // #pragma options align=power
8079 POAK_Mac68k, // #pragma options align=mac68k
8080 POAK_Reset // #pragma options align=reset
8083 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8084 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8085 SourceLocation PragmaLoc);
8087 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8088 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8089 StringRef SlotLabel, Expr *Alignment);
8091 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8092 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8094 /// ActOnPragmaMSComment - Called on well formed
8095 /// \#pragma comment(kind, "arg").
8096 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8099 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8100 /// pointers_to_members(representation method[, general purpose
8101 /// representation]).
8102 void ActOnPragmaMSPointersToMembers(
8103 LangOptions::PragmaMSPointersToMembersKind Kind,
8104 SourceLocation PragmaLoc);
8106 /// \brief Called on well formed \#pragma vtordisp().
8107 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8108 SourceLocation PragmaLoc,
8109 MSVtorDispAttr::Mode Value);
8111 enum PragmaSectionKind {
8118 bool UnifySection(StringRef SectionName,
8120 DeclaratorDecl *TheDecl);
8121 bool UnifySection(StringRef SectionName,
8123 SourceLocation PragmaSectionLocation);
8125 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8126 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8127 PragmaMsStackAction Action,
8128 llvm::StringRef StackSlotLabel,
8129 StringLiteral *SegmentName,
8130 llvm::StringRef PragmaName);
8132 /// \brief Called on well formed \#pragma section().
8133 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8134 int SectionFlags, StringLiteral *SegmentName);
8136 /// \brief Called on well-formed \#pragma init_seg().
8137 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8138 StringLiteral *SegmentName);
8140 /// \brief Called on #pragma clang __debug dump II
8141 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8143 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8144 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8147 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8148 void ActOnPragmaUnused(const Token &Identifier,
8150 SourceLocation PragmaLoc);
8152 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8153 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8154 SourceLocation PragmaLoc);
8156 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8157 SourceLocation Loc);
8158 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8160 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8161 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8162 SourceLocation PragmaLoc,
8163 SourceLocation WeakNameLoc);
8165 /// ActOnPragmaRedefineExtname - Called on well formed
8166 /// \#pragma redefine_extname oldname newname.
8167 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8168 IdentifierInfo* AliasName,
8169 SourceLocation PragmaLoc,
8170 SourceLocation WeakNameLoc,
8171 SourceLocation AliasNameLoc);
8173 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8174 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8175 IdentifierInfo* AliasName,
8176 SourceLocation PragmaLoc,
8177 SourceLocation WeakNameLoc,
8178 SourceLocation AliasNameLoc);
8180 /// ActOnPragmaFPContract - Called on well formed
8181 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8182 /// \#pragma clang fp contract
8183 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8185 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8186 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8187 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8189 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8190 void AddMsStructLayoutForRecord(RecordDecl *RD);
8192 /// FreePackedContext - Deallocate and null out PackContext.
8193 void FreePackedContext();
8195 /// PushNamespaceVisibilityAttr - Note that we've entered a
8196 /// namespace with a visibility attribute.
8197 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8198 SourceLocation Loc);
8200 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8201 /// add an appropriate visibility attribute.
8202 void AddPushedVisibilityAttribute(Decl *RD);
8204 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8205 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8206 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8208 /// FreeVisContext - Deallocate and null out VisContext.
8209 void FreeVisContext();
8211 /// AddCFAuditedAttribute - Check whether we're currently within
8212 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8213 /// the appropriate attribute.
8214 void AddCFAuditedAttribute(Decl *D);
8216 /// \brief Called on well-formed '\#pragma clang attribute push'.
8217 void ActOnPragmaAttributePush(AttributeList &Attribute,
8218 SourceLocation PragmaLoc,
8219 attr::ParsedSubjectMatchRuleSet Rules);
8221 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8222 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8224 /// \brief Adds the attributes that have been specified using the
8225 /// '\#pragma clang attribute push' directives to the given declaration.
8226 void AddPragmaAttributes(Scope *S, Decl *D);
8228 void DiagnoseUnterminatedPragmaAttribute();
8230 /// \brief Called on well formed \#pragma clang optimize.
8231 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8233 /// \brief Get the location for the currently active "\#pragma clang optimize
8234 /// off". If this location is invalid, then the state of the pragma is "on".
8235 SourceLocation getOptimizeOffPragmaLocation() const {
8236 return OptimizeOffPragmaLocation;
8239 /// \brief Only called on function definitions; if there is a pragma in scope
8240 /// with the effect of a range-based optnone, consider marking the function
8241 /// with attribute optnone.
8242 void AddRangeBasedOptnone(FunctionDecl *FD);
8244 /// \brief Adds the 'optnone' attribute to the function declaration if there
8245 /// are no conflicts; Loc represents the location causing the 'optnone'
8246 /// attribute to be added (usually because of a pragma).
8247 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8249 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8250 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8251 unsigned SpellingListIndex, bool IsPackExpansion);
8252 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8253 unsigned SpellingListIndex, bool IsPackExpansion);
8255 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8257 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8258 unsigned SpellingListIndex);
8260 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8262 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8263 unsigned SpellingListIndex);
8265 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8267 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8268 unsigned SpellingListIndex);
8270 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8272 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8273 Expr *MinBlocks, unsigned SpellingListIndex);
8275 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8276 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8277 unsigned SpellingListIndex, bool InInstantiation = false);
8279 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8280 ParameterABI ABI, unsigned SpellingListIndex);
8282 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8283 unsigned SpellingListIndex, bool isNSConsumed,
8284 bool isTemplateInstantiation);
8286 //===--------------------------------------------------------------------===//
8287 // C++ Coroutines TS
8289 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8290 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8291 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8293 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8294 bool IsImplicit = false);
8295 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8296 UnresolvedLookupExpr* Lookup);
8297 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8298 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8299 bool IsImplicit = false);
8300 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8301 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8302 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8304 //===--------------------------------------------------------------------===//
8305 // OpenCL extensions.
8308 std::string CurrOpenCLExtension;
8309 /// Extensions required by an OpenCL type.
8310 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8311 /// Extensions required by an OpenCL declaration.
8312 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8314 llvm::StringRef getCurrentOpenCLExtension() const {
8315 return CurrOpenCLExtension;
8317 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8318 CurrOpenCLExtension = Ext;
8321 /// \brief Set OpenCL extensions for a type which can only be used when these
8322 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8323 /// \param Exts A space separated list of OpenCL extensions.
8324 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8326 /// \brief Set OpenCL extensions for a declaration which can only be
8327 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8329 /// \param Exts A space separated list of OpenCL extensions.
8330 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8332 /// \brief Set current OpenCL extensions for a type which can only be used
8333 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8334 /// empty, do nothing.
8335 void setCurrentOpenCLExtensionForType(QualType T);
8337 /// \brief Set current OpenCL extensions for a declaration which
8338 /// can only be used when these OpenCL extensions are enabled. If current
8339 /// OpenCL extension is empty, do nothing.
8340 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8342 bool isOpenCLDisabledDecl(Decl *FD);
8344 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8345 /// is disabled due to required OpenCL extensions being disabled. If so,
8346 /// emit diagnostics.
8347 /// \return true if type is disabled.
8348 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8350 /// \brief Check if declaration \p D used by expression \p E
8351 /// is disabled due to required OpenCL extensions being disabled. If so,
8352 /// emit diagnostics.
8353 /// \return true if type is disabled.
8354 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8356 //===--------------------------------------------------------------------===//
8357 // OpenMP directives and clauses.
8360 void *VarDataSharingAttributesStack;
8361 /// Set to true inside '#pragma omp declare target' region.
8362 bool IsInOpenMPDeclareTargetContext = false;
8363 /// \brief Initialization of data-sharing attributes stack.
8364 void InitDataSharingAttributesStack();
8365 void DestroyDataSharingAttributesStack();
8367 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8368 bool StrictlyPositive = true);
8369 /// Returns OpenMP nesting level for current directive.
8370 unsigned getOpenMPNestingLevel() const;
8372 /// Push new OpenMP function region for non-capturing function.
8373 void pushOpenMPFunctionRegion();
8375 /// Pop OpenMP function region for non-capturing function.
8376 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8378 /// Checks if a type or a declaration is disabled due to the owning extension
8379 /// being disabled, and emits diagnostic messages if it is disabled.
8380 /// \param D type or declaration to be checked.
8381 /// \param DiagLoc source location for the diagnostic message.
8382 /// \param DiagInfo information to be emitted for the diagnostic message.
8383 /// \param SrcRange source range of the declaration.
8384 /// \param Map maps type or declaration to the extensions.
8385 /// \param Selector selects diagnostic message: 0 for type and 1 for
8387 /// \return true if the type or declaration is disabled.
8388 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8389 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8390 MapT &Map, unsigned Selector = 0,
8391 SourceRange SrcRange = SourceRange());
8394 /// \brief Return true if the provided declaration \a VD should be captured by
8396 /// \param Level Relative level of nested OpenMP construct for that the check
8398 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8400 /// \brief Check if the specified variable is used in one of the private
8401 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8403 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8404 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8405 ExprObjectKind OK, SourceLocation Loc);
8407 /// \brief Check if the specified variable is used in 'private' clause.
8408 /// \param Level Relative level of nested OpenMP construct for that the check
8410 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8412 /// \brief Check if the specified variable is captured by 'target' directive.
8413 /// \param Level Relative level of nested OpenMP construct for that the check
8415 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8417 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8419 /// \brief Called on start of new data sharing attribute block.
8420 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8421 const DeclarationNameInfo &DirName, Scope *CurScope,
8422 SourceLocation Loc);
8423 /// \brief Start analysis of clauses.
8424 void StartOpenMPClause(OpenMPClauseKind K);
8425 /// \brief End analysis of clauses.
8426 void EndOpenMPClause();
8427 /// \brief Called on end of data sharing attribute block.
8428 void EndOpenMPDSABlock(Stmt *CurDirective);
8430 /// \brief Check if the current region is an OpenMP loop region and if it is,
8431 /// mark loop control variable, used in \p Init for loop initialization, as
8432 /// private by default.
8433 /// \param Init First part of the for loop.
8434 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8436 // OpenMP directives and clauses.
8437 /// \brief Called on correct id-expression from the '#pragma omp
8439 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8440 CXXScopeSpec &ScopeSpec,
8441 const DeclarationNameInfo &Id);
8442 /// \brief Called on well-formed '#pragma omp threadprivate'.
8443 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8445 ArrayRef<Expr *> VarList);
8446 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8447 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8449 ArrayRef<Expr *> VarList);
8450 /// \brief Check if the specified type is allowed to be used in 'omp declare
8451 /// reduction' construct.
8452 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8453 TypeResult ParsedType);
8454 /// \brief Called on start of '#pragma omp declare reduction'.
8455 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8456 Scope *S, DeclContext *DC, DeclarationName Name,
8457 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8458 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8459 /// \brief Initialize declare reduction construct initializer.
8460 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8461 /// \brief Finish current declare reduction construct initializer.
8462 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8463 /// \brief Initialize declare reduction construct initializer.
8464 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8465 /// \brief Finish current declare reduction construct initializer.
8466 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8467 /// \brief Called at the end of '#pragma omp declare reduction'.
8468 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8469 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8471 /// Called on the start of target region i.e. '#pragma omp declare target'.
8472 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8473 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8474 void ActOnFinishOpenMPDeclareTargetDirective();
8475 /// Called on correct id-expression from the '#pragma omp declare target'.
8476 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8477 const DeclarationNameInfo &Id,
8478 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8479 NamedDeclSetType &SameDirectiveDecls);
8480 /// Check declaration inside target region.
8481 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8482 /// Return true inside OpenMP target region.
8483 bool isInOpenMPDeclareTargetContext() const {
8484 return IsInOpenMPDeclareTargetContext;
8487 /// Return the number of captured regions created for an OpenMP directive.
8488 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8490 /// \brief Initialization of captured region for OpenMP region.
8491 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8492 /// \brief End of OpenMP region.
8494 /// \param S Statement associated with the current OpenMP region.
8495 /// \param Clauses List of clauses for the current OpenMP region.
8497 /// \returns Statement for finished OpenMP region.
8498 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8499 StmtResult ActOnOpenMPExecutableDirective(
8500 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8501 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8502 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8503 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8504 /// of the associated statement.
8505 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8507 SourceLocation StartLoc,
8508 SourceLocation EndLoc);
8509 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8510 /// of the associated statement.
8511 StmtResult ActOnOpenMPSimdDirective(
8512 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8513 SourceLocation EndLoc,
8514 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8515 /// \brief Called on well-formed '\#pragma omp for' after parsing
8516 /// of the associated statement.
8517 StmtResult ActOnOpenMPForDirective(
8518 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8519 SourceLocation EndLoc,
8520 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8521 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8522 /// of the associated statement.
8523 StmtResult ActOnOpenMPForSimdDirective(
8524 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8525 SourceLocation EndLoc,
8526 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8527 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8528 /// of the associated statement.
8529 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8530 Stmt *AStmt, SourceLocation StartLoc,
8531 SourceLocation EndLoc);
8532 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8533 /// associated statement.
8534 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8535 SourceLocation EndLoc);
8536 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8537 /// associated statement.
8538 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8539 Stmt *AStmt, SourceLocation StartLoc,
8540 SourceLocation EndLoc);
8541 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8542 /// associated statement.
8543 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8544 SourceLocation EndLoc);
8545 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8546 /// associated statement.
8547 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8548 ArrayRef<OMPClause *> Clauses,
8549 Stmt *AStmt, SourceLocation StartLoc,
8550 SourceLocation EndLoc);
8551 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8552 /// of the associated statement.
8553 StmtResult ActOnOpenMPParallelForDirective(
8554 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8555 SourceLocation EndLoc,
8556 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8557 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8558 /// parsing of the associated statement.
8559 StmtResult ActOnOpenMPParallelForSimdDirective(
8560 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8561 SourceLocation EndLoc,
8562 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8563 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8564 /// parsing of the associated statement.
8565 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8567 SourceLocation StartLoc,
8568 SourceLocation EndLoc);
8569 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8570 /// associated statement.
8571 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8572 Stmt *AStmt, SourceLocation StartLoc,
8573 SourceLocation EndLoc);
8574 /// \brief Called on well-formed '\#pragma omp taskyield'.
8575 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8576 SourceLocation EndLoc);
8577 /// \brief Called on well-formed '\#pragma omp barrier'.
8578 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8579 SourceLocation EndLoc);
8580 /// \brief Called on well-formed '\#pragma omp taskwait'.
8581 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8582 SourceLocation EndLoc);
8583 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8584 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8585 SourceLocation EndLoc);
8586 /// \brief Called on well-formed '\#pragma omp flush'.
8587 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8588 SourceLocation StartLoc,
8589 SourceLocation EndLoc);
8590 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8591 /// associated statement.
8592 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8593 Stmt *AStmt, SourceLocation StartLoc,
8594 SourceLocation EndLoc);
8595 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8596 /// associated statement.
8597 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8598 Stmt *AStmt, SourceLocation StartLoc,
8599 SourceLocation EndLoc);
8600 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8601 /// associated statement.
8602 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8603 Stmt *AStmt, SourceLocation StartLoc,
8604 SourceLocation EndLoc);
8605 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8606 /// the associated statement.
8607 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8608 Stmt *AStmt, SourceLocation StartLoc,
8609 SourceLocation EndLoc);
8610 /// \brief Called on well-formed '\#pragma omp target enter data' after
8611 /// parsing of the associated statement.
8612 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8613 SourceLocation StartLoc,
8614 SourceLocation EndLoc);
8615 /// \brief Called on well-formed '\#pragma omp target exit data' after
8616 /// parsing of the associated statement.
8617 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8618 SourceLocation StartLoc,
8619 SourceLocation EndLoc);
8620 /// \brief Called on well-formed '\#pragma omp target parallel' after
8621 /// parsing of the associated statement.
8622 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8624 SourceLocation StartLoc,
8625 SourceLocation EndLoc);
8626 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8627 /// parsing of the associated statement.
8628 StmtResult ActOnOpenMPTargetParallelForDirective(
8629 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8630 SourceLocation EndLoc,
8631 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8632 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8633 /// associated statement.
8634 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8635 Stmt *AStmt, SourceLocation StartLoc,
8636 SourceLocation EndLoc);
8637 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8639 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8640 SourceLocation EndLoc,
8641 OpenMPDirectiveKind CancelRegion);
8642 /// \brief Called on well-formed '\#pragma omp cancel'.
8643 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8644 SourceLocation StartLoc,
8645 SourceLocation EndLoc,
8646 OpenMPDirectiveKind CancelRegion);
8647 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8648 /// associated statement.
8649 StmtResult ActOnOpenMPTaskLoopDirective(
8650 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8651 SourceLocation EndLoc,
8652 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8653 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8654 /// the associated statement.
8655 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8656 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8657 SourceLocation EndLoc,
8658 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8659 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8660 /// of the associated statement.
8661 StmtResult ActOnOpenMPDistributeDirective(
8662 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8663 SourceLocation EndLoc,
8664 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8665 /// \brief Called on well-formed '\#pragma omp target update'.
8666 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8667 SourceLocation StartLoc,
8668 SourceLocation EndLoc);
8669 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8670 /// parsing of the associated statement.
8671 StmtResult ActOnOpenMPDistributeParallelForDirective(
8672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8673 SourceLocation EndLoc,
8674 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8675 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8676 /// after parsing of the associated statement.
8677 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8679 SourceLocation EndLoc,
8680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8681 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8682 /// parsing of the associated statement.
8683 StmtResult ActOnOpenMPDistributeSimdDirective(
8684 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8685 SourceLocation EndLoc,
8686 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8687 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8688 /// parsing of the associated statement.
8689 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8690 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8691 SourceLocation EndLoc,
8692 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8693 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8694 /// the associated statement.
8695 StmtResult ActOnOpenMPTargetSimdDirective(
8696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8697 SourceLocation EndLoc,
8698 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8699 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8700 /// the associated statement.
8701 StmtResult ActOnOpenMPTeamsDistributeDirective(
8702 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8703 SourceLocation EndLoc,
8704 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8705 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8706 /// of the associated statement.
8707 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8708 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8709 SourceLocation EndLoc,
8710 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8711 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8712 /// after parsing of the associated statement.
8713 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8714 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8715 SourceLocation EndLoc,
8716 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8717 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8718 /// after parsing of the associated statement.
8719 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8720 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8721 SourceLocation EndLoc,
8722 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8723 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8724 /// associated statement.
8725 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8727 SourceLocation StartLoc,
8728 SourceLocation EndLoc);
8729 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8730 /// of the associated statement.
8731 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8732 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8733 SourceLocation EndLoc,
8734 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8735 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8736 /// after parsing of the associated statement.
8737 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8738 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8739 SourceLocation EndLoc,
8740 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8741 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8742 /// simd' after parsing of the associated statement.
8743 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8744 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8745 SourceLocation EndLoc,
8746 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8747 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8748 /// parsing of the associated statement.
8749 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8750 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8751 SourceLocation EndLoc,
8752 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8754 /// Checks correctness of linear modifiers.
8755 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8756 SourceLocation LinLoc);
8757 /// Checks that the specified declaration matches requirements for the linear
8759 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8760 OpenMPLinearClauseKind LinKind, QualType Type);
8762 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8763 /// the associated method/function.
8764 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8765 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8766 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8767 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8768 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8770 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8772 SourceLocation StartLoc,
8773 SourceLocation LParenLoc,
8774 SourceLocation EndLoc);
8775 /// \brief Called on well-formed 'if' clause.
8776 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8777 Expr *Condition, SourceLocation StartLoc,
8778 SourceLocation LParenLoc,
8779 SourceLocation NameModifierLoc,
8780 SourceLocation ColonLoc,
8781 SourceLocation EndLoc);
8782 /// \brief Called on well-formed 'final' clause.
8783 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8784 SourceLocation LParenLoc,
8785 SourceLocation EndLoc);
8786 /// \brief Called on well-formed 'num_threads' clause.
8787 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8788 SourceLocation StartLoc,
8789 SourceLocation LParenLoc,
8790 SourceLocation EndLoc);
8791 /// \brief Called on well-formed 'safelen' clause.
8792 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8793 SourceLocation StartLoc,
8794 SourceLocation LParenLoc,
8795 SourceLocation EndLoc);
8796 /// \brief Called on well-formed 'simdlen' clause.
8797 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8798 SourceLocation LParenLoc,
8799 SourceLocation EndLoc);
8800 /// \brief Called on well-formed 'collapse' clause.
8801 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8802 SourceLocation StartLoc,
8803 SourceLocation LParenLoc,
8804 SourceLocation EndLoc);
8805 /// \brief Called on well-formed 'ordered' clause.
8807 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8808 SourceLocation LParenLoc = SourceLocation(),
8809 Expr *NumForLoops = nullptr);
8810 /// \brief Called on well-formed 'grainsize' clause.
8811 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8812 SourceLocation LParenLoc,
8813 SourceLocation EndLoc);
8814 /// \brief Called on well-formed 'num_tasks' clause.
8815 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8816 SourceLocation LParenLoc,
8817 SourceLocation EndLoc);
8818 /// \brief Called on well-formed 'hint' clause.
8819 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8820 SourceLocation LParenLoc,
8821 SourceLocation EndLoc);
8823 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8825 SourceLocation ArgumentLoc,
8826 SourceLocation StartLoc,
8827 SourceLocation LParenLoc,
8828 SourceLocation EndLoc);
8829 /// \brief Called on well-formed 'default' clause.
8830 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8831 SourceLocation KindLoc,
8832 SourceLocation StartLoc,
8833 SourceLocation LParenLoc,
8834 SourceLocation EndLoc);
8835 /// \brief Called on well-formed 'proc_bind' clause.
8836 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8837 SourceLocation KindLoc,
8838 SourceLocation StartLoc,
8839 SourceLocation LParenLoc,
8840 SourceLocation EndLoc);
8842 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8843 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8844 SourceLocation StartLoc, SourceLocation LParenLoc,
8845 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8846 SourceLocation EndLoc);
8847 /// \brief Called on well-formed 'schedule' clause.
8848 OMPClause *ActOnOpenMPScheduleClause(
8849 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8850 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8851 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8852 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8854 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8855 SourceLocation EndLoc);
8856 /// \brief Called on well-formed 'nowait' clause.
8857 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8858 SourceLocation EndLoc);
8859 /// \brief Called on well-formed 'untied' clause.
8860 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8861 SourceLocation EndLoc);
8862 /// \brief Called on well-formed 'mergeable' clause.
8863 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8864 SourceLocation EndLoc);
8865 /// \brief Called on well-formed 'read' clause.
8866 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8867 SourceLocation EndLoc);
8868 /// \brief Called on well-formed 'write' clause.
8869 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8870 SourceLocation EndLoc);
8871 /// \brief Called on well-formed 'update' clause.
8872 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8873 SourceLocation EndLoc);
8874 /// \brief Called on well-formed 'capture' clause.
8875 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8876 SourceLocation EndLoc);
8877 /// \brief Called on well-formed 'seq_cst' clause.
8878 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8879 SourceLocation EndLoc);
8880 /// \brief Called on well-formed 'threads' clause.
8881 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8882 SourceLocation EndLoc);
8883 /// \brief Called on well-formed 'simd' clause.
8884 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8885 SourceLocation EndLoc);
8886 /// \brief Called on well-formed 'nogroup' clause.
8887 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8888 SourceLocation EndLoc);
8890 OMPClause *ActOnOpenMPVarListClause(
8891 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8892 SourceLocation StartLoc, SourceLocation LParenLoc,
8893 SourceLocation ColonLoc, SourceLocation EndLoc,
8894 CXXScopeSpec &ReductionIdScopeSpec,
8895 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8896 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8897 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8898 SourceLocation DepLinMapLoc);
8899 /// \brief Called on well-formed 'private' clause.
8900 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8901 SourceLocation StartLoc,
8902 SourceLocation LParenLoc,
8903 SourceLocation EndLoc);
8904 /// \brief Called on well-formed 'firstprivate' clause.
8905 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8906 SourceLocation StartLoc,
8907 SourceLocation LParenLoc,
8908 SourceLocation EndLoc);
8909 /// \brief Called on well-formed 'lastprivate' clause.
8910 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8911 SourceLocation StartLoc,
8912 SourceLocation LParenLoc,
8913 SourceLocation EndLoc);
8914 /// \brief Called on well-formed 'shared' clause.
8915 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8916 SourceLocation StartLoc,
8917 SourceLocation LParenLoc,
8918 SourceLocation EndLoc);
8919 /// \brief Called on well-formed 'reduction' clause.
8920 OMPClause *ActOnOpenMPReductionClause(
8921 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8922 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8923 CXXScopeSpec &ReductionIdScopeSpec,
8924 const DeclarationNameInfo &ReductionId,
8925 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8926 /// \brief Called on well-formed 'linear' clause.
8928 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8929 SourceLocation StartLoc, SourceLocation LParenLoc,
8930 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8931 SourceLocation ColonLoc, SourceLocation EndLoc);
8932 /// \brief Called on well-formed 'aligned' clause.
8933 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8935 SourceLocation StartLoc,
8936 SourceLocation LParenLoc,
8937 SourceLocation ColonLoc,
8938 SourceLocation EndLoc);
8939 /// \brief Called on well-formed 'copyin' clause.
8940 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8941 SourceLocation StartLoc,
8942 SourceLocation LParenLoc,
8943 SourceLocation EndLoc);
8944 /// \brief Called on well-formed 'copyprivate' clause.
8945 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8946 SourceLocation StartLoc,
8947 SourceLocation LParenLoc,
8948 SourceLocation EndLoc);
8949 /// \brief Called on well-formed 'flush' pseudo clause.
8950 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8951 SourceLocation StartLoc,
8952 SourceLocation LParenLoc,
8953 SourceLocation EndLoc);
8954 /// \brief Called on well-formed 'depend' clause.
8956 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8957 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8958 SourceLocation StartLoc, SourceLocation LParenLoc,
8959 SourceLocation EndLoc);
8960 /// \brief Called on well-formed 'device' clause.
8961 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8962 SourceLocation LParenLoc,
8963 SourceLocation EndLoc);
8964 /// \brief Called on well-formed 'map' clause.
8966 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8967 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8968 SourceLocation MapLoc, SourceLocation ColonLoc,
8969 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8970 SourceLocation LParenLoc, SourceLocation EndLoc);
8971 /// \brief Called on well-formed 'num_teams' clause.
8972 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8973 SourceLocation LParenLoc,
8974 SourceLocation EndLoc);
8975 /// \brief Called on well-formed 'thread_limit' clause.
8976 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8977 SourceLocation StartLoc,
8978 SourceLocation LParenLoc,
8979 SourceLocation EndLoc);
8980 /// \brief Called on well-formed 'priority' clause.
8981 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8982 SourceLocation LParenLoc,
8983 SourceLocation EndLoc);
8984 /// \brief Called on well-formed 'dist_schedule' clause.
8985 OMPClause *ActOnOpenMPDistScheduleClause(
8986 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8987 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8988 SourceLocation CommaLoc, SourceLocation EndLoc);
8989 /// \brief Called on well-formed 'defaultmap' clause.
8990 OMPClause *ActOnOpenMPDefaultmapClause(
8991 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8992 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8993 SourceLocation KindLoc, SourceLocation EndLoc);
8994 /// \brief Called on well-formed 'to' clause.
8995 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8996 SourceLocation StartLoc,
8997 SourceLocation LParenLoc,
8998 SourceLocation EndLoc);
8999 /// \brief Called on well-formed 'from' clause.
9000 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9001 SourceLocation StartLoc,
9002 SourceLocation LParenLoc,
9003 SourceLocation EndLoc);
9004 /// Called on well-formed 'use_device_ptr' clause.
9005 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9006 SourceLocation StartLoc,
9007 SourceLocation LParenLoc,
9008 SourceLocation EndLoc);
9009 /// Called on well-formed 'is_device_ptr' clause.
9010 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9011 SourceLocation StartLoc,
9012 SourceLocation LParenLoc,
9013 SourceLocation EndLoc);
9015 /// \brief The kind of conversion being performed.
9016 enum CheckedConversionKind {
9017 /// \brief An implicit conversion.
9018 CCK_ImplicitConversion,
9019 /// \brief A C-style cast.
9021 /// \brief A functional-style cast.
9023 /// \brief A cast other than a C-style cast.
9027 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9028 /// cast. If there is already an implicit cast, merge into the existing one.
9029 /// If isLvalue, the result of the cast is an lvalue.
9030 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9031 ExprValueKind VK = VK_RValue,
9032 const CXXCastPath *BasePath = nullptr,
9033 CheckedConversionKind CCK
9034 = CCK_ImplicitConversion);
9036 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9037 /// to the conversion from scalar type ScalarTy to the Boolean type.
9038 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9040 /// IgnoredValueConversions - Given that an expression's result is
9041 /// syntactically ignored, perform any conversions that are
9043 ExprResult IgnoredValueConversions(Expr *E);
9045 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9046 // functions and arrays to their respective pointers (C99 6.3.2.1).
9047 ExprResult UsualUnaryConversions(Expr *E);
9049 /// CallExprUnaryConversions - a special case of an unary conversion
9050 /// performed on a function designator of a call expression.
9051 ExprResult CallExprUnaryConversions(Expr *E);
9053 // DefaultFunctionArrayConversion - converts functions and arrays
9054 // to their respective pointers (C99 6.3.2.1).
9055 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9057 // DefaultFunctionArrayLvalueConversion - converts functions and
9058 // arrays to their respective pointers and performs the
9059 // lvalue-to-rvalue conversion.
9060 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9061 bool Diagnose = true);
9063 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9064 // the operand. This is DefaultFunctionArrayLvalueConversion,
9065 // except that it assumes the operand isn't of function or array
9067 ExprResult DefaultLvalueConversion(Expr *E);
9069 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9070 // do not have a prototype. Integer promotions are performed on each
9071 // argument, and arguments that have type float are promoted to double.
9072 ExprResult DefaultArgumentPromotion(Expr *E);
9074 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9075 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9076 /// we don't have xvalues there.
9077 ExprResult TemporaryMaterializationConversion(Expr *E);
9079 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9080 enum VariadicCallType {
9084 VariadicConstructor,
9085 VariadicDoesNotApply
9088 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9089 const FunctionProtoType *Proto,
9092 // Used for determining in which context a type is allowed to be passed to a
9102 // Determines which VarArgKind fits an expression.
9103 VarArgKind isValidVarArgType(const QualType &Ty);
9105 /// Check to see if the given expression is a valid argument to a variadic
9106 /// function, issuing a diagnostic if not.
9107 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9109 /// Check to see if a given expression could have '.c_str()' called on it.
9110 bool hasCStrMethod(const Expr *E);
9112 /// GatherArgumentsForCall - Collector argument expressions for various
9113 /// form of call prototypes.
9114 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9115 const FunctionProtoType *Proto,
9116 unsigned FirstParam, ArrayRef<Expr *> Args,
9117 SmallVectorImpl<Expr *> &AllArgs,
9118 VariadicCallType CallType = VariadicDoesNotApply,
9119 bool AllowExplicit = false,
9120 bool IsListInitialization = false);
9122 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9123 // will create a runtime trap if the resulting type is not a POD type.
9124 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9125 FunctionDecl *FDecl);
9127 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9128 // operands and then handles various conversions that are common to binary
9129 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9130 // routine returns the first non-arithmetic type found. The client is
9131 // responsible for emitting appropriate error diagnostics.
9132 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9133 bool IsCompAssign = false);
9135 /// AssignConvertType - All of the 'assignment' semantic checks return this
9136 /// enum to indicate whether the assignment was allowed. These checks are
9137 /// done for simple assignments, as well as initialization, return from
9138 /// function, argument passing, etc. The query is phrased in terms of a
9139 /// source and destination type.
9140 enum AssignConvertType {
9141 /// Compatible - the types are compatible according to the standard.
9144 /// PointerToInt - The assignment converts a pointer to an int, which we
9145 /// accept as an extension.
9148 /// IntToPointer - The assignment converts an int to a pointer, which we
9149 /// accept as an extension.
9152 /// FunctionVoidPointer - The assignment is between a function pointer and
9153 /// void*, which the standard doesn't allow, but we accept as an extension.
9154 FunctionVoidPointer,
9156 /// IncompatiblePointer - The assignment is between two pointers types that
9157 /// are not compatible, but we accept them as an extension.
9158 IncompatiblePointer,
9160 /// IncompatiblePointerSign - The assignment is between two pointers types
9161 /// which point to integers which have a different sign, but are otherwise
9162 /// identical. This is a subset of the above, but broken out because it's by
9163 /// far the most common case of incompatible pointers.
9164 IncompatiblePointerSign,
9166 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9167 /// c/v/r qualifiers, which we accept as an extension.
9168 CompatiblePointerDiscardsQualifiers,
9170 /// IncompatiblePointerDiscardsQualifiers - The assignment
9171 /// discards qualifiers that we don't permit to be discarded,
9172 /// like address spaces.
9173 IncompatiblePointerDiscardsQualifiers,
9175 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9176 /// nested pointer types, and the qualifiers other than the first two
9177 /// levels differ e.g. char ** -> const char **, but we accept them as an
9179 IncompatibleNestedPointerQualifiers,
9181 /// IncompatibleVectors - The assignment is between two vector types that
9182 /// have the same size, which we accept as an extension.
9183 IncompatibleVectors,
9185 /// IntToBlockPointer - The assignment converts an int to a block
9186 /// pointer. We disallow this.
9189 /// IncompatibleBlockPointer - The assignment is between two block
9190 /// pointers types that are not compatible.
9191 IncompatibleBlockPointer,
9193 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9194 /// id type and something else (that is incompatible with it). For example,
9195 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9196 IncompatibleObjCQualifiedId,
9198 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9199 /// object with __weak qualifier.
9200 IncompatibleObjCWeakRef,
9202 /// Incompatible - We reject this conversion outright, it is invalid to
9203 /// represent it in the AST.
9207 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9208 /// assignment conversion type specified by ConvTy. This returns true if the
9209 /// conversion was invalid or false if the conversion was accepted.
9210 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9212 QualType DstType, QualType SrcType,
9213 Expr *SrcExpr, AssignmentAction Action,
9214 bool *Complained = nullptr);
9216 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9217 /// enum. If AllowMask is true, then we also allow the complement of a valid
9218 /// value, to be used as a mask.
9219 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9220 bool AllowMask) const;
9222 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9223 /// integer not in the range of enum values.
9224 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9227 /// CheckAssignmentConstraints - Perform type checking for assignment,
9228 /// argument passing, variable initialization, and function return values.
9230 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9234 /// Check assignment constraints and optionally prepare for a conversion of
9235 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9237 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9240 bool ConvertRHS = true);
9242 /// Check assignment constraints for an assignment of RHS to LHSType.
9244 /// \param LHSType The destination type for the assignment.
9245 /// \param RHS The source expression for the assignment.
9246 /// \param Diagnose If \c true, diagnostics may be produced when checking
9247 /// for assignability. If a diagnostic is produced, \p RHS will be
9248 /// set to ExprError(). Note that this function may still return
9249 /// without producing a diagnostic, even for an invalid assignment.
9250 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9251 /// in an audited Core Foundation API and does not need to be checked
9252 /// for ARC retain issues.
9253 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9254 /// conversions necessary to perform the assignment. If \c false,
9255 /// \p Diagnose must also be \c false.
9256 AssignConvertType CheckSingleAssignmentConstraints(
9257 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9258 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9260 // \brief If the lhs type is a transparent union, check whether we
9261 // can initialize the transparent union with the given expression.
9262 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9265 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9267 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9269 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9270 AssignmentAction Action,
9271 bool AllowExplicit = false);
9272 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9273 AssignmentAction Action,
9275 ImplicitConversionSequence& ICS);
9276 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9277 const ImplicitConversionSequence& ICS,
9278 AssignmentAction Action,
9279 CheckedConversionKind CCK
9280 = CCK_ImplicitConversion);
9281 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9282 const StandardConversionSequence& SCS,
9283 AssignmentAction Action,
9284 CheckedConversionKind CCK);
9286 /// the following "Check" methods will return a valid/converted QualType
9287 /// or a null QualType (indicating an error diagnostic was issued).
9289 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9290 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9292 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9294 QualType CheckPointerToMemberOperands( // C++ 5.5
9295 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9296 SourceLocation OpLoc, bool isIndirect);
9297 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9298 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9300 QualType CheckRemainderOperands( // C99 6.5.5
9301 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9302 bool IsCompAssign = false);
9303 QualType CheckAdditionOperands( // C99 6.5.6
9304 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9305 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9306 QualType CheckSubtractionOperands( // C99 6.5.6
9307 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9308 QualType* CompLHSTy = nullptr);
9309 QualType CheckShiftOperands( // C99 6.5.7
9310 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9311 BinaryOperatorKind Opc, bool IsCompAssign = false);
9312 QualType CheckCompareOperands( // C99 6.5.8/9
9313 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9314 BinaryOperatorKind Opc, bool isRelational);
9315 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9316 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9317 BinaryOperatorKind Opc);
9318 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9319 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9320 BinaryOperatorKind Opc);
9321 // CheckAssignmentOperands is used for both simple and compound assignment.
9322 // For simple assignment, pass both expressions and a null converted type.
9323 // For compound assignment, pass both expressions and the converted type.
9324 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9325 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9327 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9328 UnaryOperatorKind Opcode, Expr *Op);
9329 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9330 BinaryOperatorKind Opcode,
9331 Expr *LHS, Expr *RHS);
9332 ExprResult checkPseudoObjectRValue(Expr *E);
9333 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9335 QualType CheckConditionalOperands( // C99 6.5.15
9336 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9337 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9338 QualType CXXCheckConditionalOperands( // C++ 5.16
9339 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9340 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9341 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9342 bool ConvertArgs = true);
9343 QualType FindCompositePointerType(SourceLocation Loc,
9344 ExprResult &E1, ExprResult &E2,
9345 bool ConvertArgs = true) {
9346 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9347 QualType Composite =
9348 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9354 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9355 SourceLocation QuestionLoc);
9357 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9358 SourceLocation QuestionLoc);
9360 void DiagnoseAlwaysNonNullPointer(Expr *E,
9361 Expr::NullPointerConstantKind NullType,
9362 bool IsEqual, SourceRange Range);
9364 /// type checking for vector binary operators.
9365 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9366 SourceLocation Loc, bool IsCompAssign,
9367 bool AllowBothBool, bool AllowBoolConversion);
9368 QualType GetSignedVectorType(QualType V);
9369 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9370 SourceLocation Loc, bool isRelational);
9371 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9372 SourceLocation Loc);
9374 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9375 bool isLaxVectorConversion(QualType srcType, QualType destType);
9377 /// type checking declaration initializers (C99 6.7.8)
9378 bool CheckForConstantInitializer(Expr *e, QualType t);
9380 // type checking C++ declaration initializers (C++ [dcl.init]).
9382 /// ReferenceCompareResult - Expresses the result of comparing two
9383 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9384 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9385 enum ReferenceCompareResult {
9386 /// Ref_Incompatible - The two types are incompatible, so direct
9387 /// reference binding is not possible.
9388 Ref_Incompatible = 0,
9389 /// Ref_Related - The two types are reference-related, which means
9390 /// that their unqualified forms (T1 and T2) are either the same
9391 /// or T1 is a base class of T2.
9393 /// Ref_Compatible - The two types are reference-compatible.
9397 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9398 QualType T1, QualType T2,
9399 bool &DerivedToBase,
9400 bool &ObjCConversion,
9401 bool &ObjCLifetimeConversion);
9403 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9404 Expr *CastExpr, CastKind &CastKind,
9405 ExprValueKind &VK, CXXCastPath &Path);
9407 /// \brief Force an expression with unknown-type to an expression of the
9409 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9411 /// \brief Type-check an expression that's being passed to an
9412 /// __unknown_anytype parameter.
9413 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9414 Expr *result, QualType ¶mType);
9416 // CheckVectorCast - check type constraints for vectors.
9417 // Since vectors are an extension, there are no C standard reference for this.
9418 // We allow casting between vectors and integer datatypes of the same size.
9419 // returns true if the cast is invalid
9420 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9423 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9424 /// implicit casts if necessary.
9425 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9427 // CheckExtVectorCast - check type constraints for extended vectors.
9428 // Since vectors are an extension, there are no C standard reference for this.
9429 // We allow casting between vectors and integer datatypes of the same size,
9430 // or vectors and the element type of that vector.
9431 // returns the cast expr
9432 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9435 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9436 SourceLocation LParenLoc,
9438 SourceLocation RParenLoc);
9440 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9442 /// \brief Checks for invalid conversions and casts between
9443 /// retainable pointers and other pointer kinds for ARC and Weak.
9444 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9445 QualType castType, Expr *&op,
9446 CheckedConversionKind CCK,
9447 bool Diagnose = true,
9448 bool DiagnoseCFAudited = false,
9449 BinaryOperatorKind Opc = BO_PtrMemD
9452 Expr *stripARCUnbridgedCast(Expr *e);
9453 void diagnoseARCUnbridgedCast(Expr *e);
9455 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9458 /// checkRetainCycles - Check whether an Objective-C message send
9459 /// might create an obvious retain cycle.
9460 void checkRetainCycles(ObjCMessageExpr *msg);
9461 void checkRetainCycles(Expr *receiver, Expr *argument);
9462 void checkRetainCycles(VarDecl *Var, Expr *Init);
9464 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9465 /// to weak/__unsafe_unretained type.
9466 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9468 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9469 /// to weak/__unsafe_unretained expression.
9470 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9472 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9473 /// \param Method - May be null.
9474 /// \param [out] ReturnType - The return type of the send.
9475 /// \return true iff there were any incompatible types.
9476 bool CheckMessageArgumentTypes(QualType ReceiverType,
9477 MultiExprArg Args, Selector Sel,
9478 ArrayRef<SourceLocation> SelectorLocs,
9479 ObjCMethodDecl *Method, bool isClassMessage,
9480 bool isSuperMessage,
9481 SourceLocation lbrac, SourceLocation rbrac,
9482 SourceRange RecRange,
9483 QualType &ReturnType, ExprValueKind &VK);
9485 /// \brief Determine the result of a message send expression based on
9486 /// the type of the receiver, the method expected to receive the message,
9487 /// and the form of the message send.
9488 QualType getMessageSendResultType(QualType ReceiverType,
9489 ObjCMethodDecl *Method,
9490 bool isClassMessage, bool isSuperMessage);
9492 /// \brief If the given expression involves a message send to a method
9493 /// with a related result type, emit a note describing what happened.
9494 void EmitRelatedResultTypeNote(const Expr *E);
9496 /// \brief Given that we had incompatible pointer types in a return
9497 /// statement, check whether we're in a method with a related result
9498 /// type, and if so, emit a note describing what happened.
9499 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9501 class ConditionResult {
9503 FullExprArg Condition;
9509 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9511 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9512 HasKnownValue(IsConstexpr && Condition.get() &&
9513 !Condition.get()->isValueDependent()),
9514 KnownValue(HasKnownValue &&
9515 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9516 explicit ConditionResult(bool Invalid)
9517 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9518 HasKnownValue(false), KnownValue(false) {}
9521 ConditionResult() : ConditionResult(false) {}
9522 bool isInvalid() const { return Invalid; }
9523 std::pair<VarDecl *, Expr *> get() const {
9524 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9527 llvm::Optional<bool> getKnownValue() const {
9533 static ConditionResult ConditionError() { return ConditionResult(true); }
9535 enum class ConditionKind {
9536 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9537 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9538 Switch ///< An integral condition for a 'switch' statement.
9541 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9542 Expr *SubExpr, ConditionKind CK);
9544 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9545 SourceLocation StmtLoc,
9548 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9550 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9551 SourceLocation StmtLoc,
9553 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9555 /// CheckBooleanCondition - Diagnose problems involving the use of
9556 /// the given expression as a boolean condition (e.g. in an if
9557 /// statement). Also performs the standard function and array
9558 /// decays, possibly changing the input variable.
9560 /// \param Loc - A location associated with the condition, e.g. the
9562 /// \return true iff there were any errors
9563 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9564 bool IsConstexpr = false);
9566 /// DiagnoseAssignmentAsCondition - Given that an expression is
9567 /// being used as a boolean condition, warn if it's an assignment.
9568 void DiagnoseAssignmentAsCondition(Expr *E);
9570 /// \brief Redundant parentheses over an equality comparison can indicate
9571 /// that the user intended an assignment used as condition.
9572 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9574 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9575 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9577 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9578 /// the specified width and sign. If an overflow occurs, detect it and emit
9579 /// the specified diagnostic.
9580 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9581 unsigned NewWidth, bool NewSign,
9582 SourceLocation Loc, unsigned DiagID);
9584 /// Checks that the Objective-C declaration is declared in the global scope.
9585 /// Emits an error and marks the declaration as invalid if it's not declared
9586 /// in the global scope.
9587 bool CheckObjCDeclScope(Decl *D);
9589 /// \brief Abstract base class used for diagnosing integer constant
9590 /// expression violations.
9591 class VerifyICEDiagnoser {
9595 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9597 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9598 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9599 virtual ~VerifyICEDiagnoser() { }
9602 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9603 /// and reports the appropriate diagnostics. Returns false on success.
9604 /// Can optionally return the value of the expression.
9605 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9606 VerifyICEDiagnoser &Diagnoser,
9607 bool AllowFold = true);
9608 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9610 bool AllowFold = true);
9611 ExprResult VerifyIntegerConstantExpression(Expr *E,
9612 llvm::APSInt *Result = nullptr);
9614 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9615 /// the correct width, and that the field type is valid.
9616 /// Returns false on success.
9617 /// Can optionally return whether the bit-field is of width 0
9618 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9619 QualType FieldTy, bool IsMsStruct,
9620 Expr *BitWidth, bool *ZeroWidth = nullptr);
9623 unsigned ForceCUDAHostDeviceDepth = 0;
9626 /// Increments our count of the number of times we've seen a pragma forcing
9627 /// functions to be __host__ __device__. So long as this count is greater
9628 /// than zero, all functions encountered will be __host__ __device__.
9629 void PushForceCUDAHostDevice();
9631 /// Decrements our count of the number of times we've seen a pragma forcing
9632 /// functions to be __host__ __device__. Returns false if the count is 0
9633 /// before incrementing, so you can emit an error.
9634 bool PopForceCUDAHostDevice();
9636 /// Diagnostics that are emitted only if we discover that the given function
9637 /// must be codegen'ed. Because handling these correctly adds overhead to
9638 /// compilation, this is currently only enabled for CUDA compilations.
9639 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9640 std::vector<PartialDiagnosticAt>>
9643 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9644 /// key in a hashtable, both the FD and location are hashed.
9645 struct FunctionDeclAndLoc {
9646 CanonicalDeclPtr<FunctionDecl> FD;
9650 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9651 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9652 /// same deferred diag twice.
9653 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9655 /// An inverse call graph, mapping known-emitted functions to one of their
9656 /// known-emitted callers (plus the location of the call).
9658 /// Functions that we can tell a priori must be emitted aren't added to this
9660 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9661 /* Caller = */ FunctionDeclAndLoc>
9662 CUDAKnownEmittedFns;
9664 /// A partial call graph maintained during CUDA compilation to support
9665 /// deferred diagnostics.
9667 /// Functions are only added here if, at the time they're considered, they are
9668 /// not known-emitted. As soon as we discover that a function is
9669 /// known-emitted, we remove it and everything it transitively calls from this
9670 /// set and add those functions to CUDAKnownEmittedFns.
9671 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9672 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9676 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9678 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9679 /// which are not allowed to appear inside __device__ functions and are
9680 /// allowed to appear in __host__ __device__ functions only if the host+device
9681 /// function is never codegen'ed.
9683 /// To handle this, we use the notion of "deferred diagnostics", where we
9684 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9686 /// This class lets you emit either a regular diagnostic, a deferred
9687 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9688 /// its constructor, thus simplifying the process of creating these "maybe
9689 /// deferred" diagnostics.
9690 class CUDADiagBuilder {
9693 /// Emit no diagnostics.
9695 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9697 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9698 /// emit a call stack showing how this function can be reached by an a
9699 /// priori known-emitted function.
9700 K_ImmediateWithCallStack,
9701 /// Create a deferred diagnostic, which is emitted only if the function
9702 /// it's attached to is codegen'ed. Also emit a call stack as with
9703 /// K_ImmediateWithCallStack.
9707 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9708 FunctionDecl *Fn, Sema &S);
9711 /// Convertible to bool: True if we immediately emitted an error, false if
9712 /// we didn't emit an error or we created a deferred error.
9716 /// if (CUDADiagBuilder(...) << foo << bar)
9717 /// return ExprError();
9719 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9720 /// want to use these instead of creating a CUDADiagBuilder yourself.
9721 operator bool() const { return ImmediateDiag.hasValue(); }
9723 template <typename T>
9724 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9726 if (Diag.ImmediateDiag.hasValue())
9727 *Diag.ImmediateDiag << Value;
9728 else if (Diag.PartialDiag.hasValue())
9729 *Diag.PartialDiag << Value;
9740 // Invariant: At most one of these Optionals has a value.
9741 // FIXME: Switch these to a Variant once that exists.
9742 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9743 llvm::Optional<PartialDiagnostic> PartialDiag;
9746 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9747 /// is "used as device code".
9749 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9750 /// - If CurContext is a __device__ or __global__ function, emits the
9751 /// diagnostics immediately.
9752 /// - If CurContext is a __host__ __device__ function and we are compiling for
9753 /// the device, creates a diagnostic which is emitted if and when we realize
9754 /// that the function will be codegen'ed.
9758 /// // Variable-length arrays are not allowed in CUDA device code.
9759 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9760 /// return ExprError();
9761 /// // Otherwise, continue parsing as normal.
9762 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9764 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9765 /// is "used as host code".
9767 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9768 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9770 enum CUDAFunctionTarget {
9778 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9781 /// Use this rather than examining the function's attributes yourself -- you
9782 /// will get it wrong. Returns CFT_Host if D is null.
9783 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9784 bool IgnoreImplicitHDAttr = false);
9785 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9787 /// Gets the CUDA target for the current context.
9788 CUDAFunctionTarget CurrentCUDATarget() {
9789 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9792 // CUDA function call preference. Must be ordered numerically from
9794 enum CUDAFunctionPreference {
9795 CFP_Never, // Invalid caller/callee combination.
9796 CFP_WrongSide, // Calls from host-device to host or device
9797 // function that do not match current compilation
9799 CFP_HostDevice, // Any calls to host/device functions.
9800 CFP_SameSide, // Calls from host-device to host or device
9801 // function matching current compilation mode.
9802 CFP_Native, // host-to-host or device-to-device calls.
9805 /// Identifies relative preference of a given Caller/Callee
9806 /// combination, based on their host/device attributes.
9807 /// \param Caller function which needs address of \p Callee.
9808 /// nullptr in case of global context.
9809 /// \param Callee target function
9811 /// \returns preference value for particular Caller/Callee combination.
9812 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9813 const FunctionDecl *Callee);
9815 /// Determines whether Caller may invoke Callee, based on their CUDA
9816 /// host/device attributes. Returns false if the call is not allowed.
9818 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9819 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9820 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9821 const FunctionDecl *Callee) {
9822 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9825 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9826 /// depending on FD and the current compilation settings.
9827 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9828 const LookupResult &Previous);
9831 /// Check whether we're allowed to call Callee from the current context.
9833 /// - If the call is never allowed in a semantically-correct program
9834 /// (CFP_Never), emits an error and returns false.
9836 /// - If the call is allowed in semantically-correct programs, but only if
9837 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9838 /// be emitted if and when the caller is codegen'ed, and returns true.
9840 /// Will only create deferred diagnostics for a given SourceLocation once,
9841 /// so you can safely call this multiple times without generating duplicate
9842 /// deferred errors.
9844 /// - Otherwise, returns true without emitting any diagnostics.
9845 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9847 /// Set __device__ or __host__ __device__ attributes on the given lambda
9848 /// operator() method.
9850 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9851 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9852 /// functions become __host__ __device__ themselves.
9853 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9855 /// Finds a function in \p Matches with highest calling priority
9856 /// from \p Caller context and erases all functions with lower
9857 /// calling priority.
9858 void EraseUnwantedCUDAMatches(
9859 const FunctionDecl *Caller,
9860 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9862 /// Given a implicit special member, infer its CUDA target from the
9863 /// calls it needs to make to underlying base/field special members.
9864 /// \param ClassDecl the class for which the member is being created.
9865 /// \param CSM the kind of special member.
9866 /// \param MemberDecl the special member itself.
9867 /// \param ConstRHS true if this is a copy operation with a const object on
9869 /// \param Diagnose true if this call should emit diagnostics.
9870 /// \return true if there was an error inferring.
9871 /// The result of this call is implicit CUDA target attribute(s) attached to
9872 /// the member declaration.
9873 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9874 CXXSpecialMember CSM,
9875 CXXMethodDecl *MemberDecl,
9879 /// \return true if \p CD can be considered empty according to CUDA
9880 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9881 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9882 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9884 /// Check whether NewFD is a valid overload for CUDA. Emits
9885 /// diagnostics and invalidates NewFD if not.
9886 void checkCUDATargetOverload(FunctionDecl *NewFD,
9887 const LookupResult &Previous);
9888 /// Copies target attributes from the template TD to the function FD.
9889 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9891 /// \name Code completion
9893 /// \brief Describes the context in which code completion occurs.
9894 enum ParserCompletionContext {
9895 /// \brief Code completion occurs at top-level or namespace context.
9897 /// \brief Code completion occurs within a class, struct, or union.
9899 /// \brief Code completion occurs within an Objective-C interface, protocol,
9902 /// \brief Code completion occurs within an Objective-C implementation or
9903 /// category implementation
9904 PCC_ObjCImplementation,
9905 /// \brief Code completion occurs within the list of instance variables
9906 /// in an Objective-C interface, protocol, category, or implementation.
9907 PCC_ObjCInstanceVariableList,
9908 /// \brief Code completion occurs following one or more template
9911 /// \brief Code completion occurs following one or more template
9912 /// headers within a class.
9914 /// \brief Code completion occurs within an expression.
9916 /// \brief Code completion occurs within a statement, which may
9917 /// also be an expression or a declaration.
9919 /// \brief Code completion occurs at the beginning of the
9920 /// initialization statement (or expression) in a for loop.
9922 /// \brief Code completion occurs within the condition of an if,
9923 /// while, switch, or for statement.
9925 /// \brief Code completion occurs within the body of a function on a
9926 /// recovery path, where we do not have a specific handle on our position
9928 PCC_RecoveryInFunction,
9929 /// \brief Code completion occurs where only a type is permitted.
9931 /// \brief Code completion occurs in a parenthesized expression, which
9932 /// might also be a type cast.
9933 PCC_ParenthesizedExpression,
9934 /// \brief Code completion occurs within a sequence of declaration
9935 /// specifiers within a function, method, or block.
9936 PCC_LocalDeclarationSpecifiers
9939 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9940 void CodeCompleteOrdinaryName(Scope *S,
9941 ParserCompletionContext CompletionContext);
9942 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9943 bool AllowNonIdentifiers,
9944 bool AllowNestedNameSpecifiers);
9946 struct CodeCompleteExpressionData;
9947 void CodeCompleteExpression(Scope *S,
9948 const CodeCompleteExpressionData &Data);
9949 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9950 SourceLocation OpLoc, bool IsArrow,
9951 bool IsBaseExprStatement);
9952 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9953 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9954 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9955 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9956 const VirtSpecifiers *VS = nullptr);
9957 void CodeCompleteBracketDeclarator(Scope *S);
9958 void CodeCompleteCase(Scope *S);
9959 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9960 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9961 ArrayRef<Expr *> Args);
9962 void CodeCompleteInitializer(Scope *S, Decl *D);
9963 void CodeCompleteReturn(Scope *S);
9964 void CodeCompleteAfterIf(Scope *S);
9965 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9967 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9968 bool EnteringContext);
9969 void CodeCompleteUsing(Scope *S);
9970 void CodeCompleteUsingDirective(Scope *S);
9971 void CodeCompleteNamespaceDecl(Scope *S);
9972 void CodeCompleteNamespaceAliasDecl(Scope *S);
9973 void CodeCompleteOperatorName(Scope *S);
9974 void CodeCompleteConstructorInitializer(
9976 ArrayRef<CXXCtorInitializer *> Initializers);
9978 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9979 bool AfterAmpersand);
9981 void CodeCompleteObjCAtDirective(Scope *S);
9982 void CodeCompleteObjCAtVisibility(Scope *S);
9983 void CodeCompleteObjCAtStatement(Scope *S);
9984 void CodeCompleteObjCAtExpression(Scope *S);
9985 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9986 void CodeCompleteObjCPropertyGetter(Scope *S);
9987 void CodeCompleteObjCPropertySetter(Scope *S);
9988 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9990 void CodeCompleteObjCMessageReceiver(Scope *S);
9991 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9992 ArrayRef<IdentifierInfo *> SelIdents,
9993 bool AtArgumentExpression);
9994 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9995 ArrayRef<IdentifierInfo *> SelIdents,
9996 bool AtArgumentExpression,
9997 bool IsSuper = false);
9998 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9999 ArrayRef<IdentifierInfo *> SelIdents,
10000 bool AtArgumentExpression,
10001 ObjCInterfaceDecl *Super = nullptr);
10002 void CodeCompleteObjCForCollection(Scope *S,
10003 DeclGroupPtrTy IterationVar);
10004 void CodeCompleteObjCSelector(Scope *S,
10005 ArrayRef<IdentifierInfo *> SelIdents);
10006 void CodeCompleteObjCProtocolReferences(
10007 ArrayRef<IdentifierLocPair> Protocols);
10008 void CodeCompleteObjCProtocolDecl(Scope *S);
10009 void CodeCompleteObjCInterfaceDecl(Scope *S);
10010 void CodeCompleteObjCSuperclass(Scope *S,
10011 IdentifierInfo *ClassName,
10012 SourceLocation ClassNameLoc);
10013 void CodeCompleteObjCImplementationDecl(Scope *S);
10014 void CodeCompleteObjCInterfaceCategory(Scope *S,
10015 IdentifierInfo *ClassName,
10016 SourceLocation ClassNameLoc);
10017 void CodeCompleteObjCImplementationCategory(Scope *S,
10018 IdentifierInfo *ClassName,
10019 SourceLocation ClassNameLoc);
10020 void CodeCompleteObjCPropertyDefinition(Scope *S);
10021 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10022 IdentifierInfo *PropertyName);
10023 void CodeCompleteObjCMethodDecl(Scope *S,
10024 bool IsInstanceMethod,
10025 ParsedType ReturnType);
10026 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10027 bool IsInstanceMethod,
10028 bool AtParameterName,
10029 ParsedType ReturnType,
10030 ArrayRef<IdentifierInfo *> SelIdents);
10031 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10032 SourceLocation ClassNameLoc,
10033 bool IsBaseExprStatement);
10034 void CodeCompletePreprocessorDirective(bool InConditional);
10035 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10036 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10037 void CodeCompletePreprocessorExpression();
10038 void CodeCompletePreprocessorMacroArgument(Scope *S,
10039 IdentifierInfo *Macro,
10040 MacroInfo *MacroInfo,
10041 unsigned Argument);
10042 void CodeCompleteNaturalLanguage();
10043 void CodeCompleteAvailabilityPlatformName();
10044 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10045 CodeCompletionTUInfo &CCTUInfo,
10046 SmallVectorImpl<CodeCompletionResult> &Results);
10049 //===--------------------------------------------------------------------===//
10050 // Extra semantic analysis beyond the C type system
10053 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10054 unsigned ByteNo) const;
10057 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10058 const ArraySubscriptExpr *ASE=nullptr,
10059 bool AllowOnePastEnd=true, bool IndexNegated=false);
10060 void CheckArrayAccess(const Expr *E);
10061 // Used to grab the relevant information from a FormatAttr and a
10062 // FunctionDeclaration.
10063 struct FormatStringInfo {
10064 unsigned FormatIdx;
10065 unsigned FirstDataArg;
10069 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10070 FormatStringInfo *FSI);
10071 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10072 const FunctionProtoType *Proto);
10073 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10074 ArrayRef<const Expr *> Args);
10075 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10076 const FunctionProtoType *Proto);
10077 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10078 void CheckConstructorCall(FunctionDecl *FDecl,
10079 ArrayRef<const Expr *> Args,
10080 const FunctionProtoType *Proto,
10081 SourceLocation Loc);
10083 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10084 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10085 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10086 VariadicCallType CallType);
10088 bool CheckObjCString(Expr *Arg);
10089 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10091 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10092 unsigned BuiltinID, CallExpr *TheCall);
10094 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10095 unsigned MaxWidth);
10096 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10097 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10099 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10100 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10101 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10102 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10103 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10104 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10105 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10107 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10108 bool SemaBuiltinVAStartARM(CallExpr *Call);
10109 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10110 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10111 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10114 // Used by C++ template instantiation.
10115 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10116 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10117 SourceLocation BuiltinLoc,
10118 SourceLocation RParenLoc);
10121 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10122 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10123 bool SemaBuiltinAssume(CallExpr *TheCall);
10124 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10125 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10126 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10127 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10128 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10129 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10130 AtomicExpr::AtomicOp Op);
10131 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10132 llvm::APSInt &Result);
10133 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10134 int Low, int High);
10135 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10136 unsigned Multiple);
10137 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10138 int ArgNum, unsigned ExpectedFieldNum,
10141 enum FormatStringType {
10148 FST_FreeBSDKPrintf,
10153 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10155 bool FormatStringHasSArg(const StringLiteral *FExpr);
10157 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10160 bool CheckFormatArguments(const FormatAttr *Format,
10161 ArrayRef<const Expr *> Args,
10163 VariadicCallType CallType,
10164 SourceLocation Loc, SourceRange Range,
10165 llvm::SmallBitVector &CheckedVarArgs);
10166 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10167 bool HasVAListArg, unsigned format_idx,
10168 unsigned firstDataArg, FormatStringType Type,
10169 VariadicCallType CallType,
10170 SourceLocation Loc, SourceRange range,
10171 llvm::SmallBitVector &CheckedVarArgs);
10173 void CheckAbsoluteValueFunction(const CallExpr *Call,
10174 const FunctionDecl *FDecl);
10176 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10178 void CheckMemaccessArguments(const CallExpr *Call,
10180 IdentifierInfo *FnName);
10182 void CheckStrlcpycatArguments(const CallExpr *Call,
10183 IdentifierInfo *FnName);
10185 void CheckStrncatArguments(const CallExpr *Call,
10186 IdentifierInfo *FnName);
10188 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10189 SourceLocation ReturnLoc,
10190 bool isObjCMethod = false,
10191 const AttrVec *Attrs = nullptr,
10192 const FunctionDecl *FD = nullptr);
10194 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10195 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10196 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10197 void CheckUnsequencedOperations(Expr *E);
10199 /// \brief Perform semantic checks on a completed expression. This will either
10200 /// be a full-expression or a default argument expression.
10201 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10202 bool IsConstexpr = false);
10204 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10207 /// Check if there is a field shadowing.
10208 void CheckShadowInheritedFields(const SourceLocation &Loc,
10209 DeclarationName FieldName,
10210 const CXXRecordDecl *RD);
10212 /// \brief Check if the given expression contains 'break' or 'continue'
10213 /// statement that produces control flow different from GCC.
10214 void CheckBreakContinueBinding(Expr *E);
10216 /// \brief Check whether receiver is mutable ObjC container which
10217 /// attempts to add itself into the container
10218 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10220 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10221 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10222 bool DeleteWasArrayForm);
10224 /// \brief Register a magic integral constant to be used as a type tag.
10225 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10226 uint64_t MagicValue, QualType Type,
10227 bool LayoutCompatible, bool MustBeNull);
10229 struct TypeTagData {
10232 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10233 Type(Type), LayoutCompatible(LayoutCompatible),
10234 MustBeNull(MustBeNull)
10239 /// If true, \c Type should be compared with other expression's types for
10240 /// layout-compatibility.
10241 unsigned LayoutCompatible : 1;
10242 unsigned MustBeNull : 1;
10245 /// A pair of ArgumentKind identifier and magic value. This uniquely
10246 /// identifies the magic value.
10247 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10250 /// \brief A map from magic value to type information.
10251 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10252 TypeTagForDatatypeMagicValues;
10254 /// \brief Peform checks on a call of a function with argument_with_type_tag
10255 /// or pointer_with_type_tag attributes.
10256 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10257 const Expr * const *ExprArgs);
10259 /// \brief Check if we are taking the address of a packed field
10260 /// as this may be a problem if the pointer value is dereferenced.
10261 void CheckAddressOfPackedMember(Expr *rhs);
10263 /// \brief The parser's current scope.
10265 /// The parser maintains this state here.
10268 mutable IdentifierInfo *Ident_super;
10269 mutable IdentifierInfo *Ident___float128;
10271 /// Nullability type specifiers.
10272 IdentifierInfo *Ident__Nonnull = nullptr;
10273 IdentifierInfo *Ident__Nullable = nullptr;
10274 IdentifierInfo *Ident__Null_unspecified = nullptr;
10276 IdentifierInfo *Ident_NSError = nullptr;
10279 friend class Parser;
10280 friend class InitializationSequence;
10281 friend class ASTReader;
10282 friend class ASTDeclReader;
10283 friend class ASTWriter;
10286 /// Retrieve the keyword associated
10287 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10289 /// The struct behind the CFErrorRef pointer.
10290 RecordDecl *CFError = nullptr;
10292 /// Retrieve the identifier "NSError".
10293 IdentifierInfo *getNSErrorIdent();
10295 /// \brief Retrieve the parser's current scope.
10297 /// This routine must only be used when it is certain that semantic analysis
10298 /// and the parser are in precisely the same context, which is not the case
10299 /// when, e.g., we are performing any kind of template instantiation.
10300 /// Therefore, the only safe places to use this scope are in the parser
10301 /// itself and in routines directly invoked from the parser and *never* from
10302 /// template substitution or instantiation.
10303 Scope *getCurScope() const { return CurScope; }
10305 void incrementMSManglingNumber() const {
10306 return CurScope->incrementMSManglingNumber();
10309 IdentifierInfo *getSuperIdentifier() const;
10310 IdentifierInfo *getFloat128Identifier() const;
10312 Decl *getObjCDeclContext() const;
10314 DeclContext *getCurLexicalContext() const {
10315 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10318 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10320 /// \param D The declaration to check. Note that this may be altered to point
10321 /// to another declaration that \c D gets it's availability from. i.e., we
10322 /// walk the list of typedefs to find an availability attribute.
10324 /// \param Message If non-null, this will be populated with the message from
10325 /// the availability attribute that is selected.
10326 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10327 std::string *Message);
10329 const DeclContext *getCurObjCLexicalContext() const {
10330 const DeclContext *DC = getCurLexicalContext();
10331 // A category implicitly has the attribute of the interface.
10332 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10333 DC = CatD->getClassInterface();
10337 /// \brief To be used for checking whether the arguments being passed to
10338 /// function exceeds the number of parameters expected for it.
10339 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10340 bool PartialOverloading = false) {
10341 // We check whether we're just after a comma in code-completion.
10342 if (NumArgs > 0 && PartialOverloading)
10343 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10344 return NumArgs > NumParams;
10347 // Emitting members of dllexported classes is delayed until the class
10348 // (including field initializers) is fully parsed.
10349 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10352 /// \brief Helper class that collects misaligned member designations and
10353 /// their location info for delayed diagnostics.
10354 struct MisalignedMember {
10358 CharUnits Alignment;
10360 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10361 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10362 CharUnits Alignment)
10363 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10364 explicit MisalignedMember(Expr *E)
10365 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10367 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10369 /// \brief Small set of gathered accesses to potentially misaligned members
10370 /// due to the packed attribute.
10371 SmallVector<MisalignedMember, 4> MisalignedMembers;
10373 /// \brief Adds an expression to the set of gathered misaligned members.
10374 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10375 CharUnits Alignment);
10378 /// \brief Diagnoses the current set of gathered accesses. This typically
10379 /// happens at full expression level. The set is cleared after emitting the
10381 void DiagnoseMisalignedMembers();
10383 /// \brief This function checks if the expression is in the sef of potentially
10384 /// misaligned members and it is converted to some pointer type T with lower
10385 /// or equal alignment requirements. If so it removes it. This is used when
10386 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10388 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10390 /// \brief This function calls Action when it determines that E designates a
10391 /// misaligned member due to the packed attribute. This is used to emit
10392 /// local diagnostics like in reference binding.
10393 void RefersToMemberWithReducedAlignment(
10395 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10399 /// \brief RAII object that enters a new expression evaluation context.
10400 class EnterExpressionEvaluationContext {
10402 bool Entered = true;
10406 EnterExpressionEvaluationContext(Sema &Actions,
10407 Sema::ExpressionEvaluationContext NewContext,
10408 Decl *LambdaContextDecl = nullptr,
10409 bool IsDecltype = false,
10410 bool ShouldEnter = true)
10411 : Actions(Actions), Entered(ShouldEnter) {
10413 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10416 EnterExpressionEvaluationContext(Sema &Actions,
10417 Sema::ExpressionEvaluationContext NewContext,
10418 Sema::ReuseLambdaContextDecl_t,
10419 bool IsDecltype = false)
10420 : Actions(Actions) {
10421 Actions.PushExpressionEvaluationContext(NewContext,
10422 Sema::ReuseLambdaContextDecl,
10426 enum InitListTag { InitList };
10427 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10428 bool ShouldEnter = true)
10429 : Actions(Actions), Entered(false) {
10430 // In C++11 onwards, narrowing checks are performed on the contents of
10431 // braced-init-lists, even when they occur within unevaluated operands.
10432 // Therefore we still need to instantiate constexpr functions used in such
10434 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10435 Actions.getLangOpts().CPlusPlus11) {
10436 Actions.PushExpressionEvaluationContext(
10437 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10442 ~EnterExpressionEvaluationContext() {
10444 Actions.PopExpressionEvaluationContext();
10448 DeductionFailureInfo
10449 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10450 sema::TemplateDeductionInfo &Info);
10452 /// \brief Contains a late templated function.
10453 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10454 struct LateParsedTemplate {
10456 /// \brief The template function declaration to be late parsed.
10460 } // end namespace clang
10463 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10465 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10466 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10467 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10469 static FunctionDeclAndLoc getEmptyKey() {
10470 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10473 static FunctionDeclAndLoc getTombstoneKey() {
10474 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10477 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10478 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10479 FDL.Loc.getRawEncoding());
10482 static bool isEqual(const FunctionDeclAndLoc &LHS,
10483 const FunctionDeclAndLoc &RHS) {
10484 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10487 } // namespace llvm