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;
692 bool PushedCodeSynthesisContext = false;
695 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
696 : S(S), SavedContext(S, DC) {
697 S.PushFunctionScope();
698 S.PushExpressionEvaluationContext(
699 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
700 if (auto *FD = dyn_cast<FunctionDecl>(DC))
701 FD->setWillHaveBody(true);
703 assert(isa<ObjCMethodDecl>(DC));
706 void addContextNote(SourceLocation UseLoc) {
707 assert(!PushedCodeSynthesisContext);
709 Sema::CodeSynthesisContext Ctx;
710 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
711 Ctx.PointOfInstantiation = UseLoc;
712 Ctx.Entity = cast<Decl>(S.CurContext);
713 S.pushCodeSynthesisContext(Ctx);
715 PushedCodeSynthesisContext = true;
718 ~SynthesizedFunctionScope() {
719 if (PushedCodeSynthesisContext)
720 S.popCodeSynthesisContext();
721 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
722 FD->setWillHaveBody(false);
723 S.PopExpressionEvaluationContext();
724 S.PopFunctionScopeInfo();
728 /// WeakUndeclaredIdentifiers - Identifiers contained in
729 /// \#pragma weak before declared. rare. may alias another
730 /// identifier, declared or undeclared
731 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
733 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
734 /// \#pragma redefine_extname before declared. Used in Solaris system headers
735 /// to define functions that occur in multiple standards to call the version
736 /// in the currently selected standard.
737 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
740 /// \brief Load weak undeclared identifiers from the external source.
741 void LoadExternalWeakUndeclaredIdentifiers();
743 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
744 /// \#pragma weak during processing of other Decls.
745 /// I couldn't figure out a clean way to generate these in-line, so
746 /// we store them here and handle separately -- which is a hack.
747 /// It would be best to refactor this.
748 SmallVector<Decl*,2> WeakTopLevelDecl;
750 IdentifierResolver IdResolver;
752 /// Translation Unit Scope - useful to Objective-C actions that need
753 /// to lookup file scope declarations in the "ordinary" C decl namespace.
754 /// For example, user-defined classes, built-in "id" type, etc.
757 /// \brief The C++ "std" namespace, where the standard library resides.
758 LazyDeclPtr StdNamespace;
760 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
761 /// standard library.
762 LazyDeclPtr StdBadAlloc;
764 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
765 /// standard library.
766 LazyDeclPtr StdAlignValT;
768 /// \brief The C++ "std::experimental" namespace, where the experimental parts
769 /// of the standard library resides.
770 NamespaceDecl *StdExperimentalNamespaceCache;
772 /// \brief The C++ "std::initializer_list" template, which is defined in
773 /// \<initializer_list>.
774 ClassTemplateDecl *StdInitializerList;
776 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
777 RecordDecl *CXXTypeInfoDecl;
779 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
780 RecordDecl *MSVCGuidDecl;
782 /// \brief Caches identifiers/selectors for NSFoundation APIs.
783 std::unique_ptr<NSAPI> NSAPIObj;
785 /// \brief The declaration of the Objective-C NSNumber class.
786 ObjCInterfaceDecl *NSNumberDecl;
788 /// \brief The declaration of the Objective-C NSValue class.
789 ObjCInterfaceDecl *NSValueDecl;
791 /// \brief Pointer to NSNumber type (NSNumber *).
792 QualType NSNumberPointer;
794 /// \brief Pointer to NSValue type (NSValue *).
795 QualType NSValuePointer;
797 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
798 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
800 /// \brief The declaration of the Objective-C NSString class.
801 ObjCInterfaceDecl *NSStringDecl;
803 /// \brief Pointer to NSString type (NSString *).
804 QualType NSStringPointer;
806 /// \brief The declaration of the stringWithUTF8String: method.
807 ObjCMethodDecl *StringWithUTF8StringMethod;
809 /// \brief The declaration of the valueWithBytes:objCType: method.
810 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
812 /// \brief The declaration of the Objective-C NSArray class.
813 ObjCInterfaceDecl *NSArrayDecl;
815 /// \brief The declaration of the arrayWithObjects:count: method.
816 ObjCMethodDecl *ArrayWithObjectsMethod;
818 /// \brief The declaration of the Objective-C NSDictionary class.
819 ObjCInterfaceDecl *NSDictionaryDecl;
821 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
822 ObjCMethodDecl *DictionaryWithObjectsMethod;
824 /// \brief id<NSCopying> type.
825 QualType QIDNSCopying;
827 /// \brief will hold 'respondsToSelector:'
828 Selector RespondsToSelectorSel;
830 /// A flag to remember whether the implicit forms of operator new and delete
831 /// have been declared.
832 bool GlobalNewDeleteDeclared;
834 /// A flag to indicate that we're in a context that permits abstract
835 /// references to fields. This is really a
836 bool AllowAbstractFieldReference;
838 /// \brief Describes how the expressions currently being parsed are
839 /// evaluated at run-time, if at all.
840 enum class ExpressionEvaluationContext {
841 /// \brief The current expression and its subexpressions occur within an
842 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
843 /// \c sizeof, where the type of the expression may be significant but
844 /// no code will be generated to evaluate the value of the expression at
848 /// \brief The current expression occurs within a braced-init-list within
849 /// an unevaluated operand. This is mostly like a regular unevaluated
850 /// context, except that we still instantiate constexpr functions that are
851 /// referenced here so that we can perform narrowing checks correctly.
854 /// \brief The current expression occurs within a discarded statement.
855 /// This behaves largely similarly to an unevaluated operand in preventing
856 /// definitions from being required, but not in other ways.
859 /// \brief The current expression occurs within an unevaluated
860 /// operand that unconditionally permits abstract references to
861 /// fields, such as a SIZE operator in MS-style inline assembly.
864 /// \brief The current context is "potentially evaluated" in C++11 terms,
865 /// but the expression is evaluated at compile-time (like the values of
866 /// cases in a switch statement).
869 /// \brief The current expression is potentially evaluated at run time,
870 /// which means that code may be generated to evaluate the value of the
871 /// expression at run time.
872 PotentiallyEvaluated,
874 /// \brief The current expression is potentially evaluated, but any
875 /// declarations referenced inside that expression are only used if
876 /// in fact the current expression is used.
878 /// This value is used when parsing default function arguments, for which
879 /// we would like to provide diagnostics (e.g., passing non-POD arguments
880 /// through varargs) but do not want to mark declarations as "referenced"
881 /// until the default argument is used.
882 PotentiallyEvaluatedIfUsed
885 /// \brief Data structure used to record current or nested
886 /// expression evaluation contexts.
887 struct ExpressionEvaluationContextRecord {
888 /// \brief The expression evaluation context.
889 ExpressionEvaluationContext Context;
891 /// \brief Whether the enclosing context needed a cleanup.
892 CleanupInfo ParentCleanup;
894 /// \brief Whether we are in a decltype expression.
897 /// \brief The number of active cleanup objects when we entered
898 /// this expression evaluation context.
899 unsigned NumCleanupObjects;
901 /// \brief The number of typos encountered during this expression evaluation
902 /// context (i.e. the number of TypoExprs created).
905 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
907 /// \brief The lambdas that are present within this context, if it
908 /// is indeed an unevaluated context.
909 SmallVector<LambdaExpr *, 2> Lambdas;
911 /// \brief The declaration that provides context for lambda expressions
912 /// and block literals if the normal declaration context does not
913 /// suffice, e.g., in a default function argument.
914 Decl *ManglingContextDecl;
916 /// \brief The context information used to mangle lambda expressions
917 /// and block literals within this context.
919 /// This mangling information is allocated lazily, since most contexts
920 /// do not have lambda expressions or block literals.
921 std::unique_ptr<MangleNumberingContext> MangleNumbering;
923 /// \brief If we are processing a decltype type, a set of call expressions
924 /// for which we have deferred checking the completeness of the return type.
925 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
927 /// \brief If we are processing a decltype type, a set of temporary binding
928 /// expressions for which we have deferred checking the destructor.
929 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
931 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
932 unsigned NumCleanupObjects,
933 CleanupInfo ParentCleanup,
934 Decl *ManglingContextDecl,
936 : Context(Context), ParentCleanup(ParentCleanup),
937 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
939 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
941 /// \brief Retrieve the mangling numbering context, used to consistently
942 /// number constructs like lambdas for mangling.
943 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
945 bool isUnevaluated() const {
946 return Context == ExpressionEvaluationContext::Unevaluated ||
947 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
948 Context == ExpressionEvaluationContext::UnevaluatedList;
950 bool isConstantEvaluated() const {
951 return Context == ExpressionEvaluationContext::ConstantEvaluated;
955 /// A stack of expression evaluation contexts.
956 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
958 /// \brief Compute the mangling number context for a lambda expression or
961 /// \param DC - The DeclContext containing the lambda expression or
963 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
964 /// associated with the context, if relevant.
965 MangleNumberingContext *getCurrentMangleNumberContext(
966 const DeclContext *DC,
967 Decl *&ManglingContextDecl);
970 /// SpecialMemberOverloadResult - The overloading result for a special member
973 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
974 /// integer are used to determine whether overload resolution succeeded.
975 class SpecialMemberOverloadResult {
984 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
987 SpecialMemberOverloadResult() : Pair() {}
988 SpecialMemberOverloadResult(CXXMethodDecl *MD)
989 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
991 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
992 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
994 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
995 void setKind(Kind K) { Pair.setInt(K); }
998 class SpecialMemberOverloadResultEntry
999 : public llvm::FastFoldingSetNode,
1000 public SpecialMemberOverloadResult {
1002 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1003 : FastFoldingSetNode(ID)
1007 /// \brief A cache of special member function overload resolution results
1008 /// for C++ records.
1009 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1011 /// \brief A cache of the flags available in enumerations with the flag_bits
1013 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1015 /// \brief The kind of translation unit we are processing.
1017 /// When we're processing a complete translation unit, Sema will perform
1018 /// end-of-translation-unit semantic tasks (such as creating
1019 /// initializers for tentative definitions in C) once parsing has
1020 /// completed. Modules and precompiled headers perform different kinds of
1022 TranslationUnitKind TUKind;
1024 llvm::BumpPtrAllocator BumpAlloc;
1026 /// \brief The number of SFINAE diagnostics that have been trapped.
1027 unsigned NumSFINAEErrors;
1029 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1030 UnparsedDefaultArgInstantiationsMap;
1032 /// \brief A mapping from parameters with unparsed default arguments to the
1033 /// set of instantiations of each parameter.
1035 /// This mapping is a temporary data structure used when parsing
1036 /// nested class templates or nested classes of class templates,
1037 /// where we might end up instantiating an inner class before the
1038 /// default arguments of its methods have been parsed.
1039 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1041 // Contains the locations of the beginning of unparsed default
1042 // argument locations.
1043 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1045 /// UndefinedInternals - all the used, undefined objects which require a
1046 /// definition in this translation unit.
1047 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1049 /// Obtain a sorted list of functions that are undefined but ODR-used.
1050 void getUndefinedButUsed(
1051 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1053 /// Retrieves list of suspicious delete-expressions that will be checked at
1054 /// the end of translation unit.
1055 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1056 getMismatchingDeleteExpressions() const;
1058 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1059 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1061 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1062 /// We need to maintain a list, since selectors can have differing signatures
1063 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1064 /// of selectors are "overloaded").
1065 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1066 /// methods inside categories with a particular selector.
1067 GlobalMethodPool MethodPool;
1069 /// Method selectors used in a \@selector expression. Used for implementation
1071 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1073 /// Kinds of C++ special members.
1074 enum CXXSpecialMember {
1075 CXXDefaultConstructor,
1084 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1086 /// The C++ special members which we are currently in the process of
1087 /// declaring. If this process recursively triggers the declaration of the
1088 /// same special member, we should act as if it is not yet declared.
1089 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1091 /// The function definitions which were renamed as part of typo-correction
1092 /// to match their respective declarations. We want to keep track of them
1093 /// to ensure that we don't emit a "redefinition" error if we encounter a
1094 /// correctly named definition after the renamed definition.
1095 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1097 /// Stack of types that correspond to the parameter entities that are
1098 /// currently being copy-initialized. Can be empty.
1099 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1101 void ReadMethodPool(Selector Sel);
1102 void updateOutOfDateSelector(Selector Sel);
1104 /// Private Helper predicate to check for 'self'.
1105 bool isSelfExpr(Expr *RExpr);
1106 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1108 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1109 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1110 /// should not be used elsewhere.
1111 void EmitCurrentDiagnostic(unsigned DiagID);
1113 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1115 class FPContractStateRAII {
1117 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1118 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1122 FPOptions OldFPFeaturesState;
1125 void addImplicitTypedef(StringRef Name, QualType T);
1128 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1129 TranslationUnitKind TUKind = TU_Complete,
1130 CodeCompleteConsumer *CompletionConsumer = nullptr);
1133 /// \brief Perform initialization that occurs after the parser has been
1134 /// initialized but before it parses anything.
1137 const LangOptions &getLangOpts() const { return LangOpts; }
1138 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1139 FPOptions &getFPOptions() { return FPFeatures; }
1141 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1142 SourceManager &getSourceManager() const { return SourceMgr; }
1143 Preprocessor &getPreprocessor() const { return PP; }
1144 ASTContext &getASTContext() const { return Context; }
1145 ASTConsumer &getASTConsumer() const { return Consumer; }
1146 ASTMutationListener *getASTMutationListener() const;
1147 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1149 ///\brief Registers an external source. If an external source already exists,
1150 /// creates a multiplex external source and appends to it.
1152 ///\param[in] E - A non-null external sema source.
1154 void addExternalSource(ExternalSemaSource *E);
1156 void PrintStats() const;
1158 /// \brief Helper class that creates diagnostics with optional
1159 /// template instantiation stacks.
1161 /// This class provides a wrapper around the basic DiagnosticBuilder
1162 /// class that emits diagnostics. SemaDiagnosticBuilder is
1163 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1164 /// does) and, if the diagnostic comes from inside a template
1165 /// instantiation, printing the template instantiation stack as
1167 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1172 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1173 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1175 // This is a cunning lie. DiagnosticBuilder actually performs move
1176 // construction in its copy constructor (but due to varied uses, it's not
1177 // possible to conveniently express this as actual move construction). So
1178 // the default copy ctor here is fine, because the base class disables the
1179 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1180 // in that case anwyay.
1181 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1183 ~SemaDiagnosticBuilder() {
1184 // If we aren't active, there is nothing to do.
1185 if (!isActive()) return;
1187 // Otherwise, we need to emit the diagnostic. First flush the underlying
1188 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1189 // won't emit the diagnostic in its own destructor.
1191 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1192 // do its own needless checks to see if the diagnostic needs to be
1193 // emitted. However, because we take care to ensure that the builder
1194 // objects never escape, a sufficiently smart compiler will be able to
1195 // eliminate that code.
1199 // Dispatch to Sema to emit the diagnostic.
1200 SemaRef.EmitCurrentDiagnostic(DiagID);
1203 /// Teach operator<< to produce an object of the correct type.
1204 template<typename T>
1205 friend const SemaDiagnosticBuilder &operator<<(
1206 const SemaDiagnosticBuilder &Diag, const T &Value) {
1207 const DiagnosticBuilder &BaseDiag = Diag;
1213 /// \brief Emit a diagnostic.
1214 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1215 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1216 return SemaDiagnosticBuilder(DB, *this, DiagID);
1219 /// \brief Emit a partial diagnostic.
1220 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1222 /// \brief Build a partial diagnostic.
1223 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1225 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1227 /// \brief Get a string to suggest for zero-initialization of a type.
1229 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1230 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1232 /// \brief Calls \c Lexer::getLocForEndOfToken()
1233 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1235 /// \brief Retrieve the module loader associated with the preprocessor.
1236 ModuleLoader &getModuleLoader() const;
1238 void emitAndClearUnusedLocalTypedefWarnings();
1240 void ActOnEndOfTranslationUnit();
1242 void CheckDelegatingCtorCycles();
1244 Scope *getScopeForContext(DeclContext *Ctx);
1246 void PushFunctionScope();
1247 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1248 sema::LambdaScopeInfo *PushLambdaScope();
1250 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1251 /// is during Parsing. Currently it is used to pass on the depth
1252 /// when parsing generic lambda 'auto' parameters.
1253 void RecordParsingTemplateParameterDepth(unsigned Depth);
1255 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1257 CapturedRegionKind K);
1259 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1260 const Decl *D = nullptr,
1261 const BlockExpr *blkExpr = nullptr);
1263 sema::FunctionScopeInfo *getCurFunction() const {
1264 return FunctionScopes.back();
1267 sema::FunctionScopeInfo *getEnclosingFunction() const {
1268 if (FunctionScopes.empty())
1271 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1272 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1274 return FunctionScopes[e];
1279 template <typename ExprT>
1280 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1281 if (!isUnevaluatedContext())
1282 getCurFunction()->recordUseOfWeak(E, IsRead);
1285 void PushCompoundScope();
1286 void PopCompoundScope();
1288 sema::CompoundScopeInfo &getCurCompoundScope() const;
1290 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1292 /// \brief Retrieve the current block, if any.
1293 sema::BlockScopeInfo *getCurBlock();
1295 /// Retrieve the current lambda scope info, if any.
1296 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1297 /// lambda scope info ignoring all inner capturing scopes that are not
1299 sema::LambdaScopeInfo *
1300 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1302 /// \brief Retrieve the current generic lambda info, if any.
1303 sema::LambdaScopeInfo *getCurGenericLambda();
1305 /// \brief Retrieve the current captured region, if any.
1306 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1308 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1309 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1311 void ActOnComment(SourceRange Comment);
1313 //===--------------------------------------------------------------------===//
1314 // Type Analysis / Processing: SemaType.cpp.
1317 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1318 const DeclSpec *DS = nullptr);
1319 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1320 const DeclSpec *DS = nullptr);
1321 QualType BuildPointerType(QualType T,
1322 SourceLocation Loc, DeclarationName Entity);
1323 QualType BuildReferenceType(QualType T, bool LValueRef,
1324 SourceLocation Loc, DeclarationName Entity);
1325 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1326 Expr *ArraySize, unsigned Quals,
1327 SourceRange Brackets, DeclarationName Entity);
1328 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1329 SourceLocation AttrLoc);
1331 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1333 /// \brief Build a function type.
1335 /// This routine checks the function type according to C++ rules and
1336 /// under the assumption that the result type and parameter types have
1337 /// just been instantiated from a template. It therefore duplicates
1338 /// some of the behavior of GetTypeForDeclarator, but in a much
1339 /// simpler form that is only suitable for this narrow use case.
1341 /// \param T The return type of the function.
1343 /// \param ParamTypes The parameter types of the function. This array
1344 /// will be modified to account for adjustments to the types of the
1345 /// function parameters.
1347 /// \param Loc The location of the entity whose type involves this
1348 /// function type or, if there is no such entity, the location of the
1349 /// type that will have function type.
1351 /// \param Entity The name of the entity that involves the function
1354 /// \param EPI Extra information about the function type. Usually this will
1355 /// be taken from an existing function with the same prototype.
1357 /// \returns A suitable function type, if there are no errors. The
1358 /// unqualified type will always be a FunctionProtoType.
1359 /// Otherwise, returns a NULL type.
1360 QualType BuildFunctionType(QualType T,
1361 MutableArrayRef<QualType> ParamTypes,
1362 SourceLocation Loc, DeclarationName Entity,
1363 const FunctionProtoType::ExtProtoInfo &EPI);
1365 QualType BuildMemberPointerType(QualType T, QualType Class,
1367 DeclarationName Entity);
1368 QualType BuildBlockPointerType(QualType T,
1369 SourceLocation Loc, DeclarationName Entity);
1370 QualType BuildParenType(QualType T);
1371 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1372 QualType BuildReadPipeType(QualType T,
1373 SourceLocation Loc);
1374 QualType BuildWritePipeType(QualType T,
1375 SourceLocation Loc);
1377 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1378 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1379 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1380 TypeSourceInfo *ReturnTypeInfo);
1382 /// \brief Package the given type and TSI into a ParsedType.
1383 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1384 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1385 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1386 static QualType GetTypeFromParser(ParsedType Ty,
1387 TypeSourceInfo **TInfo = nullptr);
1388 CanThrowResult canThrow(const Expr *E);
1389 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1390 const FunctionProtoType *FPT);
1391 void UpdateExceptionSpec(FunctionDecl *FD,
1392 const FunctionProtoType::ExceptionSpecInfo &ESI);
1393 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1394 bool CheckDistantExceptionSpec(QualType T);
1395 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1396 bool CheckEquivalentExceptionSpec(
1397 const FunctionProtoType *Old, SourceLocation OldLoc,
1398 const FunctionProtoType *New, SourceLocation NewLoc);
1399 bool CheckEquivalentExceptionSpec(
1400 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1401 const FunctionProtoType *Old, SourceLocation OldLoc,
1402 const FunctionProtoType *New, SourceLocation NewLoc);
1403 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1404 const PartialDiagnostic &NestedDiagID,
1405 const PartialDiagnostic &NoteID,
1406 const FunctionProtoType *Superset,
1407 SourceLocation SuperLoc,
1408 const FunctionProtoType *Subset,
1409 SourceLocation SubLoc);
1410 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1411 const PartialDiagnostic &NoteID,
1412 const FunctionProtoType *Target,
1413 SourceLocation TargetLoc,
1414 const FunctionProtoType *Source,
1415 SourceLocation SourceLoc);
1417 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1419 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1420 /// in an Objective-C message declaration. Return the appropriate type.
1421 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1423 /// \brief Abstract class used to diagnose incomplete types.
1424 struct TypeDiagnoser {
1427 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1428 virtual ~TypeDiagnoser() {}
1431 static int getPrintable(int I) { return I; }
1432 static unsigned getPrintable(unsigned I) { return I; }
1433 static bool getPrintable(bool B) { return B; }
1434 static const char * getPrintable(const char *S) { return S; }
1435 static StringRef getPrintable(StringRef S) { return S; }
1436 static const std::string &getPrintable(const std::string &S) { return S; }
1437 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1440 static DeclarationName getPrintable(DeclarationName N) { return N; }
1441 static QualType getPrintable(QualType T) { return T; }
1442 static SourceRange getPrintable(SourceRange R) { return R; }
1443 static SourceRange getPrintable(SourceLocation L) { return L; }
1444 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1445 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1447 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1449 std::tuple<const Ts &...> Args;
1451 template <std::size_t... Is>
1452 void emit(const SemaDiagnosticBuilder &DB,
1453 llvm::index_sequence<Is...>) const {
1454 // Apply all tuple elements to the builder in order.
1455 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1460 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1461 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1462 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1465 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1466 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1467 emit(DB, llvm::index_sequence_for<Ts...>());
1473 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1474 TypeDiagnoser *Diagnoser);
1476 struct ModuleScope {
1477 clang::Module *Module;
1478 VisibleModuleSet OuterVisibleModules;
1480 /// The modules we're currently parsing.
1481 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1483 /// Get the module whose scope we are currently within.
1484 Module *getCurrentModule() const {
1485 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1488 VisibleModuleSet VisibleModules;
1491 /// \brief Get the module owning an entity.
1492 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1494 /// \brief Make a merged definition of an existing hidden definition \p ND
1495 /// visible at the specified location.
1496 void makeMergedDefinitionVisible(NamedDecl *ND);
1498 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1500 /// Determine whether a declaration is visible to name lookup.
1501 bool isVisible(const NamedDecl *D) {
1502 return !D->isHidden() || isVisibleSlow(D);
1505 /// Determine whether any declaration of an entity is visible.
1507 hasVisibleDeclaration(const NamedDecl *D,
1508 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1509 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1511 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1512 llvm::SmallVectorImpl<Module *> *Modules);
1514 bool hasVisibleMergedDefinition(NamedDecl *Def);
1516 /// Determine if \p D has a visible definition. If not, suggest a declaration
1517 /// that should be made visible to expose the definition.
1518 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1519 bool OnlyNeedComplete = false);
1520 bool hasVisibleDefinition(const NamedDecl *D) {
1522 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1525 /// Determine if the template parameter \p D has a visible default argument.
1527 hasVisibleDefaultArgument(const NamedDecl *D,
1528 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1530 /// Determine if there is a visible declaration of \p D that is an explicit
1531 /// specialization declaration for a specialization of a template. (For a
1532 /// member specialization, use hasVisibleMemberSpecialization.)
1533 bool hasVisibleExplicitSpecialization(
1534 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1536 /// Determine if there is a visible declaration of \p D that is a member
1537 /// specialization declaration (as opposed to an instantiated declaration).
1538 bool hasVisibleMemberSpecialization(
1539 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1541 /// Determine if \p A and \p B are equivalent internal linkage declarations
1542 /// from different modules, and thus an ambiguity error can be downgraded to
1543 /// an extension warning.
1544 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1545 const NamedDecl *B);
1546 void diagnoseEquivalentInternalLinkageDeclarations(
1547 SourceLocation Loc, const NamedDecl *D,
1548 ArrayRef<const NamedDecl *> Equiv);
1550 bool isCompleteType(SourceLocation Loc, QualType T) {
1551 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1553 bool RequireCompleteType(SourceLocation Loc, QualType T,
1554 TypeDiagnoser &Diagnoser);
1555 bool RequireCompleteType(SourceLocation Loc, QualType T,
1558 template <typename... Ts>
1559 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1560 const Ts &...Args) {
1561 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1562 return RequireCompleteType(Loc, T, Diagnoser);
1565 void completeExprArrayBound(Expr *E);
1566 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1567 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1569 template <typename... Ts>
1570 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1571 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1572 return RequireCompleteExprType(E, Diagnoser);
1575 bool RequireLiteralType(SourceLocation Loc, QualType T,
1576 TypeDiagnoser &Diagnoser);
1577 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1579 template <typename... Ts>
1580 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1581 const Ts &...Args) {
1582 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1583 return RequireLiteralType(Loc, T, Diagnoser);
1586 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1587 const CXXScopeSpec &SS, QualType T);
1589 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1590 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1591 /// context, such as when building a type for decltype(auto).
1592 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1593 bool AsUnevaluated = true);
1594 QualType BuildUnaryTransformType(QualType BaseType,
1595 UnaryTransformType::UTTKind UKind,
1596 SourceLocation Loc);
1598 //===--------------------------------------------------------------------===//
1599 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1602 struct SkipBodyInfo {
1603 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1605 NamedDecl *Previous;
1608 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1610 void DiagnoseUseOfUnimplementedSelectors();
1612 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1614 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1615 Scope *S, CXXScopeSpec *SS = nullptr,
1616 bool isClassName = false, bool HasTrailingDot = false,
1617 ParsedType ObjectType = nullptr,
1618 bool IsCtorOrDtorName = false,
1619 bool WantNontrivialTypeSourceInfo = false,
1620 bool IsClassTemplateDeductionContext = true,
1621 IdentifierInfo **CorrectedII = nullptr);
1622 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1623 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1624 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1625 SourceLocation IILoc,
1628 ParsedType &SuggestedType,
1629 bool IsTemplateName = false);
1631 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1632 /// type name has failed in a dependent context. In these situations, we
1633 /// automatically form a DependentTypeName that will retry lookup in a related
1634 /// scope during instantiation.
1635 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1636 SourceLocation NameLoc,
1637 bool IsTemplateTypeArg);
1639 /// \brief Describes the result of the name lookup and resolution performed
1640 /// by \c ClassifyName().
1641 enum NameClassificationKind {
1647 NC_NestedNameSpecifier,
1653 class NameClassification {
1654 NameClassificationKind Kind;
1656 TemplateName Template;
1658 const IdentifierInfo *Keyword;
1660 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1663 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1665 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1667 NameClassification(const IdentifierInfo *Keyword)
1668 : Kind(NC_Keyword), Keyword(Keyword) { }
1670 static NameClassification Error() {
1671 return NameClassification(NC_Error);
1674 static NameClassification Unknown() {
1675 return NameClassification(NC_Unknown);
1678 static NameClassification NestedNameSpecifier() {
1679 return NameClassification(NC_NestedNameSpecifier);
1682 static NameClassification TypeTemplate(TemplateName Name) {
1683 NameClassification Result(NC_TypeTemplate);
1684 Result.Template = Name;
1688 static NameClassification VarTemplate(TemplateName Name) {
1689 NameClassification Result(NC_VarTemplate);
1690 Result.Template = Name;
1694 static NameClassification FunctionTemplate(TemplateName Name) {
1695 NameClassification Result(NC_FunctionTemplate);
1696 Result.Template = Name;
1700 NameClassificationKind getKind() const { return Kind; }
1702 ParsedType getType() const {
1703 assert(Kind == NC_Type);
1707 ExprResult getExpression() const {
1708 assert(Kind == NC_Expression);
1712 TemplateName getTemplateName() const {
1713 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1714 Kind == NC_VarTemplate);
1718 TemplateNameKind getTemplateNameKind() const {
1720 case NC_TypeTemplate:
1721 return TNK_Type_template;
1722 case NC_FunctionTemplate:
1723 return TNK_Function_template;
1724 case NC_VarTemplate:
1725 return TNK_Var_template;
1727 llvm_unreachable("unsupported name classification.");
1732 /// \brief Perform name lookup on the given name, classifying it based on
1733 /// the results of name lookup and the following token.
1735 /// This routine is used by the parser to resolve identifiers and help direct
1736 /// parsing. When the identifier cannot be found, this routine will attempt
1737 /// to correct the typo and classify based on the resulting name.
1739 /// \param S The scope in which we're performing name lookup.
1741 /// \param SS The nested-name-specifier that precedes the name.
1743 /// \param Name The identifier. If typo correction finds an alternative name,
1744 /// this pointer parameter will be updated accordingly.
1746 /// \param NameLoc The location of the identifier.
1748 /// \param NextToken The token following the identifier. Used to help
1749 /// disambiguate the name.
1751 /// \param IsAddressOfOperand True if this name is the operand of a unary
1752 /// address of ('&') expression, assuming it is classified as an
1755 /// \param CCC The correction callback, if typo correction is desired.
1757 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1758 SourceLocation NameLoc, const Token &NextToken,
1759 bool IsAddressOfOperand,
1760 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1762 /// Describes the detailed kind of a template name. Used in diagnostics.
1763 enum class TemplateNameKindForDiagnostics {
1768 TemplateTemplateParam,
1771 TemplateNameKindForDiagnostics
1772 getTemplateNameKindForDiagnostics(TemplateName Name);
1774 /// Determine whether it's plausible that E was intended to be a
1776 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1777 if (!getLangOpts().CPlusPlus || E.isInvalid())
1779 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1780 return !DRE->hasExplicitTemplateArgs();
1781 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1782 return !ME->hasExplicitTemplateArgs();
1783 // Any additional cases recognized here should also be handled by
1784 // diagnoseExprIntendedAsTemplateName.
1787 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1788 SourceLocation Less,
1789 SourceLocation Greater);
1791 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1793 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1794 MultiTemplateParamsArg TemplateParameterLists);
1795 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1796 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1797 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1798 DeclarationName Name,
1799 SourceLocation Loc);
1801 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1802 SourceLocation FallbackLoc,
1803 SourceLocation ConstQualLoc = SourceLocation(),
1804 SourceLocation VolatileQualLoc = SourceLocation(),
1805 SourceLocation RestrictQualLoc = SourceLocation(),
1806 SourceLocation AtomicQualLoc = SourceLocation(),
1807 SourceLocation UnalignedQualLoc = SourceLocation());
1809 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1810 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1811 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1812 const LookupResult &R);
1813 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1814 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1815 const LookupResult &R);
1816 void CheckShadow(Scope *S, VarDecl *D);
1818 /// Warn if 'E', which is an expression that is about to be modified, refers
1819 /// to a shadowing declaration.
1820 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1822 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1825 /// Map of current shadowing declarations to shadowed declarations. Warn if
1826 /// it looks like the user is trying to modify the shadowing declaration.
1827 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1830 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1831 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1832 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1833 TypedefNameDecl *NewTD);
1834 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1835 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1836 TypeSourceInfo *TInfo,
1837 LookupResult &Previous);
1838 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1839 LookupResult &Previous, bool &Redeclaration);
1840 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1841 TypeSourceInfo *TInfo,
1842 LookupResult &Previous,
1843 MultiTemplateParamsArg TemplateParamLists,
1845 ArrayRef<BindingDecl *> Bindings = None);
1847 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1848 MultiTemplateParamsArg TemplateParamLists);
1849 // Returns true if the variable declaration is a redeclaration
1850 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1851 void CheckVariableDeclarationType(VarDecl *NewVD);
1852 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1854 void CheckCompleteVariableDeclaration(VarDecl *VD);
1855 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1856 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1858 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1859 TypeSourceInfo *TInfo,
1860 LookupResult &Previous,
1861 MultiTemplateParamsArg TemplateParamLists,
1863 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1865 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1866 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1868 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1869 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1870 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1871 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1872 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1873 // Returns true if the function declaration is a redeclaration
1874 bool CheckFunctionDeclaration(Scope *S,
1875 FunctionDecl *NewFD, LookupResult &Previous,
1876 bool IsMemberSpecialization);
1877 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1878 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1879 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1880 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1881 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1884 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1885 SourceLocation NameLoc, IdentifierInfo *Name,
1886 QualType T, TypeSourceInfo *TSInfo,
1888 void ActOnParamDefaultArgument(Decl *param,
1889 SourceLocation EqualLoc,
1891 void ActOnParamUnparsedDefaultArgument(Decl *param,
1892 SourceLocation EqualLoc,
1893 SourceLocation ArgLoc);
1894 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1895 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1896 SourceLocation EqualLoc);
1898 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1899 void ActOnUninitializedDecl(Decl *dcl);
1900 void ActOnInitializerError(Decl *Dcl);
1902 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1903 void ActOnCXXForRangeDecl(Decl *D);
1904 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1905 IdentifierInfo *Ident,
1906 ParsedAttributes &Attrs,
1907 SourceLocation AttrEnd);
1908 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1909 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1910 void FinalizeDeclaration(Decl *D);
1911 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1912 ArrayRef<Decl *> Group);
1913 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1915 /// Should be called on all declarations that might have attached
1916 /// documentation comments.
1917 void ActOnDocumentableDecl(Decl *D);
1918 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1920 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1921 SourceLocation LocAfterDecls);
1922 void CheckForFunctionRedefinition(
1923 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1924 SkipBodyInfo *SkipBody = nullptr);
1925 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1926 MultiTemplateParamsArg TemplateParamLists,
1927 SkipBodyInfo *SkipBody = nullptr);
1928 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1929 SkipBodyInfo *SkipBody = nullptr);
1930 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1931 bool isObjCMethodDecl(Decl *D) {
1932 return D && isa<ObjCMethodDecl>(D);
1935 /// \brief Determine whether we can delay parsing the body of a function or
1936 /// function template until it is used, assuming we don't care about emitting
1937 /// code for that function.
1939 /// This will be \c false if we may need the body of the function in the
1940 /// middle of parsing an expression (where it's impractical to switch to
1941 /// parsing a different function), for instance, if it's constexpr in C++11
1942 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1943 bool canDelayFunctionBody(const Declarator &D);
1945 /// \brief Determine whether we can skip parsing the body of a function
1946 /// definition, assuming we don't care about analyzing its body or emitting
1947 /// code for that function.
1949 /// This will be \c false only if we may need the body of the function in
1950 /// order to parse the rest of the program (for instance, if it is
1951 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1952 bool canSkipFunctionBody(Decl *D);
1954 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1955 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1956 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1957 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1958 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1960 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1961 /// attribute for which parsing is delayed.
1962 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1964 /// \brief Diagnose any unused parameters in the given sequence of
1965 /// ParmVarDecl pointers.
1966 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1968 /// \brief Diagnose whether the size of parameters or return value of a
1969 /// function or obj-c method definition is pass-by-value and larger than a
1970 /// specified threshold.
1972 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1973 QualType ReturnTy, NamedDecl *D);
1975 void DiagnoseInvalidJumps(Stmt *Body);
1976 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1977 SourceLocation AsmLoc,
1978 SourceLocation RParenLoc);
1980 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1981 Decl *ActOnEmptyDeclaration(Scope *S,
1982 AttributeList *AttrList,
1983 SourceLocation SemiLoc);
1985 enum class ModuleDeclKind {
1986 Module, ///< 'module X;'
1987 Partition, ///< 'module partition X;'
1988 Implementation, ///< 'module implementation X;'
1991 /// The parser has processed a module-declaration that begins the definition
1992 /// of a module interface or implementation.
1993 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
1994 SourceLocation ModuleLoc, ModuleDeclKind MDK,
1997 /// \brief The parser has processed a module import declaration.
1999 /// \param AtLoc The location of the '@' symbol, if any.
2001 /// \param ImportLoc The location of the 'import' keyword.
2003 /// \param Path The module access path.
2004 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2007 /// \brief The parser has processed a module import translated from a
2008 /// #include or similar preprocessing directive.
2009 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2010 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2012 /// \brief The parsed has entered a submodule.
2013 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2014 /// \brief The parser has left a submodule.
2015 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2017 /// \brief Create an implicit import of the given module at the given
2018 /// source location, for error recovery, if possible.
2020 /// This routine is typically used when an entity found by name lookup
2021 /// is actually hidden within a module that we know about but the user
2022 /// has forgotten to import.
2023 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2026 /// Kinds of missing import. Note, the values of these enumerators correspond
2027 /// to %select values in diagnostics.
2028 enum class MissingImportKind {
2032 ExplicitSpecialization,
2033 PartialSpecialization
2036 /// \brief Diagnose that the specified declaration needs to be visible but
2037 /// isn't, and suggest a module import that would resolve the problem.
2038 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2039 MissingImportKind MIK, bool Recover = true);
2040 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2041 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2042 MissingImportKind MIK, bool Recover);
2044 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2045 SourceLocation LBraceLoc);
2046 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2047 SourceLocation RBraceLoc);
2049 /// \brief We've found a use of a templated declaration that would trigger an
2050 /// implicit instantiation. Check that any relevant explicit specializations
2051 /// and partial specializations are visible, and diagnose if not.
2052 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2054 /// \brief We've found a use of a template specialization that would select a
2055 /// partial specialization. Check that the partial specialization is visible,
2056 /// and diagnose if not.
2057 void checkPartialSpecializationVisibility(SourceLocation Loc,
2060 /// \brief Retrieve a suitable printing policy.
2061 PrintingPolicy getPrintingPolicy() const {
2062 return getPrintingPolicy(Context, PP);
2065 /// \brief Retrieve a suitable printing policy.
2066 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2067 const Preprocessor &PP);
2070 void ActOnPopScope(SourceLocation Loc, Scope *S);
2071 void ActOnTranslationUnitScope(Scope *S);
2073 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2074 RecordDecl *&AnonRecord);
2075 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2076 MultiTemplateParamsArg TemplateParams,
2077 bool IsExplicitInstantiation,
2078 RecordDecl *&AnonRecord);
2080 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2083 const PrintingPolicy &Policy);
2085 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2086 RecordDecl *Record);
2088 /// Common ways to introduce type names without a tag for use in diagnostics.
2089 /// Keep in sync with err_tag_reference_non_tag.
2098 NTK_TypeAliasTemplate,
2099 NTK_TemplateTemplateArgument,
2102 /// Given a non-tag type declaration, returns an enum useful for indicating
2103 /// what kind of non-tag type this is.
2104 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2106 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2107 TagTypeKind NewTag, bool isDefinition,
2108 SourceLocation NewTagLoc,
2109 const IdentifierInfo *Name);
2112 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2113 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2114 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2115 TUK_Friend // Friend declaration: 'friend struct foo;'
2118 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2119 SourceLocation KWLoc, CXXScopeSpec &SS,
2120 IdentifierInfo *Name, SourceLocation NameLoc,
2121 AttributeList *Attr, AccessSpecifier AS,
2122 SourceLocation ModulePrivateLoc,
2123 MultiTemplateParamsArg TemplateParameterLists,
2124 bool &OwnedDecl, bool &IsDependent,
2125 SourceLocation ScopedEnumKWLoc,
2126 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2127 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2129 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2130 unsigned TagSpec, SourceLocation TagLoc,
2132 IdentifierInfo *Name, SourceLocation NameLoc,
2133 AttributeList *Attr,
2134 MultiTemplateParamsArg TempParamLists);
2136 TypeResult ActOnDependentTag(Scope *S,
2139 const CXXScopeSpec &SS,
2140 IdentifierInfo *Name,
2141 SourceLocation TagLoc,
2142 SourceLocation NameLoc);
2144 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2145 IdentifierInfo *ClassName,
2146 SmallVectorImpl<Decl *> &Decls);
2147 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2148 Declarator &D, Expr *BitfieldWidth);
2150 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2151 Declarator &D, Expr *BitfieldWidth,
2152 InClassInitStyle InitStyle,
2153 AccessSpecifier AS);
2154 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2155 SourceLocation DeclStart,
2156 Declarator &D, Expr *BitfieldWidth,
2157 InClassInitStyle InitStyle,
2159 AttributeList *MSPropertyAttr);
2161 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2162 TypeSourceInfo *TInfo,
2163 RecordDecl *Record, SourceLocation Loc,
2164 bool Mutable, Expr *BitfieldWidth,
2165 InClassInitStyle InitStyle,
2166 SourceLocation TSSL,
2167 AccessSpecifier AS, NamedDecl *PrevDecl,
2168 Declarator *D = nullptr);
2170 bool CheckNontrivialField(FieldDecl *FD);
2171 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2172 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2173 bool Diagnose = false);
2174 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2175 void ActOnLastBitfield(SourceLocation DeclStart,
2176 SmallVectorImpl<Decl *> &AllIvarDecls);
2177 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2178 Declarator &D, Expr *BitfieldWidth,
2179 tok::ObjCKeywordKind visibility);
2181 // This is used for both record definitions and ObjC interface declarations.
2182 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2183 ArrayRef<Decl *> Fields,
2184 SourceLocation LBrac, SourceLocation RBrac,
2185 AttributeList *AttrList);
2187 /// ActOnTagStartDefinition - Invoked when we have entered the
2188 /// scope of a tag's definition (e.g., for an enumeration, class,
2189 /// struct, or union).
2190 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2192 typedef void *SkippedDefinitionContext;
2194 /// \brief Invoked when we enter a tag definition that we're skipping.
2195 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2197 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2199 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2200 /// C++ record definition's base-specifiers clause and are starting its
2201 /// member declarations.
2202 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2203 SourceLocation FinalLoc,
2204 bool IsFinalSpelledSealed,
2205 SourceLocation LBraceLoc);
2207 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2208 /// the definition of a tag (enumeration, class, struct, or union).
2209 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2210 SourceRange BraceRange);
2212 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2214 void ActOnObjCContainerFinishDefinition();
2216 /// \brief Invoked when we must temporarily exit the objective-c container
2217 /// scope for parsing/looking-up C constructs.
2219 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2220 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2221 void ActOnObjCReenterContainerContext(DeclContext *DC);
2223 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2224 /// error parsing the definition of a tag.
2225 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2227 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2228 EnumConstantDecl *LastEnumConst,
2229 SourceLocation IdLoc,
2232 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2233 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2234 QualType EnumUnderlyingTy,
2235 bool EnumUnderlyingIsImplicit,
2236 const EnumDecl *Prev);
2238 /// Determine whether the body of an anonymous enumeration should be skipped.
2239 /// \param II The name of the first enumerator.
2240 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2241 SourceLocation IILoc);
2243 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2244 SourceLocation IdLoc, IdentifierInfo *Id,
2245 AttributeList *Attrs,
2246 SourceLocation EqualLoc, Expr *Val);
2247 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2249 ArrayRef<Decl *> Elements,
2250 Scope *S, AttributeList *Attr);
2252 DeclContext *getContainingDC(DeclContext *DC);
2254 /// Set the current declaration context until it gets popped.
2255 void PushDeclContext(Scope *S, DeclContext *DC);
2256 void PopDeclContext();
2258 /// EnterDeclaratorContext - Used when we must lookup names in the context
2259 /// of a declarator's nested name specifier.
2260 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2261 void ExitDeclaratorContext(Scope *S);
2263 /// Push the parameters of D, which must be a function, into scope.
2264 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2265 void ActOnExitFunctionContext();
2267 DeclContext *getFunctionLevelDeclContext();
2269 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2270 /// to the function decl for the function being parsed. If we're currently
2271 /// in a 'block', this returns the containing context.
2272 FunctionDecl *getCurFunctionDecl();
2274 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2275 /// the method decl for the method being parsed. If we're currently
2276 /// in a 'block', this returns the containing context.
2277 ObjCMethodDecl *getCurMethodDecl();
2279 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2280 /// or C function we're in, otherwise return null. If we're currently
2281 /// in a 'block', this returns the containing context.
2282 NamedDecl *getCurFunctionOrMethodDecl();
2284 /// Add this decl to the scope shadowed decl chains.
2285 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2287 /// \brief Make the given externally-produced declaration visible at the
2288 /// top level scope.
2290 /// \param D The externally-produced declaration to push.
2292 /// \param Name The name of the externally-produced declaration.
2293 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2295 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2296 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2297 /// true if 'D' belongs to the given declaration context.
2299 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2300 /// enclosing namespace set of the context, rather than contained
2301 /// directly within it.
2302 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2303 bool AllowInlineNamespace = false);
2305 /// Finds the scope corresponding to the given decl context, if it
2306 /// happens to be an enclosing scope. Otherwise return NULL.
2307 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2309 /// Subroutines of ActOnDeclarator().
2310 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2311 TypeSourceInfo *TInfo);
2312 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2314 /// \brief Describes the kind of merge to perform for availability
2315 /// attributes (including "deprecated", "unavailable", and "availability").
2316 enum AvailabilityMergeKind {
2317 /// \brief Don't merge availability attributes at all.
2319 /// \brief Merge availability attributes for a redeclaration, which requires
2322 /// \brief Merge availability attributes for an override, which requires
2323 /// an exact match or a weakening of constraints.
2325 /// \brief Merge availability attributes for an implementation of
2326 /// a protocol requirement.
2327 AMK_ProtocolImplementation,
2330 /// Attribute merging methods. Return true if a new attribute was added.
2331 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2332 IdentifierInfo *Platform,
2334 VersionTuple Introduced,
2335 VersionTuple Deprecated,
2336 VersionTuple Obsoleted,
2339 bool IsStrict, StringRef Replacement,
2340 AvailabilityMergeKind AMK,
2341 unsigned AttrSpellingListIndex);
2342 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2343 TypeVisibilityAttr::VisibilityType Vis,
2344 unsigned AttrSpellingListIndex);
2345 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2346 VisibilityAttr::VisibilityType Vis,
2347 unsigned AttrSpellingListIndex);
2348 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2349 unsigned AttrSpellingListIndex, StringRef Uuid);
2350 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2351 unsigned AttrSpellingListIndex);
2352 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2353 unsigned AttrSpellingListIndex);
2355 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2356 unsigned AttrSpellingListIndex,
2357 MSInheritanceAttr::Spelling SemanticSpelling);
2358 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2359 IdentifierInfo *Format, int FormatIdx,
2360 int FirstArg, unsigned AttrSpellingListIndex);
2361 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2362 unsigned AttrSpellingListIndex);
2363 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2364 IdentifierInfo *Ident,
2365 unsigned AttrSpellingListIndex);
2366 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2367 unsigned AttrSpellingListIndex);
2368 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2369 unsigned AttrSpellingListIndex);
2370 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2371 IdentifierInfo *Ident,
2372 unsigned AttrSpellingListIndex);
2373 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2374 unsigned AttrSpellingListIndex);
2376 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2377 AvailabilityMergeKind AMK = AMK_Redeclaration);
2378 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2379 LookupResult &OldDecls);
2380 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2381 bool MergeTypeWithOld);
2382 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2383 Scope *S, bool MergeTypeWithOld);
2384 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2385 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2386 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2387 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2388 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2389 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2390 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2392 // AssignmentAction - This is used by all the assignment diagnostic functions
2393 // to represent what is actually causing the operation
2394 enum AssignmentAction {
2402 AA_Passing_CFAudited
2405 /// C++ Overloading.
2407 /// This is a legitimate overload: the existing declarations are
2408 /// functions or function templates with different signatures.
2411 /// This is not an overload because the signature exactly matches
2412 /// an existing declaration.
2415 /// This is not an overload because the lookup results contain a
2419 OverloadKind CheckOverload(Scope *S,
2421 const LookupResult &OldDecls,
2422 NamedDecl *&OldDecl,
2423 bool IsForUsingDecl);
2424 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2425 bool ConsiderCudaAttrs = true);
2427 /// \brief Checks availability of the function depending on the current
2428 /// function context.Inside an unavailable function,unavailability is ignored.
2430 /// \returns true if \p FD is unavailable and current context is inside
2431 /// an available function, false otherwise.
2432 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2434 ImplicitConversionSequence
2435 TryImplicitConversion(Expr *From, QualType ToType,
2436 bool SuppressUserConversions,
2438 bool InOverloadResolution,
2440 bool AllowObjCWritebackConversion);
2442 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2443 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2444 bool IsComplexPromotion(QualType FromType, QualType ToType);
2445 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2446 bool InOverloadResolution,
2447 QualType& ConvertedType, bool &IncompatibleObjC);
2448 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2449 QualType& ConvertedType, bool &IncompatibleObjC);
2450 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2451 QualType &ConvertedType);
2452 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2453 QualType& ConvertedType);
2454 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2455 const FunctionProtoType *NewType,
2456 unsigned *ArgPos = nullptr);
2457 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2458 QualType FromType, QualType ToType);
2460 void maybeExtendBlockObject(ExprResult &E);
2461 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2462 bool CheckPointerConversion(Expr *From, QualType ToType,
2464 CXXCastPath& BasePath,
2465 bool IgnoreBaseAccess,
2466 bool Diagnose = true);
2467 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2468 bool InOverloadResolution,
2469 QualType &ConvertedType);
2470 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2472 CXXCastPath &BasePath,
2473 bool IgnoreBaseAccess);
2474 bool IsQualificationConversion(QualType FromType, QualType ToType,
2475 bool CStyle, bool &ObjCLifetimeConversion);
2476 bool IsFunctionConversion(QualType FromType, QualType ToType,
2477 QualType &ResultTy);
2478 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2479 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2481 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2482 const VarDecl *NRVOCandidate,
2483 QualType ResultType,
2485 bool AllowNRVO = true);
2487 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2489 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2490 SourceLocation EqualLoc,
2492 bool TopLevelOfInitList = false,
2493 bool AllowExplicit = false);
2494 ExprResult PerformObjectArgumentInitialization(Expr *From,
2495 NestedNameSpecifier *Qualifier,
2496 NamedDecl *FoundDecl,
2497 CXXMethodDecl *Method);
2499 ExprResult PerformContextuallyConvertToBool(Expr *From);
2500 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2502 /// Contexts in which a converted constant expression is required.
2504 CCEK_CaseValue, ///< Expression in a case label.
2505 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2506 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2507 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2508 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2510 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2511 llvm::APSInt &Value, CCEKind CCE);
2512 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2513 APValue &Value, CCEKind CCE);
2515 /// \brief Abstract base class used to perform a contextual implicit
2516 /// conversion from an expression to any type passing a filter.
2517 class ContextualImplicitConverter {
2520 bool SuppressConversion;
2522 ContextualImplicitConverter(bool Suppress = false,
2523 bool SuppressConversion = false)
2524 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2526 /// \brief Determine whether the specified type is a valid destination type
2527 /// for this conversion.
2528 virtual bool match(QualType T) = 0;
2530 /// \brief Emits a diagnostic complaining that the expression does not have
2531 /// integral or enumeration type.
2532 virtual SemaDiagnosticBuilder
2533 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2535 /// \brief Emits a diagnostic when the expression has incomplete class type.
2536 virtual SemaDiagnosticBuilder
2537 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2539 /// \brief Emits a diagnostic when the only matching conversion function
2541 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2542 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2544 /// \brief Emits a note for the explicit conversion function.
2545 virtual SemaDiagnosticBuilder
2546 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2548 /// \brief Emits a diagnostic when there are multiple possible conversion
2550 virtual SemaDiagnosticBuilder
2551 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2553 /// \brief Emits a note for one of the candidate conversions.
2554 virtual SemaDiagnosticBuilder
2555 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2557 /// \brief Emits a diagnostic when we picked a conversion function
2558 /// (for cases when we are not allowed to pick a conversion function).
2559 virtual SemaDiagnosticBuilder diagnoseConversion(
2560 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2562 virtual ~ContextualImplicitConverter() {}
2565 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2566 bool AllowScopedEnumerations;
2569 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2570 bool Suppress, bool SuppressConversion)
2571 : ContextualImplicitConverter(Suppress, SuppressConversion),
2572 AllowScopedEnumerations(AllowScopedEnumerations) {}
2574 /// Match an integral or (possibly scoped) enumeration type.
2575 bool match(QualType T) override;
2577 SemaDiagnosticBuilder
2578 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2579 return diagnoseNotInt(S, Loc, T);
2582 /// \brief Emits a diagnostic complaining that the expression does not have
2583 /// integral or enumeration type.
2584 virtual SemaDiagnosticBuilder
2585 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2588 /// Perform a contextual implicit conversion.
2589 ExprResult PerformContextualImplicitConversion(
2590 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2593 enum ObjCSubscriptKind {
2598 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2600 // Note that LK_String is intentionally after the other literals, as
2601 // this is used for diagnostics logic.
2602 enum ObjCLiteralKind {
2611 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2613 ExprResult PerformObjectMemberConversion(Expr *From,
2614 NestedNameSpecifier *Qualifier,
2615 NamedDecl *FoundDecl,
2618 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2619 // TODO: make this is a typesafe union.
2620 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2621 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2623 void AddOverloadCandidate(FunctionDecl *Function,
2624 DeclAccessPair FoundDecl,
2625 ArrayRef<Expr *> Args,
2626 OverloadCandidateSet &CandidateSet,
2627 bool SuppressUserConversions = false,
2628 bool PartialOverloading = false,
2629 bool AllowExplicit = false,
2630 ConversionSequenceList EarlyConversions = None);
2631 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2632 ArrayRef<Expr *> Args,
2633 OverloadCandidateSet &CandidateSet,
2634 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2635 bool SuppressUserConversions = false,
2636 bool PartialOverloading = false);
2637 void AddMethodCandidate(DeclAccessPair FoundDecl,
2638 QualType ObjectType,
2639 Expr::Classification ObjectClassification,
2640 ArrayRef<Expr *> Args,
2641 OverloadCandidateSet& CandidateSet,
2642 bool SuppressUserConversion = false);
2643 void AddMethodCandidate(CXXMethodDecl *Method,
2644 DeclAccessPair FoundDecl,
2645 CXXRecordDecl *ActingContext, QualType ObjectType,
2646 Expr::Classification ObjectClassification,
2647 ArrayRef<Expr *> Args,
2648 OverloadCandidateSet& CandidateSet,
2649 bool SuppressUserConversions = false,
2650 bool PartialOverloading = false,
2651 ConversionSequenceList EarlyConversions = None);
2652 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2653 DeclAccessPair FoundDecl,
2654 CXXRecordDecl *ActingContext,
2655 TemplateArgumentListInfo *ExplicitTemplateArgs,
2656 QualType ObjectType,
2657 Expr::Classification ObjectClassification,
2658 ArrayRef<Expr *> Args,
2659 OverloadCandidateSet& CandidateSet,
2660 bool SuppressUserConversions = false,
2661 bool PartialOverloading = false);
2662 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2663 DeclAccessPair FoundDecl,
2664 TemplateArgumentListInfo *ExplicitTemplateArgs,
2665 ArrayRef<Expr *> Args,
2666 OverloadCandidateSet& CandidateSet,
2667 bool SuppressUserConversions = false,
2668 bool PartialOverloading = false);
2669 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2670 ArrayRef<QualType> ParamTypes,
2671 ArrayRef<Expr *> Args,
2672 OverloadCandidateSet &CandidateSet,
2673 ConversionSequenceList &Conversions,
2674 bool SuppressUserConversions,
2675 CXXRecordDecl *ActingContext = nullptr,
2676 QualType ObjectType = QualType(),
2677 Expr::Classification
2678 ObjectClassification = {});
2679 void AddConversionCandidate(CXXConversionDecl *Conversion,
2680 DeclAccessPair FoundDecl,
2681 CXXRecordDecl *ActingContext,
2682 Expr *From, QualType ToType,
2683 OverloadCandidateSet& CandidateSet,
2684 bool AllowObjCConversionOnExplicit);
2685 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2686 DeclAccessPair FoundDecl,
2687 CXXRecordDecl *ActingContext,
2688 Expr *From, QualType ToType,
2689 OverloadCandidateSet &CandidateSet,
2690 bool AllowObjCConversionOnExplicit);
2691 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2692 DeclAccessPair FoundDecl,
2693 CXXRecordDecl *ActingContext,
2694 const FunctionProtoType *Proto,
2695 Expr *Object, ArrayRef<Expr *> Args,
2696 OverloadCandidateSet& CandidateSet);
2697 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2698 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2699 OverloadCandidateSet& CandidateSet,
2700 SourceRange OpRange = SourceRange());
2701 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2702 ArrayRef<Expr *> Args,
2703 OverloadCandidateSet& CandidateSet,
2704 bool IsAssignmentOperator = false,
2705 unsigned NumContextualBoolArguments = 0);
2706 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2707 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2708 OverloadCandidateSet& CandidateSet);
2709 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2711 ArrayRef<Expr *> Args,
2712 TemplateArgumentListInfo *ExplicitTemplateArgs,
2713 OverloadCandidateSet& CandidateSet,
2714 bool PartialOverloading = false);
2716 // Emit as a 'note' the specific overload candidate
2717 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2718 QualType DestType = QualType(),
2719 bool TakingAddress = false);
2721 // Emit as a series of 'note's all template and non-templates identified by
2722 // the expression Expr
2723 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2724 bool TakingAddress = false);
2726 /// Check the enable_if expressions on the given function. Returns the first
2727 /// failing attribute, or NULL if they were all successful.
2728 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2729 bool MissingImplicitThis = false);
2731 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2732 /// non-ArgDependent DiagnoseIfAttrs.
2734 /// Argument-dependent diagnose_if attributes should be checked each time a
2735 /// function is used as a direct callee of a function call.
2737 /// Returns true if any errors were emitted.
2738 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2739 const Expr *ThisArg,
2740 ArrayRef<const Expr *> Args,
2741 SourceLocation Loc);
2743 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2744 /// ArgDependent DiagnoseIfAttrs.
2746 /// Argument-independent diagnose_if attributes should be checked on every use
2749 /// Returns true if any errors were emitted.
2750 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2751 SourceLocation Loc);
2753 /// Returns whether the given function's address can be taken or not,
2754 /// optionally emitting a diagnostic if the address can't be taken.
2756 /// Returns false if taking the address of the function is illegal.
2757 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2758 bool Complain = false,
2759 SourceLocation Loc = SourceLocation());
2761 // [PossiblyAFunctionType] --> [Return]
2762 // NonFunctionType --> NonFunctionType
2764 // R (*)(A) --> R (A)
2765 // R (&)(A) --> R (A)
2766 // R (S::*)(A) --> R (A)
2767 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2770 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2771 QualType TargetType,
2773 DeclAccessPair &Found,
2774 bool *pHadMultipleCandidates = nullptr);
2777 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2778 DeclAccessPair &FoundResult);
2780 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2781 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2784 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2785 bool Complain = false,
2786 DeclAccessPair *Found = nullptr);
2788 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2789 ExprResult &SrcExpr,
2790 bool DoFunctionPointerConverion = false,
2791 bool Complain = false,
2792 SourceRange OpRangeForComplaining = SourceRange(),
2793 QualType DestTypeForComplaining = QualType(),
2794 unsigned DiagIDForComplaining = 0);
2797 Expr *FixOverloadedFunctionReference(Expr *E,
2798 DeclAccessPair FoundDecl,
2800 ExprResult FixOverloadedFunctionReference(ExprResult,
2801 DeclAccessPair FoundDecl,
2804 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2805 ArrayRef<Expr *> Args,
2806 OverloadCandidateSet &CandidateSet,
2807 bool PartialOverloading = false);
2809 // An enum used to represent the different possible results of building a
2810 // range-based for loop.
2811 enum ForRangeStatus {
2813 FRS_NoViableFunction,
2814 FRS_DiagnosticIssued
2817 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2818 SourceLocation RangeLoc,
2819 const DeclarationNameInfo &NameInfo,
2820 LookupResult &MemberLookup,
2821 OverloadCandidateSet *CandidateSet,
2822 Expr *Range, ExprResult *CallExpr);
2824 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2825 UnresolvedLookupExpr *ULE,
2826 SourceLocation LParenLoc,
2828 SourceLocation RParenLoc,
2830 bool AllowTypoCorrection=true,
2831 bool CalleesAddressIsTaken=false);
2833 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2834 MultiExprArg Args, SourceLocation RParenLoc,
2835 OverloadCandidateSet *CandidateSet,
2836 ExprResult *Result);
2838 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2839 UnaryOperatorKind Opc,
2840 const UnresolvedSetImpl &Fns,
2843 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2844 BinaryOperatorKind Opc,
2845 const UnresolvedSetImpl &Fns,
2846 Expr *LHS, Expr *RHS);
2848 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2849 SourceLocation RLoc,
2850 Expr *Base,Expr *Idx);
2853 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2854 SourceLocation LParenLoc,
2856 SourceLocation RParenLoc);
2858 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2860 SourceLocation RParenLoc);
2862 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2863 SourceLocation OpLoc,
2864 bool *NoArrowOperatorFound = nullptr);
2866 /// CheckCallReturnType - Checks that a call expression's return type is
2867 /// complete. Returns true on failure. The location passed in is the location
2868 /// that best represents the call.
2869 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2870 CallExpr *CE, FunctionDecl *FD);
2872 /// Helpers for dealing with blocks and functions.
2873 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2874 bool CheckParameterNames);
2875 void CheckCXXDefaultArguments(FunctionDecl *FD);
2876 void CheckExtraCXXDefaultArguments(Declarator &D);
2877 Scope *getNonFieldDeclScope(Scope *S);
2879 /// \name Name lookup
2881 /// These routines provide name lookup that is used during semantic
2882 /// analysis to resolve the various kinds of names (identifiers,
2883 /// overloaded operator names, constructor names, etc.) into zero or
2884 /// more declarations within a particular scope. The major entry
2885 /// points are LookupName, which performs unqualified name lookup,
2886 /// and LookupQualifiedName, which performs qualified name lookup.
2888 /// All name lookup is performed based on some specific criteria,
2889 /// which specify what names will be visible to name lookup and how
2890 /// far name lookup should work. These criteria are important both
2891 /// for capturing language semantics (certain lookups will ignore
2892 /// certain names, for example) and for performance, since name
2893 /// lookup is often a bottleneck in the compilation of C++. Name
2894 /// lookup criteria is specified via the LookupCriteria enumeration.
2896 /// The results of name lookup can vary based on the kind of name
2897 /// lookup performed, the current language, and the translation
2898 /// unit. In C, for example, name lookup will either return nothing
2899 /// (no entity found) or a single declaration. In C++, name lookup
2900 /// can additionally refer to a set of overloaded functions or
2901 /// result in an ambiguity. All of the possible results of name
2902 /// lookup are captured by the LookupResult class, which provides
2903 /// the ability to distinguish among them.
2906 /// @brief Describes the kind of name lookup to perform.
2907 enum LookupNameKind {
2908 /// Ordinary name lookup, which finds ordinary names (functions,
2909 /// variables, typedefs, etc.) in C and most kinds of names
2910 /// (functions, variables, members, types, etc.) in C++.
2911 LookupOrdinaryName = 0,
2912 /// Tag name lookup, which finds the names of enums, classes,
2913 /// structs, and unions.
2915 /// Label name lookup.
2917 /// Member name lookup, which finds the names of
2918 /// class/struct/union members.
2920 /// Look up of an operator name (e.g., operator+) for use with
2921 /// operator overloading. This lookup is similar to ordinary name
2922 /// lookup, but will ignore any declarations that are class members.
2924 /// Look up of a name that precedes the '::' scope resolution
2925 /// operator in C++. This lookup completely ignores operator, object,
2926 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2927 LookupNestedNameSpecifierName,
2928 /// Look up a namespace name within a C++ using directive or
2929 /// namespace alias definition, ignoring non-namespace names (C++
2930 /// [basic.lookup.udir]p1).
2931 LookupNamespaceName,
2932 /// Look up all declarations in a scope with the given name,
2933 /// including resolved using declarations. This is appropriate
2934 /// for checking redeclarations for a using declaration.
2935 LookupUsingDeclName,
2936 /// Look up an ordinary name that is going to be redeclared as a
2937 /// name with linkage. This lookup ignores any declarations that
2938 /// are outside of the current scope unless they have linkage. See
2939 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2940 LookupRedeclarationWithLinkage,
2941 /// Look up a friend of a local class. This lookup does not look
2942 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2943 LookupLocalFriendName,
2944 /// Look up the name of an Objective-C protocol.
2945 LookupObjCProtocolName,
2946 /// Look up implicit 'self' parameter of an objective-c method.
2947 LookupObjCImplicitSelfParam,
2948 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2949 LookupOMPReductionName,
2950 /// \brief Look up any declaration with any name.
2954 /// \brief Specifies whether (or how) name lookup is being performed for a
2955 /// redeclaration (vs. a reference).
2956 enum RedeclarationKind {
2957 /// \brief The lookup is a reference to this name that is not for the
2958 /// purpose of redeclaring the name.
2959 NotForRedeclaration = 0,
2960 /// \brief The lookup results will be used for redeclaration of a name,
2961 /// if an entity by that name already exists.
2965 /// \brief The possible outcomes of name lookup for a literal operator.
2966 enum LiteralOperatorLookupResult {
2967 /// \brief The lookup resulted in an error.
2969 /// \brief The lookup found a single 'cooked' literal operator, which
2970 /// expects a normal literal to be built and passed to it.
2972 /// \brief The lookup found a single 'raw' literal operator, which expects
2973 /// a string literal containing the spelling of the literal token.
2975 /// \brief The lookup found an overload set of literal operator templates,
2976 /// which expect the characters of the spelling of the literal token to be
2977 /// passed as a non-type template argument pack.
2979 /// \brief The lookup found an overload set of literal operator templates,
2980 /// which expect the character type and characters of the spelling of the
2981 /// string literal token to be passed as template arguments.
2985 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2986 CXXSpecialMember SM,
2993 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2994 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2995 TypoRecoveryCallback;
2998 bool CppLookupName(LookupResult &R, Scope *S);
3000 struct TypoExprState {
3001 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3002 TypoDiagnosticGenerator DiagHandler;
3003 TypoRecoveryCallback RecoveryHandler;
3005 TypoExprState(TypoExprState &&other) noexcept;
3006 TypoExprState &operator=(TypoExprState &&other) noexcept;
3009 /// \brief The set of unhandled TypoExprs and their associated state.
3010 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3012 /// \brief Creates a new TypoExpr AST node.
3013 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3014 TypoDiagnosticGenerator TDG,
3015 TypoRecoveryCallback TRC);
3017 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3019 // The boolean value will be true to indicate that the namespace was loaded
3020 // from an AST/PCH file, or false otherwise.
3021 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3023 /// \brief Whether we have already loaded known namespaces from an extenal
3025 bool LoadedExternalKnownNamespaces;
3027 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3028 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3029 /// should be skipped entirely.
3030 std::unique_ptr<TypoCorrectionConsumer>
3031 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3032 Sema::LookupNameKind LookupKind, Scope *S,
3034 std::unique_ptr<CorrectionCandidateCallback> CCC,
3035 DeclContext *MemberContext, bool EnteringContext,
3036 const ObjCObjectPointerType *OPT,
3037 bool ErrorRecovery);
3040 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3042 /// \brief Clears the state of the given TypoExpr.
3043 void clearDelayedTypo(TypoExpr *TE);
3045 /// \brief Look up a name, looking for a single declaration. Return
3046 /// null if the results were absent, ambiguous, or overloaded.
3048 /// It is preferable to use the elaborated form and explicitly handle
3049 /// ambiguity and overloaded.
3050 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3052 LookupNameKind NameKind,
3053 RedeclarationKind Redecl
3054 = NotForRedeclaration);
3055 bool LookupName(LookupResult &R, Scope *S,
3056 bool AllowBuiltinCreation = false);
3057 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3058 bool InUnqualifiedLookup = false);
3059 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3061 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3062 bool AllowBuiltinCreation = false,
3063 bool EnteringContext = false);
3064 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3065 RedeclarationKind Redecl
3066 = NotForRedeclaration);
3067 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3069 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3070 QualType T1, QualType T2,
3071 UnresolvedSetImpl &Functions);
3073 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3074 SourceLocation GnuLabelLoc = SourceLocation());
3076 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3077 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3078 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3080 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3081 bool RValueThis, unsigned ThisQuals);
3082 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3084 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3085 bool RValueThis, unsigned ThisQuals);
3086 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3088 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3089 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3090 ArrayRef<QualType> ArgTys,
3093 bool AllowStringTemplate);
3094 bool isKnownName(StringRef name);
3096 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3097 ArrayRef<Expr *> Args, ADLResult &Functions);
3099 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3100 VisibleDeclConsumer &Consumer,
3101 bool IncludeGlobalScope = true);
3102 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3103 VisibleDeclConsumer &Consumer,
3104 bool IncludeGlobalScope = true,
3105 bool IncludeDependentBases = false);
3107 enum CorrectTypoKind {
3108 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3109 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3112 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3113 Sema::LookupNameKind LookupKind,
3114 Scope *S, CXXScopeSpec *SS,
3115 std::unique_ptr<CorrectionCandidateCallback> CCC,
3116 CorrectTypoKind Mode,
3117 DeclContext *MemberContext = nullptr,
3118 bool EnteringContext = false,
3119 const ObjCObjectPointerType *OPT = nullptr,
3120 bool RecordFailure = true);
3122 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3123 Sema::LookupNameKind LookupKind, Scope *S,
3125 std::unique_ptr<CorrectionCandidateCallback> CCC,
3126 TypoDiagnosticGenerator TDG,
3127 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3128 DeclContext *MemberContext = nullptr,
3129 bool EnteringContext = false,
3130 const ObjCObjectPointerType *OPT = nullptr);
3132 /// \brief Process any TypoExprs in the given Expr and its children,
3133 /// generating diagnostics as appropriate and returning a new Expr if there
3134 /// were typos that were all successfully corrected and ExprError if one or
3135 /// more typos could not be corrected.
3137 /// \param E The Expr to check for TypoExprs.
3139 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3142 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3143 /// it is an acceptable/usable result from a single combination of typo
3144 /// corrections. As long as the filter returns ExprError, different
3145 /// combinations of corrections will be tried until all are exhausted.
3147 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3148 llvm::function_ref<ExprResult(Expr *)> Filter =
3149 [](Expr *E) -> ExprResult { return E; });
3152 CorrectDelayedTyposInExpr(Expr *E,
3153 llvm::function_ref<ExprResult(Expr *)> Filter) {
3154 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3158 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3159 llvm::function_ref<ExprResult(Expr *)> Filter =
3160 [](Expr *E) -> ExprResult { return E; }) {
3161 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3165 CorrectDelayedTyposInExpr(ExprResult ER,
3166 llvm::function_ref<ExprResult(Expr *)> Filter) {
3167 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3170 void diagnoseTypo(const TypoCorrection &Correction,
3171 const PartialDiagnostic &TypoDiag,
3172 bool ErrorRecovery = true);
3174 void diagnoseTypo(const TypoCorrection &Correction,
3175 const PartialDiagnostic &TypoDiag,
3176 const PartialDiagnostic &PrevNote,
3177 bool ErrorRecovery = true);
3179 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3181 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3182 ArrayRef<Expr *> Args,
3183 AssociatedNamespaceSet &AssociatedNamespaces,
3184 AssociatedClassSet &AssociatedClasses);
3186 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3187 bool ConsiderLinkage, bool AllowInlineNamespace);
3189 void DiagnoseAmbiguousLookup(LookupResult &Result);
3192 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3193 SourceLocation IdLoc,
3194 bool TypoCorrection = false);
3195 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3196 Scope *S, bool ForRedeclaration,
3197 SourceLocation Loc);
3198 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3200 void AddKnownFunctionAttributes(FunctionDecl *FD);
3202 // More parsing and symbol table subroutines.
3204 void ProcessPragmaWeak(Scope *S, Decl *D);
3205 // Decl attributes - this routine is the top level dispatcher.
3206 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3207 // Helper for delayed proccessing of attributes.
3208 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3209 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3210 bool IncludeCXX11Attributes = true);
3211 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3212 const AttributeList *AttrList);
3214 void checkUnusedDeclAttributes(Declarator &D);
3216 /// Determine if type T is a valid subject for a nonnull and similar
3217 /// attributes. By default, we look through references (the behavior used by
3218 /// nonnull), but if the second parameter is true, then we treat a reference
3220 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3222 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3223 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3224 const FunctionDecl *FD = nullptr);
3225 bool CheckNoReturnAttr(const AttributeList &attr);
3226 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3227 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3228 unsigned ArgNum, StringRef &Str,
3229 SourceLocation *ArgLocation = nullptr);
3230 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3231 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3232 bool checkMSInheritanceAttrOnDefinition(
3233 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3234 MSInheritanceAttr::Spelling SemanticSpelling);
3236 void CheckAlignasUnderalignment(Decl *D);
3238 /// Adjust the calling convention of a method to be the ABI default if it
3239 /// wasn't specified explicitly. This handles method types formed from
3240 /// function type typedefs and typename template arguments.
3241 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3242 SourceLocation Loc);
3244 // Check if there is an explicit attribute, but only look through parens.
3245 // The intent is to look for an attribute on the current declarator, but not
3246 // one that came from a typedef.
3247 bool hasExplicitCallingConv(QualType &T);
3249 /// Get the outermost AttributedType node that sets a calling convention.
3250 /// Valid types should not have multiple attributes with different CCs.
3251 const AttributedType *getCallingConvAttributedType(QualType T) const;
3253 /// Check whether a nullability type specifier can be added to the given
3256 /// \param type The type to which the nullability specifier will be
3257 /// added. On success, this type will be updated appropriately.
3259 /// \param nullability The nullability specifier to add.
3261 /// \param nullabilityLoc The location of the nullability specifier.
3263 /// \param isContextSensitive Whether this nullability specifier was
3264 /// written as a context-sensitive keyword (in an Objective-C
3265 /// method) or an Objective-C property attribute, rather than as an
3266 /// underscored type specifier.
3268 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3269 /// array type (e.g., because it will decay to a pointer).
3271 /// \returns true if nullability cannot be applied, false otherwise.
3272 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3273 SourceLocation nullabilityLoc,
3274 bool isContextSensitive,
3275 bool allowArrayTypes);
3277 /// \brief Stmt attributes - this routine is the top level dispatcher.
3278 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3281 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3282 ObjCMethodDecl *MethodDecl,
3283 bool IsProtocolMethodDecl);
3285 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3286 ObjCMethodDecl *Overridden,
3287 bool IsProtocolMethodDecl);
3289 /// WarnExactTypedMethods - This routine issues a warning if method
3290 /// implementation declaration matches exactly that of its declaration.
3291 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3292 ObjCMethodDecl *MethodDecl,
3293 bool IsProtocolMethodDecl);
3295 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3297 /// CheckImplementationIvars - This routine checks if the instance variables
3298 /// listed in the implelementation match those listed in the interface.
3299 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3300 ObjCIvarDecl **Fields, unsigned nIvars,
3301 SourceLocation Loc);
3303 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3304 /// remains unimplemented in the class or category \@implementation.
3305 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3306 ObjCContainerDecl* IDecl,
3307 bool IncompleteImpl = false);
3309 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3310 /// which must be implemented by this implementation.
3311 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3312 ObjCContainerDecl *CDecl,
3313 bool SynthesizeProperties);
3315 /// Diagnose any null-resettable synthesized setters.
3316 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3318 /// DefaultSynthesizeProperties - This routine default synthesizes all
3319 /// properties which must be synthesized in the class's \@implementation.
3320 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3321 ObjCInterfaceDecl *IDecl);
3322 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3324 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3325 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3326 /// declared in class 'IFace'.
3327 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3328 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3330 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3331 /// backs the property is not used in the property's accessor.
3332 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3333 const ObjCImplementationDecl *ImplD);
3335 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3336 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3337 /// It also returns ivar's property on success.
3338 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3339 const ObjCPropertyDecl *&PDecl) const;
3341 /// Called by ActOnProperty to handle \@property declarations in
3342 /// class extensions.
3343 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3344 SourceLocation AtLoc,
3345 SourceLocation LParenLoc,
3346 FieldDeclarator &FD,
3348 SourceLocation GetterNameLoc,
3350 SourceLocation SetterNameLoc,
3351 const bool isReadWrite,
3352 unsigned &Attributes,
3353 const unsigned AttributesAsWritten,
3355 TypeSourceInfo *TSI,
3356 tok::ObjCKeywordKind MethodImplKind);
3358 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3359 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3360 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3361 ObjCContainerDecl *CDecl,
3362 SourceLocation AtLoc,
3363 SourceLocation LParenLoc,
3364 FieldDeclarator &FD,
3366 SourceLocation GetterNameLoc,
3368 SourceLocation SetterNameLoc,
3369 const bool isReadWrite,
3370 const unsigned Attributes,
3371 const unsigned AttributesAsWritten,
3373 TypeSourceInfo *TSI,
3374 tok::ObjCKeywordKind MethodImplKind,
3375 DeclContext *lexicalDC = nullptr);
3377 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3378 /// warning) when atomic property has one but not the other user-declared
3379 /// setter or getter.
3380 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3381 ObjCInterfaceDecl* IDecl);
3383 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3385 void DiagnoseMissingDesignatedInitOverrides(
3386 const ObjCImplementationDecl *ImplD,
3387 const ObjCInterfaceDecl *IFD);
3389 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3391 enum MethodMatchStrategy {
3396 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3397 /// true, or false, accordingly.
3398 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3399 const ObjCMethodDecl *PrevMethod,
3400 MethodMatchStrategy strategy = MMS_strict);
3402 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3403 /// or protocol against those declared in their implementations.
3404 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3405 const SelectorSet &ClsMap,
3406 SelectorSet &InsMapSeen,
3407 SelectorSet &ClsMapSeen,
3408 ObjCImplDecl* IMPDecl,
3409 ObjCContainerDecl* IDecl,
3410 bool &IncompleteImpl,
3411 bool ImmediateClass,
3412 bool WarnCategoryMethodImpl=false);
3414 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3415 /// category matches with those implemented in its primary class and
3416 /// warns each time an exact match is found.
3417 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3419 /// \brief Add the given method to the list of globally-known methods.
3420 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3423 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3424 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3425 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3427 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3428 /// optionally warns if there are multiple signatures.
3429 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3430 bool receiverIdOrClass,
3434 /// \brief - Returns instance or factory methods in global method pool for
3435 /// given selector. It checks the desired kind first, if none is found, and
3436 /// parameter checkTheOther is set, it then checks the other kind. If no such
3437 /// method or only one method is found, function returns false; otherwise, it
3440 CollectMultipleMethodsInGlobalPool(Selector Sel,
3441 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3442 bool InstanceFirst, bool CheckTheOther,
3443 const ObjCObjectType *TypeBound = nullptr);
3446 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3447 SourceRange R, bool receiverIdOrClass,
3448 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3451 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3452 Selector Sel, SourceRange R,
3453 bool receiverIdOrClass);
3456 /// \brief - Returns a selector which best matches given argument list or
3457 /// nullptr if none could be found
3458 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3460 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3463 /// \brief Record the typo correction failure and return an empty correction.
3464 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3465 bool RecordFailure = true) {
3467 TypoCorrectionFailures[Typo].insert(TypoLoc);
3468 return TypoCorrection();
3472 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3473 /// unit are added to a global pool. This allows us to efficiently associate
3474 /// a selector with a method declaraation for purposes of typechecking
3475 /// messages sent to "id" (where the class of the object is unknown).
3476 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3477 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3480 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3481 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3482 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3485 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3487 void AddAnyMethodToGlobalPool(Decl *D);
3489 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3490 /// there are multiple signatures.
3491 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3492 bool receiverIdOrClass=false) {
3493 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3497 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3498 /// there are multiple signatures.
3499 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3500 bool receiverIdOrClass=false) {
3501 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3505 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3506 QualType ObjectType=QualType());
3507 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3509 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3511 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3513 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3514 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3516 //===--------------------------------------------------------------------===//
3517 // Statement Parsing Callbacks: SemaStmt.cpp.
3521 FullExprArg() : E(nullptr) { }
3522 FullExprArg(Sema &actions) : E(nullptr) { }
3524 ExprResult release() {
3528 Expr *get() const { return E; }
3530 Expr *operator->() {
3535 // FIXME: No need to make the entire Sema class a friend when it's just
3536 // Sema::MakeFullExpr that needs access to the constructor below.
3539 explicit FullExprArg(Expr *expr) : E(expr) {}
3544 FullExprArg MakeFullExpr(Expr *Arg) {
3545 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3547 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3548 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3550 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3552 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3553 /*DiscardedValue*/ true);
3554 return FullExprArg(FE.get());
3557 StmtResult ActOnExprStmt(ExprResult Arg);
3558 StmtResult ActOnExprStmtError();
3560 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3561 bool HasLeadingEmptyMacro = false);
3563 void ActOnStartOfCompoundStmt();
3564 void ActOnFinishOfCompoundStmt();
3565 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3566 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3568 /// \brief A RAII object to enter scope of a compound statement.
3569 class CompoundScopeRAII {
3571 CompoundScopeRAII(Sema &S): S(S) {
3572 S.ActOnStartOfCompoundStmt();
3575 ~CompoundScopeRAII() {
3576 S.ActOnFinishOfCompoundStmt();
3583 /// An RAII helper that pops function a function scope on exit.
3584 struct FunctionScopeRAII {
3587 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3588 ~FunctionScopeRAII() {
3590 S.PopFunctionScopeInfo();
3592 void disable() { Active = false; }
3595 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3596 SourceLocation StartLoc,
3597 SourceLocation EndLoc);
3598 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3599 StmtResult ActOnForEachLValueExpr(Expr *E);
3600 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3601 SourceLocation DotDotDotLoc, Expr *RHSVal,
3602 SourceLocation ColonLoc);
3603 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3605 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3606 SourceLocation ColonLoc,
3607 Stmt *SubStmt, Scope *CurScope);
3608 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3609 SourceLocation ColonLoc, Stmt *SubStmt);
3611 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3612 ArrayRef<const Attr*> Attrs,
3615 class ConditionResult;
3616 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3618 ConditionResult Cond, Stmt *ThenVal,
3619 SourceLocation ElseLoc, Stmt *ElseVal);
3620 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3622 ConditionResult Cond, Stmt *ThenVal,
3623 SourceLocation ElseLoc, Stmt *ElseVal);
3624 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3626 ConditionResult Cond);
3627 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3628 Stmt *Switch, Stmt *Body);
3629 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3631 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3632 SourceLocation WhileLoc, SourceLocation CondLParen,
3633 Expr *Cond, SourceLocation CondRParen);
3635 StmtResult ActOnForStmt(SourceLocation ForLoc,
3636 SourceLocation LParenLoc,
3638 ConditionResult Second,
3640 SourceLocation RParenLoc,
3642 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3644 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3645 Stmt *First, Expr *collection,
3646 SourceLocation RParenLoc);
3647 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3649 enum BuildForRangeKind {
3650 /// Initial building of a for-range statement.
3652 /// Instantiation or recovery rebuild of a for-range statement. Don't
3653 /// attempt any typo-correction.
3655 /// Determining whether a for-range statement could be built. Avoid any
3656 /// unnecessary or irreversible actions.
3660 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3661 SourceLocation CoawaitLoc,
3663 SourceLocation ColonLoc, Expr *Collection,
3664 SourceLocation RParenLoc,
3665 BuildForRangeKind Kind);
3666 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3667 SourceLocation CoawaitLoc,
3668 SourceLocation ColonLoc,
3669 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3670 Expr *Cond, Expr *Inc,
3672 SourceLocation RParenLoc,
3673 BuildForRangeKind Kind);
3674 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3676 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3677 SourceLocation LabelLoc,
3678 LabelDecl *TheDecl);
3679 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3680 SourceLocation StarLoc,
3682 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3683 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3685 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3686 CapturedRegionKind Kind, unsigned NumParams);
3687 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3688 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3689 CapturedRegionKind Kind,
3690 ArrayRef<CapturedParamNameType> Params);
3691 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3692 void ActOnCapturedRegionError();
3693 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3695 unsigned NumParams);
3696 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3697 bool AllowParamOrMoveConstructible);
3698 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3699 bool AllowParamOrMoveConstructible);
3701 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3703 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3704 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3706 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3707 bool IsVolatile, unsigned NumOutputs,
3708 unsigned NumInputs, IdentifierInfo **Names,
3709 MultiExprArg Constraints, MultiExprArg Exprs,
3710 Expr *AsmString, MultiExprArg Clobbers,
3711 SourceLocation RParenLoc);
3713 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3714 SourceLocation TemplateKWLoc,
3716 llvm::InlineAsmIdentifierInfo &Info,
3717 bool IsUnevaluatedContext);
3718 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3719 unsigned &Offset, SourceLocation AsmLoc);
3720 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3721 llvm::InlineAsmIdentifierInfo &Info,
3722 SourceLocation AsmLoc);
3723 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3724 ArrayRef<Token> AsmToks,
3725 StringRef AsmString,
3726 unsigned NumOutputs, unsigned NumInputs,
3727 ArrayRef<StringRef> Constraints,
3728 ArrayRef<StringRef> Clobbers,
3729 ArrayRef<Expr*> Exprs,
3730 SourceLocation EndLoc);
3731 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3732 SourceLocation Location,
3735 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3736 SourceLocation StartLoc,
3737 SourceLocation IdLoc, IdentifierInfo *Id,
3738 bool Invalid = false);
3740 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3742 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3743 Decl *Parm, Stmt *Body);
3745 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3747 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3748 MultiStmtArg Catch, Stmt *Finally);
3750 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3751 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3753 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3755 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3759 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3761 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3762 SourceLocation StartLoc,
3763 SourceLocation IdLoc,
3764 IdentifierInfo *Id);
3766 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3768 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3769 Decl *ExDecl, Stmt *HandlerBlock);
3770 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3771 ArrayRef<Stmt *> Handlers);
3773 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3774 SourceLocation TryLoc, Stmt *TryBlock,
3776 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3779 void ActOnStartSEHFinallyBlock();
3780 void ActOnAbortSEHFinallyBlock();
3781 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3782 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3784 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3786 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3788 /// \brief If it's a file scoped decl that must warn if not used, keep track
3790 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3792 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3793 /// whose result is unused, warn.
3794 void DiagnoseUnusedExprResult(const Stmt *S);
3795 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3796 void DiagnoseUnusedDecl(const NamedDecl *ND);
3798 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3799 /// statement as a \p Body, and it is located on the same line.
3801 /// This helps prevent bugs due to typos, such as:
3804 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3808 /// Warn if a for/while loop statement \p S, which is followed by
3809 /// \p PossibleBody, has a suspicious null statement as a body.
3810 void DiagnoseEmptyLoopBody(const Stmt *S,
3811 const Stmt *PossibleBody);
3813 /// Warn if a value is moved to itself.
3814 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3815 SourceLocation OpLoc);
3817 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3819 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3820 SourceLocation Loc);
3822 /// Warn when implicitly casting 0 to nullptr.
3823 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3825 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3826 return DelayedDiagnostics.push(pool);
3828 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3830 typedef ProcessingContextState ParsingClassState;
3831 ParsingClassState PushParsingClass() {
3832 return DelayedDiagnostics.pushUndelayed();
3834 void PopParsingClass(ParsingClassState state) {
3835 DelayedDiagnostics.popUndelayed(state);
3838 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3840 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3841 StringRef Message, SourceLocation Loc,
3842 const ObjCInterfaceDecl *UnknownObjCClass,
3843 const ObjCPropertyDecl *ObjCProperty,
3844 bool ObjCPropertyAccess);
3846 bool makeUnavailableInSystemHeader(SourceLocation loc,
3847 UnavailableAttr::ImplicitReason reason);
3849 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3850 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3852 //===--------------------------------------------------------------------===//
3853 // Expression Parsing Callbacks: SemaExpr.cpp.
3855 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3856 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3857 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3858 bool ObjCPropertyAccess=false);
3859 void NoteDeletedFunction(FunctionDecl *FD);
3860 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3861 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3862 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3863 ObjCMethodDecl *Getter,
3864 SourceLocation Loc);
3865 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3866 ArrayRef<Expr *> Args);
3868 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3869 Decl *LambdaContextDecl = nullptr,
3870 bool IsDecltype = false);
3871 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3872 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3873 ReuseLambdaContextDecl_t,
3874 bool IsDecltype = false);
3875 void PopExpressionEvaluationContext();
3877 void DiscardCleanupsInEvaluationContext();
3879 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3880 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3882 ExprResult ActOnConstantExpression(ExprResult Res);
3884 // Functions for marking a declaration referenced. These functions also
3885 // contain the relevant logic for marking if a reference to a function or
3886 // variable is an odr-use (in the C++11 sense). There are separate variants
3887 // for expressions referring to a decl; these exist because odr-use marking
3888 // needs to be delayed for some constant variables when we build one of the
3889 // named expressions.
3891 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3892 // should usually be true. This only needs to be set to false if the lack of
3893 // odr-use cannot be determined from the current context (for instance,
3894 // because the name denotes a virtual function and was written without an
3895 // explicit nested-name-specifier).
3896 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3897 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3898 bool MightBeOdrUse = true);
3899 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3900 void MarkDeclRefReferenced(DeclRefExpr *E);
3901 void MarkMemberReferenced(MemberExpr *E);
3903 void UpdateMarkingForLValueToRValue(Expr *E);
3904 void CleanupVarDeclMarking();
3906 enum TryCaptureKind {
3907 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3910 /// \brief Try to capture the given variable.
3912 /// \param Var The variable to capture.
3914 /// \param Loc The location at which the capture occurs.
3916 /// \param Kind The kind of capture, which may be implicit (for either a
3917 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3919 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3920 /// an explicit lambda capture.
3922 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3923 /// captures or diagnose errors. If false, this routine merely check whether
3924 /// the capture can occur without performing the capture itself or complaining
3925 /// if the variable cannot be captured.
3927 /// \param CaptureType Will be set to the type of the field used to capture
3928 /// this variable in the innermost block or lambda. Only valid when the
3929 /// variable can be captured.
3931 /// \param DeclRefType Will be set to the type of a reference to the capture
3932 /// from within the current scope. Only valid when the variable can be
3935 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3936 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3937 /// This is useful when enclosing lambdas must speculatively capture
3938 /// variables that may or may not be used in certain specializations of
3939 /// a nested generic lambda.
3941 /// \returns true if an error occurred (i.e., the variable cannot be
3942 /// captured) and false if the capture succeeded.
3943 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3944 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3945 QualType &CaptureType,
3946 QualType &DeclRefType,
3947 const unsigned *const FunctionScopeIndexToStopAt);
3949 /// \brief Try to capture the given variable.
3950 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3951 TryCaptureKind Kind = TryCapture_Implicit,
3952 SourceLocation EllipsisLoc = SourceLocation());
3954 /// \brief Checks if the variable must be captured.
3955 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3957 /// \brief Given a variable, determine the type that a reference to that
3958 /// variable will have in the given scope.
3959 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3961 /// Mark all of the declarations referenced within a particular AST node as
3962 /// referenced. Used when template instantiation instantiates a non-dependent
3963 /// type -- entities referenced by the type are now referenced.
3964 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3965 void MarkDeclarationsReferencedInExpr(Expr *E,
3966 bool SkipLocalVariables = false);
3968 /// \brief Try to recover by turning the given expression into a
3969 /// call. Returns true if recovery was attempted or an error was
3970 /// emitted; this may also leave the ExprResult invalid.
3971 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3972 bool ForceComplain = false,
3973 bool (*IsPlausibleResult)(QualType) = nullptr);
3975 /// \brief Figure out if an expression could be turned into a call.
3976 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3977 UnresolvedSetImpl &NonTemplateOverloads);
3979 /// \brief Conditionally issue a diagnostic based on the current
3980 /// evaluation context.
3982 /// \param Statement If Statement is non-null, delay reporting the
3983 /// diagnostic until the function body is parsed, and then do a basic
3984 /// reachability analysis to determine if the statement is reachable.
3985 /// If it is unreachable, the diagnostic will not be emitted.
3986 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3987 const PartialDiagnostic &PD);
3989 // Primary Expressions.
3990 SourceRange getExprRange(Expr *E) const;
3992 ExprResult ActOnIdExpression(
3993 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3994 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3995 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3996 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3998 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3999 TemplateArgumentListInfo &Buffer,
4000 DeclarationNameInfo &NameInfo,
4001 const TemplateArgumentListInfo *&TemplateArgs);
4004 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4005 std::unique_ptr<CorrectionCandidateCallback> CCC,
4006 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4007 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4009 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4011 bool AllowBuiltinCreation=false);
4013 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4014 SourceLocation TemplateKWLoc,
4015 const DeclarationNameInfo &NameInfo,
4016 bool isAddressOfOperand,
4017 const TemplateArgumentListInfo *TemplateArgs);
4019 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4022 const CXXScopeSpec *SS = nullptr);
4024 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4025 const DeclarationNameInfo &NameInfo,
4026 const CXXScopeSpec *SS = nullptr,
4027 NamedDecl *FoundD = nullptr,
4028 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4030 BuildAnonymousStructUnionMemberReference(
4031 const CXXScopeSpec &SS,
4032 SourceLocation nameLoc,
4033 IndirectFieldDecl *indirectField,
4034 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4035 Expr *baseObjectExpr = nullptr,
4036 SourceLocation opLoc = SourceLocation());
4038 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4039 SourceLocation TemplateKWLoc,
4041 const TemplateArgumentListInfo *TemplateArgs,
4043 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4044 SourceLocation TemplateKWLoc,
4046 const TemplateArgumentListInfo *TemplateArgs,
4047 bool IsDefiniteInstance,
4049 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4050 const LookupResult &R,
4051 bool HasTrailingLParen);
4054 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4055 const DeclarationNameInfo &NameInfo,
4056 bool IsAddressOfOperand, const Scope *S,
4057 TypeSourceInfo **RecoveryTSI = nullptr);
4059 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4060 SourceLocation TemplateKWLoc,
4061 const DeclarationNameInfo &NameInfo,
4062 const TemplateArgumentListInfo *TemplateArgs);
4064 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4067 bool AcceptInvalidDecl = false);
4068 ExprResult BuildDeclarationNameExpr(
4069 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4070 NamedDecl *FoundD = nullptr,
4071 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4072 bool AcceptInvalidDecl = false);
4074 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4075 DeclarationNameInfo &SuffixInfo,
4076 ArrayRef<Expr *> Args,
4077 SourceLocation LitEndLoc,
4078 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4080 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4081 PredefinedExpr::IdentType IT);
4082 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4083 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4085 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4087 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4088 ExprResult ActOnCharacterConstant(const Token &Tok,
4089 Scope *UDLScope = nullptr);
4090 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4091 ExprResult ActOnParenListExpr(SourceLocation L,
4095 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4096 /// fragments (e.g. "foo" "bar" L"baz").
4097 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4098 Scope *UDLScope = nullptr);
4100 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4101 SourceLocation DefaultLoc,
4102 SourceLocation RParenLoc,
4103 Expr *ControllingExpr,
4104 ArrayRef<ParsedType> ArgTypes,
4105 ArrayRef<Expr *> ArgExprs);
4106 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4107 SourceLocation DefaultLoc,
4108 SourceLocation RParenLoc,
4109 Expr *ControllingExpr,
4110 ArrayRef<TypeSourceInfo *> Types,
4111 ArrayRef<Expr *> Exprs);
4113 // Binary/Unary Operators. 'Tok' is the token for the operator.
4114 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4116 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4117 UnaryOperatorKind Opc, Expr *Input);
4118 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4119 tok::TokenKind Op, Expr *Input);
4121 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4123 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4124 SourceLocation OpLoc,
4125 UnaryExprOrTypeTrait ExprKind,
4127 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4128 UnaryExprOrTypeTrait ExprKind);
4130 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4131 UnaryExprOrTypeTrait ExprKind,
4132 bool IsType, void *TyOrEx,
4133 SourceRange ArgRange);
4135 ExprResult CheckPlaceholderExpr(Expr *E);
4136 bool CheckVecStepExpr(Expr *E);
4138 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4139 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4140 SourceRange ExprRange,
4141 UnaryExprOrTypeTrait ExprKind);
4142 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4143 SourceLocation OpLoc,
4144 IdentifierInfo &Name,
4145 SourceLocation NameLoc,
4146 SourceLocation RParenLoc);
4147 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4148 tok::TokenKind Kind, Expr *Input);
4150 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4151 Expr *Idx, SourceLocation RLoc);
4152 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4153 Expr *Idx, SourceLocation RLoc);
4154 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4155 Expr *LowerBound, SourceLocation ColonLoc,
4156 Expr *Length, SourceLocation RBLoc);
4158 // This struct is for use by ActOnMemberAccess to allow
4159 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4160 // changing the access operator from a '.' to a '->' (to see if that is the
4161 // change needed to fix an error about an unknown member, e.g. when the class
4162 // defines a custom operator->).
4163 struct ActOnMemberAccessExtraArgs {
4169 ExprResult BuildMemberReferenceExpr(
4170 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4171 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4172 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4173 const TemplateArgumentListInfo *TemplateArgs,
4175 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4178 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4179 bool IsArrow, const CXXScopeSpec &SS,
4180 SourceLocation TemplateKWLoc,
4181 NamedDecl *FirstQualifierInScope, LookupResult &R,
4182 const TemplateArgumentListInfo *TemplateArgs,
4184 bool SuppressQualifierCheck = false,
4185 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4187 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4188 SourceLocation OpLoc,
4189 const CXXScopeSpec &SS, FieldDecl *Field,
4190 DeclAccessPair FoundDecl,
4191 const DeclarationNameInfo &MemberNameInfo);
4193 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4195 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4196 const CXXScopeSpec &SS,
4197 const LookupResult &R);
4199 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4200 bool IsArrow, SourceLocation OpLoc,
4201 const CXXScopeSpec &SS,
4202 SourceLocation TemplateKWLoc,
4203 NamedDecl *FirstQualifierInScope,
4204 const DeclarationNameInfo &NameInfo,
4205 const TemplateArgumentListInfo *TemplateArgs);
4207 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4208 SourceLocation OpLoc,
4209 tok::TokenKind OpKind,
4211 SourceLocation TemplateKWLoc,
4212 UnqualifiedId &Member,
4215 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4216 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4217 FunctionDecl *FDecl,
4218 const FunctionProtoType *Proto,
4219 ArrayRef<Expr *> Args,
4220 SourceLocation RParenLoc,
4221 bool ExecConfig = false);
4222 void CheckStaticArrayArgument(SourceLocation CallLoc,
4224 const Expr *ArgExpr);
4226 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4227 /// This provides the location of the left/right parens and a list of comma
4229 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4230 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4231 Expr *ExecConfig = nullptr,
4232 bool IsExecConfig = false);
4233 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4234 SourceLocation LParenLoc,
4235 ArrayRef<Expr *> Arg,
4236 SourceLocation RParenLoc,
4237 Expr *Config = nullptr,
4238 bool IsExecConfig = false);
4240 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4241 MultiExprArg ExecConfig,
4242 SourceLocation GGGLoc);
4244 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4245 Declarator &D, ParsedType &Ty,
4246 SourceLocation RParenLoc, Expr *CastExpr);
4247 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4249 SourceLocation RParenLoc,
4251 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4253 /// \brief Build an altivec or OpenCL literal.
4254 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4255 SourceLocation RParenLoc, Expr *E,
4256 TypeSourceInfo *TInfo);
4258 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4260 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4262 SourceLocation RParenLoc,
4265 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4266 TypeSourceInfo *TInfo,
4267 SourceLocation RParenLoc,
4270 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4271 MultiExprArg InitArgList,
4272 SourceLocation RBraceLoc);
4274 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4280 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4283 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4284 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4285 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4286 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4287 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4288 Expr *LHSExpr, Expr *RHSExpr);
4290 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4292 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4293 /// in the case of a the GNU conditional expr extension.
4294 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4295 SourceLocation ColonLoc,
4296 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4298 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4299 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4300 LabelDecl *TheDecl);
4302 void ActOnStartStmtExpr();
4303 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4304 SourceLocation RPLoc); // "({..})"
4305 void ActOnStmtExprError();
4307 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4308 struct OffsetOfComponent {
4309 SourceLocation LocStart, LocEnd;
4310 bool isBrackets; // true if [expr], false if .ident
4312 IdentifierInfo *IdentInfo;
4317 /// __builtin_offsetof(type, a.b[123][456].c)
4318 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4319 TypeSourceInfo *TInfo,
4320 ArrayRef<OffsetOfComponent> Components,
4321 SourceLocation RParenLoc);
4322 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4323 SourceLocation BuiltinLoc,
4324 SourceLocation TypeLoc,
4325 ParsedType ParsedArgTy,
4326 ArrayRef<OffsetOfComponent> Components,
4327 SourceLocation RParenLoc);
4329 // __builtin_choose_expr(constExpr, expr1, expr2)
4330 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4331 Expr *CondExpr, Expr *LHSExpr,
4332 Expr *RHSExpr, SourceLocation RPLoc);
4334 // __builtin_va_arg(expr, type)
4335 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4336 SourceLocation RPLoc);
4337 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4338 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4341 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4343 bool CheckCaseExpression(Expr *E);
4345 /// \brief Describes the result of an "if-exists" condition check.
4346 enum IfExistsResult {
4347 /// \brief The symbol exists.
4350 /// \brief The symbol does not exist.
4353 /// \brief The name is a dependent name, so the results will differ
4354 /// from one instantiation to the next.
4357 /// \brief An error occurred.
4362 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4363 const DeclarationNameInfo &TargetNameInfo);
4366 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4367 bool IsIfExists, CXXScopeSpec &SS,
4368 UnqualifiedId &Name);
4370 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4372 NestedNameSpecifierLoc QualifierLoc,
4373 DeclarationNameInfo NameInfo,
4375 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4377 CXXScopeSpec &SS, UnqualifiedId &Name,
4380 //===------------------------- "Block" Extension ------------------------===//
4382 /// ActOnBlockStart - This callback is invoked when a block literal is
4384 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4386 /// ActOnBlockArguments - This callback allows processing of block arguments.
4387 /// If there are no arguments, this is still invoked.
4388 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4391 /// ActOnBlockError - If there is an error parsing a block, this callback
4392 /// is invoked to pop the information about the block from the action impl.
4393 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4395 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4396 /// literal was successfully completed. ^(int x){...}
4397 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4400 //===---------------------------- Clang Extensions ----------------------===//
4402 /// __builtin_convertvector(...)
4403 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4404 SourceLocation BuiltinLoc,
4405 SourceLocation RParenLoc);
4407 //===---------------------------- OpenCL Features -----------------------===//
4409 /// __builtin_astype(...)
4410 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4411 SourceLocation BuiltinLoc,
4412 SourceLocation RParenLoc);
4414 //===---------------------------- C++ Features --------------------------===//
4416 // Act on C++ namespaces
4417 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4418 SourceLocation NamespaceLoc,
4419 SourceLocation IdentLoc,
4420 IdentifierInfo *Ident,
4421 SourceLocation LBrace,
4422 AttributeList *AttrList,
4423 UsingDirectiveDecl * &UsingDecl);
4424 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4426 NamespaceDecl *getStdNamespace() const;
4427 NamespaceDecl *getOrCreateStdNamespace();
4429 NamespaceDecl *lookupStdExperimentalNamespace();
4431 CXXRecordDecl *getStdBadAlloc() const;
4432 EnumDecl *getStdAlignValT() const;
4434 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4435 /// it is and Element is not NULL, assigns the element type to Element.
4436 bool isStdInitializerList(QualType Ty, QualType *Element);
4438 /// \brief Looks for the std::initializer_list template and instantiates it
4439 /// with Element, or emits an error if it's not found.
4441 /// \returns The instantiated template, or null on error.
4442 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4444 /// \brief Determine whether Ctor is an initializer-list constructor, as
4445 /// defined in [dcl.init.list]p2.
4446 bool isInitListConstructor(const FunctionDecl *Ctor);
4448 Decl *ActOnUsingDirective(Scope *CurScope,
4449 SourceLocation UsingLoc,
4450 SourceLocation NamespcLoc,
4452 SourceLocation IdentLoc,
4453 IdentifierInfo *NamespcName,
4454 AttributeList *AttrList);
4456 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4458 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4459 SourceLocation NamespaceLoc,
4460 SourceLocation AliasLoc,
4461 IdentifierInfo *Alias,
4463 SourceLocation IdentLoc,
4464 IdentifierInfo *Ident);
4466 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4467 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4468 const LookupResult &PreviousDecls,
4469 UsingShadowDecl *&PrevShadow);
4470 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4472 UsingShadowDecl *PrevDecl);
4474 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4475 bool HasTypenameKeyword,
4476 const CXXScopeSpec &SS,
4477 SourceLocation NameLoc,
4478 const LookupResult &Previous);
4479 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4481 const CXXScopeSpec &SS,
4482 const DeclarationNameInfo &NameInfo,
4483 SourceLocation NameLoc);
4485 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4486 SourceLocation UsingLoc,
4487 bool HasTypenameKeyword,
4488 SourceLocation TypenameLoc,
4490 DeclarationNameInfo NameInfo,
4491 SourceLocation EllipsisLoc,
4492 AttributeList *AttrList,
4493 bool IsInstantiation);
4494 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4495 ArrayRef<NamedDecl *> Expansions);
4497 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4499 /// Given a derived-class using shadow declaration for a constructor and the
4500 /// correspnding base class constructor, find or create the implicit
4501 /// synthesized derived class constructor to use for this initialization.
4502 CXXConstructorDecl *
4503 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4504 ConstructorUsingShadowDecl *DerivedShadow);
4506 Decl *ActOnUsingDeclaration(Scope *CurScope,
4508 SourceLocation UsingLoc,
4509 SourceLocation TypenameLoc,
4511 UnqualifiedId &Name,
4512 SourceLocation EllipsisLoc,
4513 AttributeList *AttrList);
4514 Decl *ActOnAliasDeclaration(Scope *CurScope,
4516 MultiTemplateParamsArg TemplateParams,
4517 SourceLocation UsingLoc,
4518 UnqualifiedId &Name,
4519 AttributeList *AttrList,
4521 Decl *DeclFromDeclSpec);
4523 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4524 /// including handling of its default argument expressions.
4526 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4528 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4529 NamedDecl *FoundDecl,
4530 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4531 bool HadMultipleCandidates, bool IsListInitialization,
4532 bool IsStdInitListInitialization,
4533 bool RequiresZeroInit, unsigned ConstructKind,
4534 SourceRange ParenRange);
4536 /// Build a CXXConstructExpr whose constructor has already been resolved if
4537 /// it denotes an inherited constructor.
4539 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4540 CXXConstructorDecl *Constructor, bool Elidable,
4542 bool HadMultipleCandidates, bool IsListInitialization,
4543 bool IsStdInitListInitialization,
4544 bool RequiresZeroInit, unsigned ConstructKind,
4545 SourceRange ParenRange);
4547 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4548 // the constructor can be elidable?
4550 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4551 NamedDecl *FoundDecl,
4552 CXXConstructorDecl *Constructor, bool Elidable,
4553 MultiExprArg Exprs, bool HadMultipleCandidates,
4554 bool IsListInitialization,
4555 bool IsStdInitListInitialization, bool RequiresZeroInit,
4556 unsigned ConstructKind, SourceRange ParenRange);
4558 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4561 /// Instantiate or parse a C++ default argument expression as necessary.
4562 /// Return true on error.
4563 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4564 ParmVarDecl *Param);
4566 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4567 /// the default expr if needed.
4568 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4570 ParmVarDecl *Param);
4572 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4573 /// constructed variable.
4574 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4576 /// \brief Helper class that collects exception specifications for
4577 /// implicitly-declared special member functions.
4578 class ImplicitExceptionSpecification {
4579 // Pointer to allow copying
4581 // We order exception specifications thus:
4582 // noexcept is the most restrictive, but is only used in C++11.
4583 // throw() comes next.
4584 // Then a throw(collected exceptions)
4585 // Finally no specification, which is expressed as noexcept(false).
4586 // throw(...) is used instead if any called function uses it.
4587 ExceptionSpecificationType ComputedEST;
4588 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4589 SmallVector<QualType, 4> Exceptions;
4591 void ClearExceptions() {
4592 ExceptionsSeen.clear();
4597 explicit ImplicitExceptionSpecification(Sema &Self)
4598 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4599 if (!Self.getLangOpts().CPlusPlus11)
4600 ComputedEST = EST_DynamicNone;
4603 /// \brief Get the computed exception specification type.
4604 ExceptionSpecificationType getExceptionSpecType() const {
4605 assert(ComputedEST != EST_ComputedNoexcept &&
4606 "noexcept(expr) should not be a possible result");
4610 /// \brief The number of exceptions in the exception specification.
4611 unsigned size() const { return Exceptions.size(); }
4613 /// \brief The set of exceptions in the exception specification.
4614 const QualType *data() const { return Exceptions.data(); }
4616 /// \brief Integrate another called method into the collected data.
4617 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4619 /// \brief Integrate an invoked expression into the collected data.
4620 void CalledExpr(Expr *E);
4622 /// \brief Overwrite an EPI's exception specification with this
4623 /// computed exception specification.
4624 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4625 FunctionProtoType::ExceptionSpecInfo ESI;
4626 ESI.Type = getExceptionSpecType();
4627 if (ESI.Type == EST_Dynamic) {
4628 ESI.Exceptions = Exceptions;
4629 } else if (ESI.Type == EST_None) {
4630 /// C++11 [except.spec]p14:
4631 /// The exception-specification is noexcept(false) if the set of
4632 /// potential exceptions of the special member function contains "any"
4633 ESI.Type = EST_ComputedNoexcept;
4634 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4635 tok::kw_false).get();
4641 /// \brief Determine what sort of exception specification a defaulted
4642 /// copy constructor of a class will have.
4643 ImplicitExceptionSpecification
4644 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4647 /// \brief Determine what sort of exception specification a defaulted
4648 /// default constructor of a class will have, and whether the parameter
4650 ImplicitExceptionSpecification
4651 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4653 /// \brief Determine what sort of exception specification a defautled
4654 /// copy assignment operator of a class will have, and whether the
4655 /// parameter will be const.
4656 ImplicitExceptionSpecification
4657 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4659 /// \brief Determine what sort of exception specification a defaulted move
4660 /// constructor of a class will have.
4661 ImplicitExceptionSpecification
4662 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4664 /// \brief Determine what sort of exception specification a defaulted move
4665 /// assignment operator of a class will have.
4666 ImplicitExceptionSpecification
4667 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4669 /// \brief Determine what sort of exception specification a defaulted
4670 /// destructor of a class will have.
4671 ImplicitExceptionSpecification
4672 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4674 /// \brief Determine what sort of exception specification an inheriting
4675 /// constructor of a class will have.
4676 ImplicitExceptionSpecification
4677 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4678 CXXConstructorDecl *CD);
4680 /// \brief Evaluate the implicit exception specification for a defaulted
4681 /// special member function.
4682 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4684 /// \brief Check the given exception-specification and update the
4685 /// exception specification information with the results.
4686 void checkExceptionSpecification(bool IsTopLevel,
4687 ExceptionSpecificationType EST,
4688 ArrayRef<ParsedType> DynamicExceptions,
4689 ArrayRef<SourceRange> DynamicExceptionRanges,
4691 SmallVectorImpl<QualType> &Exceptions,
4692 FunctionProtoType::ExceptionSpecInfo &ESI);
4694 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4695 /// parse an exception specification to work around a libstdc++ bug.
4696 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4698 /// \brief Add an exception-specification to the given member function
4699 /// (or member function template). The exception-specification was parsed
4700 /// after the method itself was declared.
4701 void actOnDelayedExceptionSpecification(Decl *Method,
4702 ExceptionSpecificationType EST,
4703 SourceRange SpecificationRange,
4704 ArrayRef<ParsedType> DynamicExceptions,
4705 ArrayRef<SourceRange> DynamicExceptionRanges,
4706 Expr *NoexceptExpr);
4708 class InheritedConstructorInfo;
4710 /// \brief Determine if a special member function should have a deleted
4711 /// definition when it is defaulted.
4712 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4713 InheritedConstructorInfo *ICI = nullptr,
4714 bool Diagnose = false);
4716 /// \brief Declare the implicit default constructor for the given class.
4718 /// \param ClassDecl The class declaration into which the implicit
4719 /// default constructor will be added.
4721 /// \returns The implicitly-declared default constructor.
4722 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4723 CXXRecordDecl *ClassDecl);
4725 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4726 /// defining this constructor as the default constructor.
4727 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4728 CXXConstructorDecl *Constructor);
4730 /// \brief Declare the implicit destructor for the given class.
4732 /// \param ClassDecl The class declaration into which the implicit
4733 /// destructor will be added.
4735 /// \returns The implicitly-declared destructor.
4736 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4738 /// DefineImplicitDestructor - Checks for feasibility of
4739 /// defining this destructor as the default destructor.
4740 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4741 CXXDestructorDecl *Destructor);
4743 /// \brief Build an exception spec for destructors that don't have one.
4745 /// C++11 says that user-defined destructors with no exception spec get one
4746 /// that looks as if the destructor was implicitly declared.
4747 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4748 CXXDestructorDecl *Destructor);
4750 /// \brief Define the specified inheriting constructor.
4751 void DefineInheritingConstructor(SourceLocation UseLoc,
4752 CXXConstructorDecl *Constructor);
4754 /// \brief Declare the implicit copy constructor for the given class.
4756 /// \param ClassDecl The class declaration into which the implicit
4757 /// copy constructor will be added.
4759 /// \returns The implicitly-declared copy constructor.
4760 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4762 /// DefineImplicitCopyConstructor - Checks for feasibility of
4763 /// defining this constructor as the copy constructor.
4764 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4765 CXXConstructorDecl *Constructor);
4767 /// \brief Declare the implicit move constructor for the given class.
4769 /// \param ClassDecl The Class declaration into which the implicit
4770 /// move constructor will be added.
4772 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4774 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4776 /// DefineImplicitMoveConstructor - Checks for feasibility of
4777 /// defining this constructor as the move constructor.
4778 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4779 CXXConstructorDecl *Constructor);
4781 /// \brief Declare the implicit copy assignment operator for the given class.
4783 /// \param ClassDecl The class declaration into which the implicit
4784 /// copy assignment operator will be added.
4786 /// \returns The implicitly-declared copy assignment operator.
4787 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4789 /// \brief Defines an implicitly-declared copy assignment operator.
4790 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4791 CXXMethodDecl *MethodDecl);
4793 /// \brief Declare the implicit move assignment operator for the given class.
4795 /// \param ClassDecl The Class declaration into which the implicit
4796 /// move assignment operator will be added.
4798 /// \returns The implicitly-declared move assignment operator, or NULL if it
4799 /// wasn't declared.
4800 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4802 /// \brief Defines an implicitly-declared move assignment operator.
4803 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4804 CXXMethodDecl *MethodDecl);
4806 /// \brief Force the declaration of any implicitly-declared members of this
4808 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4810 /// \brief Check a completed declaration of an implicit special member.
4811 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4813 /// \brief Determine whether the given function is an implicitly-deleted
4814 /// special member function.
4815 bool isImplicitlyDeleted(FunctionDecl *FD);
4817 /// \brief Check whether 'this' shows up in the type of a static member
4818 /// function after the (naturally empty) cv-qualifier-seq would be.
4820 /// \returns true if an error occurred.
4821 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4823 /// \brief Whether this' shows up in the exception specification of a static
4824 /// member function.
4825 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4827 /// \brief Check whether 'this' shows up in the attributes of the given
4828 /// static member function.
4830 /// \returns true if an error occurred.
4831 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4833 /// MaybeBindToTemporary - If the passed in expression has a record type with
4834 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4835 /// it simply returns the passed in expression.
4836 ExprResult MaybeBindToTemporary(Expr *E);
4838 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4839 MultiExprArg ArgsPtr,
4841 SmallVectorImpl<Expr*> &ConvertedArgs,
4842 bool AllowExplicit = false,
4843 bool IsListInitialization = false);
4845 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4846 SourceLocation NameLoc,
4847 IdentifierInfo &Name);
4849 ParsedType getDestructorName(SourceLocation TildeLoc,
4850 IdentifierInfo &II, SourceLocation NameLoc,
4851 Scope *S, CXXScopeSpec &SS,
4852 ParsedType ObjectType,
4853 bool EnteringContext);
4855 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4856 ParsedType ObjectType);
4858 // Checks that reinterpret casts don't have undefined behavior.
4859 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4860 bool IsDereference, SourceRange Range);
4862 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4863 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4864 tok::TokenKind Kind,
4865 SourceLocation LAngleBracketLoc,
4867 SourceLocation RAngleBracketLoc,
4868 SourceLocation LParenLoc,
4870 SourceLocation RParenLoc);
4872 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4873 tok::TokenKind Kind,
4876 SourceRange AngleBrackets,
4877 SourceRange Parens);
4879 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4880 SourceLocation TypeidLoc,
4881 TypeSourceInfo *Operand,
4882 SourceLocation RParenLoc);
4883 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4884 SourceLocation TypeidLoc,
4886 SourceLocation RParenLoc);
4888 /// ActOnCXXTypeid - Parse typeid( something ).
4889 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4890 SourceLocation LParenLoc, bool isType,
4892 SourceLocation RParenLoc);
4894 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4895 SourceLocation TypeidLoc,
4896 TypeSourceInfo *Operand,
4897 SourceLocation RParenLoc);
4898 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4899 SourceLocation TypeidLoc,
4901 SourceLocation RParenLoc);
4903 /// ActOnCXXUuidof - Parse __uuidof( something ).
4904 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4905 SourceLocation LParenLoc, bool isType,
4907 SourceLocation RParenLoc);
4909 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4910 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4911 tok::TokenKind Operator,
4912 SourceLocation EllipsisLoc, Expr *RHS,
4913 SourceLocation RParenLoc);
4914 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4915 BinaryOperatorKind Operator,
4916 SourceLocation EllipsisLoc, Expr *RHS,
4917 SourceLocation RParenLoc);
4918 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4919 BinaryOperatorKind Operator);
4921 //// ActOnCXXThis - Parse 'this' pointer.
4922 ExprResult ActOnCXXThis(SourceLocation loc);
4924 /// \brief Try to retrieve the type of the 'this' pointer.
4926 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4927 QualType getCurrentThisType();
4929 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4930 /// current context not being a non-static member function. In such cases,
4931 /// this provides the type used for 'this'.
4932 QualType CXXThisTypeOverride;
4934 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4935 /// to be used, with the given qualifiers on the current class type.
4936 class CXXThisScopeRAII {
4938 QualType OldCXXThisTypeOverride;
4942 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4943 /// using the given declaration (which is either a class template or a
4944 /// class) along with the given qualifiers.
4945 /// along with the qualifiers placed on '*this'.
4946 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4947 bool Enabled = true);
4949 ~CXXThisScopeRAII();
4952 /// \brief Make sure the value of 'this' is actually available in the current
4953 /// context, if it is a potentially evaluated context.
4955 /// \param Loc The location at which the capture of 'this' occurs.
4957 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4960 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4961 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4962 /// This is useful when enclosing lambdas must speculatively capture
4963 /// 'this' that may or may not be used in certain specializations of
4964 /// a nested generic lambda (depending on whether the name resolves to
4965 /// a non-static member function or a static function).
4966 /// \return returns 'true' if failed, 'false' if success.
4967 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4968 bool BuildAndDiagnose = true,
4969 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4970 bool ByCopy = false);
4972 /// \brief Determine whether the given type is the type of *this that is used
4973 /// outside of the body of a member function for a type that is currently
4975 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4977 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4978 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4981 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4982 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4985 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4986 SourceLocation AtLoc, SourceLocation RParen);
4988 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4989 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4991 //// ActOnCXXThrow - Parse throw expressions.
4992 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4993 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4994 bool IsThrownVarInScope);
4995 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4997 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4998 /// Can be interpreted either as function-style casting ("int(x)")
4999 /// or class type construction ("ClassType(x,y,z)")
5000 /// or creation of a value-initialized type ("int()").
5001 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5002 SourceLocation LParenLoc,
5004 SourceLocation RParenLoc);
5006 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5007 SourceLocation LParenLoc,
5009 SourceLocation RParenLoc);
5011 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5012 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5013 SourceLocation PlacementLParen,
5014 MultiExprArg PlacementArgs,
5015 SourceLocation PlacementRParen,
5016 SourceRange TypeIdParens, Declarator &D,
5018 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5019 SourceLocation PlacementLParen,
5020 MultiExprArg PlacementArgs,
5021 SourceLocation PlacementRParen,
5022 SourceRange TypeIdParens,
5024 TypeSourceInfo *AllocTypeInfo,
5026 SourceRange DirectInitRange,
5029 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5031 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5032 bool UseGlobal, QualType AllocType, bool IsArray,
5033 bool &PassAlignment, MultiExprArg PlaceArgs,
5034 FunctionDecl *&OperatorNew,
5035 FunctionDecl *&OperatorDelete);
5036 void DeclareGlobalNewDelete();
5037 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5038 ArrayRef<QualType> Params);
5040 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5041 DeclarationName Name, FunctionDecl* &Operator,
5042 bool Diagnose = true);
5043 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5044 bool CanProvideSize,
5046 DeclarationName Name);
5047 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5050 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5051 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5052 bool UseGlobal, bool ArrayForm,
5054 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5055 bool IsDelete, bool CallCanBeVirtual,
5056 bool WarnOnNonAbstractTypes,
5057 SourceLocation DtorLoc);
5059 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5060 Expr *Operand, SourceLocation RParen);
5061 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5062 SourceLocation RParen);
5064 /// \brief Parsed one of the type trait support pseudo-functions.
5065 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5066 ArrayRef<ParsedType> Args,
5067 SourceLocation RParenLoc);
5068 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5069 ArrayRef<TypeSourceInfo *> Args,
5070 SourceLocation RParenLoc);
5072 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5073 /// pseudo-functions.
5074 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5075 SourceLocation KWLoc,
5078 SourceLocation RParen);
5080 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5081 SourceLocation KWLoc,
5082 TypeSourceInfo *TSInfo,
5084 SourceLocation RParen);
5086 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5087 /// pseudo-functions.
5088 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5089 SourceLocation KWLoc,
5091 SourceLocation RParen);
5093 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5094 SourceLocation KWLoc,
5096 SourceLocation RParen);
5098 ExprResult ActOnStartCXXMemberReference(Scope *S,
5100 SourceLocation OpLoc,
5101 tok::TokenKind OpKind,
5102 ParsedType &ObjectType,
5103 bool &MayBePseudoDestructor);
5105 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5106 SourceLocation OpLoc,
5107 tok::TokenKind OpKind,
5108 const CXXScopeSpec &SS,
5109 TypeSourceInfo *ScopeType,
5110 SourceLocation CCLoc,
5111 SourceLocation TildeLoc,
5112 PseudoDestructorTypeStorage DestroyedType);
5114 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5115 SourceLocation OpLoc,
5116 tok::TokenKind OpKind,
5118 UnqualifiedId &FirstTypeName,
5119 SourceLocation CCLoc,
5120 SourceLocation TildeLoc,
5121 UnqualifiedId &SecondTypeName);
5123 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5124 SourceLocation OpLoc,
5125 tok::TokenKind OpKind,
5126 SourceLocation TildeLoc,
5127 const DeclSpec& DS);
5129 /// MaybeCreateExprWithCleanups - If the current full-expression
5130 /// requires any cleanups, surround it with a ExprWithCleanups node.
5131 /// Otherwise, just returns the passed-in expression.
5132 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5133 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5134 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5136 MaterializeTemporaryExpr *
5137 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5138 bool BoundToLvalueReference);
5140 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5141 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5142 : SourceLocation());
5144 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5145 bool DiscardedValue = false,
5146 bool IsConstexpr = false,
5147 bool IsLambdaInitCaptureInitializer = false);
5148 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5150 // Marks SS invalid if it represents an incomplete type.
5151 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5153 DeclContext *computeDeclContext(QualType T);
5154 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5155 bool EnteringContext = false);
5156 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5157 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5159 /// \brief The parser has parsed a global nested-name-specifier '::'.
5161 /// \param CCLoc The location of the '::'.
5163 /// \param SS The nested-name-specifier, which will be updated in-place
5164 /// to reflect the parsed nested-name-specifier.
5166 /// \returns true if an error occurred, false otherwise.
5167 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5169 /// \brief The parser has parsed a '__super' nested-name-specifier.
5171 /// \param SuperLoc The location of the '__super' keyword.
5173 /// \param ColonColonLoc The location of the '::'.
5175 /// \param SS The nested-name-specifier, which will be updated in-place
5176 /// to reflect the parsed nested-name-specifier.
5178 /// \returns true if an error occurred, false otherwise.
5179 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5180 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5182 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5183 bool *CanCorrect = nullptr);
5184 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5186 /// \brief Keeps information about an identifier in a nested-name-spec.
5188 struct NestedNameSpecInfo {
5189 /// \brief The type of the object, if we're parsing nested-name-specifier in
5190 /// a member access expression.
5191 ParsedType ObjectType;
5193 /// \brief The identifier preceding the '::'.
5194 IdentifierInfo *Identifier;
5196 /// \brief The location of the identifier.
5197 SourceLocation IdentifierLoc;
5199 /// \brief The location of the '::'.
5200 SourceLocation CCLoc;
5202 /// \brief Creates info object for the most typical case.
5203 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5204 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5205 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5206 CCLoc(ColonColonLoc) {
5209 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5210 SourceLocation ColonColonLoc, QualType ObjectType)
5211 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5212 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5216 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5217 NestedNameSpecInfo &IdInfo);
5219 bool BuildCXXNestedNameSpecifier(Scope *S,
5220 NestedNameSpecInfo &IdInfo,
5221 bool EnteringContext,
5223 NamedDecl *ScopeLookupResult,
5224 bool ErrorRecoveryLookup,
5225 bool *IsCorrectedToColon = nullptr,
5226 bool OnlyNamespace = false);
5228 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5230 /// \param S The scope in which this nested-name-specifier occurs.
5232 /// \param IdInfo Parser information about an identifier in the
5233 /// nested-name-spec.
5235 /// \param EnteringContext Whether we're entering the context nominated by
5236 /// this nested-name-specifier.
5238 /// \param SS The nested-name-specifier, which is both an input
5239 /// parameter (the nested-name-specifier before this type) and an
5240 /// output parameter (containing the full nested-name-specifier,
5241 /// including this new type).
5243 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5244 /// error recovery. In this case do not emit error message.
5246 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5247 /// are allowed. The bool value pointed by this parameter is set to 'true'
5248 /// if the identifier is treated as if it was followed by ':', not '::'.
5250 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5252 /// \returns true if an error occurred, false otherwise.
5253 bool ActOnCXXNestedNameSpecifier(Scope *S,
5254 NestedNameSpecInfo &IdInfo,
5255 bool EnteringContext,
5257 bool ErrorRecoveryLookup = false,
5258 bool *IsCorrectedToColon = nullptr,
5259 bool OnlyNamespace = false);
5261 ExprResult ActOnDecltypeExpression(Expr *E);
5263 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5265 SourceLocation ColonColonLoc);
5267 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5268 NestedNameSpecInfo &IdInfo,
5269 bool EnteringContext);
5271 /// \brief The parser has parsed a nested-name-specifier
5272 /// 'template[opt] template-name < template-args >::'.
5274 /// \param S The scope in which this nested-name-specifier occurs.
5276 /// \param SS The nested-name-specifier, which is both an input
5277 /// parameter (the nested-name-specifier before this type) and an
5278 /// output parameter (containing the full nested-name-specifier,
5279 /// including this new type).
5281 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5282 /// \param TemplateName the template name.
5283 /// \param TemplateNameLoc The location of the template name.
5284 /// \param LAngleLoc The location of the opening angle bracket ('<').
5285 /// \param TemplateArgs The template arguments.
5286 /// \param RAngleLoc The location of the closing angle bracket ('>').
5287 /// \param CCLoc The location of the '::'.
5289 /// \param EnteringContext Whether we're entering the context of the
5290 /// nested-name-specifier.
5293 /// \returns true if an error occurred, false otherwise.
5294 bool ActOnCXXNestedNameSpecifier(Scope *S,
5296 SourceLocation TemplateKWLoc,
5297 TemplateTy TemplateName,
5298 SourceLocation TemplateNameLoc,
5299 SourceLocation LAngleLoc,
5300 ASTTemplateArgsPtr TemplateArgs,
5301 SourceLocation RAngleLoc,
5302 SourceLocation CCLoc,
5303 bool EnteringContext);
5305 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5306 /// that the parser can use later to reconstruct the given
5307 /// nested-name-specifier.
5309 /// \param SS A nested-name-specifier.
5311 /// \returns A pointer containing all of the information in the
5312 /// nested-name-specifier \p SS.
5313 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5315 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5316 /// the nested-name-specifier structure.
5318 /// \param Annotation The annotation pointer, produced by
5319 /// \c SaveNestedNameSpecifierAnnotation().
5321 /// \param AnnotationRange The source range corresponding to the annotation.
5323 /// \param SS The nested-name-specifier that will be updated with the contents
5324 /// of the annotation pointer.
5325 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5326 SourceRange AnnotationRange,
5329 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5331 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5332 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5333 /// After this method is called, according to [C++ 3.4.3p3], names should be
5334 /// looked up in the declarator-id's scope, until the declarator is parsed and
5335 /// ActOnCXXExitDeclaratorScope is called.
5336 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5337 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5339 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5340 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5341 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5342 /// Used to indicate that names should revert to being looked up in the
5344 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5346 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5347 /// initializer for the declaration 'Dcl'.
5348 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5349 /// static data member of class X, names should be looked up in the scope of
5351 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5353 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5354 /// initializer for the declaration 'Dcl'.
5355 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5357 /// \brief Create a new lambda closure type.
5358 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5359 TypeSourceInfo *Info,
5360 bool KnownDependent,
5361 LambdaCaptureDefault CaptureDefault);
5363 /// \brief Start the definition of a lambda expression.
5364 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5365 SourceRange IntroducerRange,
5366 TypeSourceInfo *MethodType,
5367 SourceLocation EndLoc,
5368 ArrayRef<ParmVarDecl *> Params,
5369 bool IsConstexprSpecified);
5371 /// \brief Endow the lambda scope info with the relevant properties.
5372 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5373 CXXMethodDecl *CallOperator,
5374 SourceRange IntroducerRange,
5375 LambdaCaptureDefault CaptureDefault,
5376 SourceLocation CaptureDefaultLoc,
5377 bool ExplicitParams,
5378 bool ExplicitResultType,
5381 /// \brief Perform initialization analysis of the init-capture and perform
5382 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5383 /// not being used to initialize a reference.
5384 ParsedType actOnLambdaInitCaptureInitialization(
5385 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5386 LambdaCaptureInitKind InitKind, Expr *&Init) {
5387 return ParsedType::make(buildLambdaInitCaptureInitialization(
5388 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5390 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5392 bool DirectInit, Expr *&Init);
5394 /// \brief Create a dummy variable within the declcontext of the lambda's
5395 /// call operator, for name lookup purposes for a lambda init capture.
5397 /// CodeGen handles emission of lambda captures, ignoring these dummy
5398 /// variables appropriately.
5399 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5400 QualType InitCaptureType,
5402 unsigned InitStyle, Expr *Init);
5404 /// \brief Build the implicit field for an init-capture.
5405 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5407 /// \brief Note that we have finished the explicit captures for the
5409 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5411 /// \brief Introduce the lambda parameters into scope.
5412 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5414 /// \brief Deduce a block or lambda's return type based on the return
5415 /// statements present in the body.
5416 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5418 /// ActOnStartOfLambdaDefinition - This is called just before we start
5419 /// parsing the body of a lambda; it analyzes the explicit captures and
5420 /// arguments, and sets up various data-structures for the body of the
5422 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5423 Declarator &ParamInfo, Scope *CurScope);
5425 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5426 /// is invoked to pop the information about the lambda.
5427 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5428 bool IsInstantiation = false);
5430 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5431 /// was successfully completed.
5432 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5435 /// \brief Does copying/destroying the captured variable have side effects?
5436 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5438 /// \brief Diagnose if an explicit lambda capture is unused.
5439 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5441 /// \brief Complete a lambda-expression having processed and attached the
5443 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5444 sema::LambdaScopeInfo *LSI);
5446 /// \brief Define the "body" of the conversion from a lambda object to a
5447 /// function pointer.
5449 /// This routine doesn't actually define a sensible body; rather, it fills
5450 /// in the initialization expression needed to copy the lambda object into
5451 /// the block, and IR generation actually generates the real body of the
5452 /// block pointer conversion.
5453 void DefineImplicitLambdaToFunctionPointerConversion(
5454 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5456 /// \brief Define the "body" of the conversion from a lambda object to a
5459 /// This routine doesn't actually define a sensible body; rather, it fills
5460 /// in the initialization expression needed to copy the lambda object into
5461 /// the block, and IR generation actually generates the real body of the
5462 /// block pointer conversion.
5463 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5464 CXXConversionDecl *Conv);
5466 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5467 SourceLocation ConvLocation,
5468 CXXConversionDecl *Conv,
5471 // ParseObjCStringLiteral - Parse Objective-C string literals.
5472 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5473 ArrayRef<Expr *> Strings);
5475 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5477 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5478 /// numeric literal expression. Type of the expression will be "NSNumber *"
5479 /// or "id" if NSNumber is unavailable.
5480 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5481 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5483 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5485 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5486 /// '@' prefixed parenthesized expression. The type of the expression will
5487 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5488 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5489 /// "const char *" or C structure with attribute 'objc_boxable'.
5490 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5492 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5494 ObjCMethodDecl *getterMethod,
5495 ObjCMethodDecl *setterMethod);
5497 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5498 MutableArrayRef<ObjCDictionaryElement> Elements);
5500 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5501 TypeSourceInfo *EncodedTypeInfo,
5502 SourceLocation RParenLoc);
5503 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5504 CXXConversionDecl *Method,
5505 bool HadMultipleCandidates);
5507 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5508 SourceLocation EncodeLoc,
5509 SourceLocation LParenLoc,
5511 SourceLocation RParenLoc);
5513 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5514 ExprResult ParseObjCSelectorExpression(Selector Sel,
5515 SourceLocation AtLoc,
5516 SourceLocation SelLoc,
5517 SourceLocation LParenLoc,
5518 SourceLocation RParenLoc,
5519 bool WarnMultipleSelectors);
5521 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5522 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5523 SourceLocation AtLoc,
5524 SourceLocation ProtoLoc,
5525 SourceLocation LParenLoc,
5526 SourceLocation ProtoIdLoc,
5527 SourceLocation RParenLoc);
5529 //===--------------------------------------------------------------------===//
5532 Decl *ActOnStartLinkageSpecification(Scope *S,
5533 SourceLocation ExternLoc,
5535 SourceLocation LBraceLoc);
5536 Decl *ActOnFinishLinkageSpecification(Scope *S,
5538 SourceLocation RBraceLoc);
5541 //===--------------------------------------------------------------------===//
5544 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5545 const CXXScopeSpec *SS = nullptr);
5546 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5548 bool ActOnAccessSpecifier(AccessSpecifier Access,
5549 SourceLocation ASLoc,
5550 SourceLocation ColonLoc,
5551 AttributeList *Attrs = nullptr);
5553 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5555 MultiTemplateParamsArg TemplateParameterLists,
5556 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5557 InClassInitStyle InitStyle);
5559 void ActOnStartCXXInClassMemberInitializer();
5560 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5561 SourceLocation EqualLoc,
5564 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5567 IdentifierInfo *MemberOrBase,
5568 ParsedType TemplateTypeTy,
5570 SourceLocation IdLoc,
5571 SourceLocation LParenLoc,
5572 ArrayRef<Expr *> Args,
5573 SourceLocation RParenLoc,
5574 SourceLocation EllipsisLoc);
5576 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5579 IdentifierInfo *MemberOrBase,
5580 ParsedType TemplateTypeTy,
5582 SourceLocation IdLoc,
5584 SourceLocation EllipsisLoc);
5586 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5589 IdentifierInfo *MemberOrBase,
5590 ParsedType TemplateTypeTy,
5592 SourceLocation IdLoc,
5594 SourceLocation EllipsisLoc);
5596 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5598 SourceLocation IdLoc);
5600 MemInitResult BuildBaseInitializer(QualType BaseType,
5601 TypeSourceInfo *BaseTInfo,
5603 CXXRecordDecl *ClassDecl,
5604 SourceLocation EllipsisLoc);
5606 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5608 CXXRecordDecl *ClassDecl);
5610 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5611 CXXCtorInitializer *Initializer);
5613 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5614 ArrayRef<CXXCtorInitializer *> Initializers = None);
5616 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5619 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5620 /// mark all the non-trivial destructors of its members and bases as
5622 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5623 CXXRecordDecl *Record);
5625 /// \brief The list of classes whose vtables have been used within
5626 /// this translation unit, and the source locations at which the
5627 /// first use occurred.
5628 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5630 /// \brief The list of vtables that are required but have not yet been
5632 SmallVector<VTableUse, 16> VTableUses;
5634 /// \brief The set of classes whose vtables have been used within
5635 /// this translation unit, and a bit that will be true if the vtable is
5636 /// required to be emitted (otherwise, it should be emitted only if needed
5637 /// by code generation).
5638 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5640 /// \brief Load any externally-stored vtable uses.
5641 void LoadExternalVTableUses();
5643 /// \brief Note that the vtable for the given class was used at the
5645 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5646 bool DefinitionRequired = false);
5648 /// \brief Mark the exception specifications of all virtual member functions
5649 /// in the given class as needed.
5650 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5651 const CXXRecordDecl *RD);
5653 /// MarkVirtualMembersReferenced - Will mark all members of the given
5654 /// CXXRecordDecl referenced.
5655 void MarkVirtualMembersReferenced(SourceLocation Loc,
5656 const CXXRecordDecl *RD);
5658 /// \brief Define all of the vtables that have been used in this
5659 /// translation unit and reference any virtual members used by those
5662 /// \returns true if any work was done, false otherwise.
5663 bool DefineUsedVTables();
5665 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5667 void ActOnMemInitializers(Decl *ConstructorDecl,
5668 SourceLocation ColonLoc,
5669 ArrayRef<CXXCtorInitializer*> MemInits,
5672 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5673 /// ensure that referenceDLLExportedClassMethods is called some point later
5674 /// when all outer classes of Class are complete.
5675 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5677 void referenceDLLExportedClassMethods();
5679 void propagateDLLAttrToBaseClassTemplate(
5680 CXXRecordDecl *Class, Attr *ClassAttr,
5681 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5682 SourceLocation BaseLoc);
5684 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5685 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5687 SourceLocation LBrac,
5688 SourceLocation RBrac,
5689 AttributeList *AttrList);
5690 void ActOnFinishCXXMemberDecls();
5691 void ActOnFinishCXXNonNestedClass(Decl *D);
5693 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5694 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5695 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5696 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5697 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5698 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5699 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5700 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5701 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5702 CachedTokens &Toks);
5703 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5704 bool IsInsideALocalClassWithinATemplateFunction();
5706 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5708 Expr *AssertMessageExpr,
5709 SourceLocation RParenLoc);
5710 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5712 StringLiteral *AssertMessageExpr,
5713 SourceLocation RParenLoc,
5716 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5717 SourceLocation FriendLoc,
5718 TypeSourceInfo *TSInfo);
5719 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5720 MultiTemplateParamsArg TemplateParams);
5721 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5722 MultiTemplateParamsArg TemplateParams);
5724 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5726 void CheckConstructor(CXXConstructorDecl *Constructor);
5727 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5729 bool CheckDestructor(CXXDestructorDecl *Destructor);
5730 void CheckConversionDeclarator(Declarator &D, QualType &R,
5732 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5733 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5735 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5737 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5738 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5739 const FunctionProtoType *T);
5740 void CheckDelayedMemberExceptionSpecs();
5742 //===--------------------------------------------------------------------===//
5743 // C++ Derived Classes
5746 /// ActOnBaseSpecifier - Parsed a base specifier
5747 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5748 SourceRange SpecifierRange,
5749 bool Virtual, AccessSpecifier Access,
5750 TypeSourceInfo *TInfo,
5751 SourceLocation EllipsisLoc);
5753 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5754 SourceRange SpecifierRange,
5755 ParsedAttributes &Attrs,
5756 bool Virtual, AccessSpecifier Access,
5757 ParsedType basetype,
5758 SourceLocation BaseLoc,
5759 SourceLocation EllipsisLoc);
5761 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5762 MutableArrayRef<CXXBaseSpecifier *> Bases);
5763 void ActOnBaseSpecifiers(Decl *ClassDecl,
5764 MutableArrayRef<CXXBaseSpecifier *> Bases);
5766 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5767 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5768 CXXBasePaths &Paths);
5770 // FIXME: I don't like this name.
5771 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5773 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5774 SourceLocation Loc, SourceRange Range,
5775 CXXCastPath *BasePath = nullptr,
5776 bool IgnoreAccess = false);
5777 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5778 unsigned InaccessibleBaseID,
5779 unsigned AmbigiousBaseConvID,
5780 SourceLocation Loc, SourceRange Range,
5781 DeclarationName Name,
5782 CXXCastPath *BasePath,
5783 bool IgnoreAccess = false);
5785 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5787 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5788 const CXXMethodDecl *Old);
5790 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5791 /// covariant, according to C++ [class.virtual]p5.
5792 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5793 const CXXMethodDecl *Old);
5795 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5796 /// spec is a subset of base spec.
5797 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5798 const CXXMethodDecl *Old);
5800 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5802 /// CheckOverrideControl - Check C++11 override control semantics.
5803 void CheckOverrideControl(NamedDecl *D);
5805 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5806 /// not used in the declaration of an overriding method.
5807 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5809 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5810 /// overrides a virtual member function marked 'final', according to
5811 /// C++11 [class.virtual]p4.
5812 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5813 const CXXMethodDecl *Old);
5816 //===--------------------------------------------------------------------===//
5817 // C++ Access Control
5827 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5828 NamedDecl *PrevMemberDecl,
5829 AccessSpecifier LexicalAS);
5831 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5832 DeclAccessPair FoundDecl);
5833 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5834 DeclAccessPair FoundDecl);
5835 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5836 SourceRange PlacementRange,
5837 CXXRecordDecl *NamingClass,
5838 DeclAccessPair FoundDecl,
5839 bool Diagnose = true);
5840 AccessResult CheckConstructorAccess(SourceLocation Loc,
5841 CXXConstructorDecl *D,
5842 DeclAccessPair FoundDecl,
5843 const InitializedEntity &Entity,
5844 bool IsCopyBindingRefToTemp = false);
5845 AccessResult CheckConstructorAccess(SourceLocation Loc,
5846 CXXConstructorDecl *D,
5847 DeclAccessPair FoundDecl,
5848 const InitializedEntity &Entity,
5849 const PartialDiagnostic &PDiag);
5850 AccessResult CheckDestructorAccess(SourceLocation Loc,
5851 CXXDestructorDecl *Dtor,
5852 const PartialDiagnostic &PDiag,
5853 QualType objectType = QualType());
5854 AccessResult CheckFriendAccess(NamedDecl *D);
5855 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5856 CXXRecordDecl *NamingClass,
5857 DeclAccessPair Found);
5858 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5861 DeclAccessPair FoundDecl);
5862 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5863 DeclAccessPair FoundDecl);
5864 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5865 QualType Base, QualType Derived,
5866 const CXXBasePath &Path,
5868 bool ForceCheck = false,
5869 bool ForceUnprivileged = false);
5870 void CheckLookupAccess(const LookupResult &R);
5871 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5872 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5873 AccessSpecifier access,
5874 QualType objectType);
5876 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5877 const MultiLevelTemplateArgumentList &TemplateArgs);
5878 void PerformDependentDiagnostics(const DeclContext *Pattern,
5879 const MultiLevelTemplateArgumentList &TemplateArgs);
5881 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5883 /// \brief When true, access checking violations are treated as SFINAE
5884 /// failures rather than hard errors.
5885 bool AccessCheckingSFINAE;
5887 enum AbstractDiagSelID {
5891 AbstractVariableType,
5894 AbstractSynthesizedIvarType,
5898 bool isAbstractType(SourceLocation Loc, QualType T);
5899 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5900 TypeDiagnoser &Diagnoser);
5901 template <typename... Ts>
5902 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5903 const Ts &...Args) {
5904 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5905 return RequireNonAbstractType(Loc, T, Diagnoser);
5908 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5910 //===--------------------------------------------------------------------===//
5911 // C++ Overloaded Operators [C++ 13.5]
5914 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5916 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5918 //===--------------------------------------------------------------------===//
5919 // C++ Templates [C++ 14]
5921 void FilterAcceptableTemplateNames(LookupResult &R,
5922 bool AllowFunctionTemplates = true);
5923 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5924 bool AllowFunctionTemplates = true);
5926 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5927 QualType ObjectType, bool EnteringContext,
5928 bool &MemberOfUnknownSpecialization);
5930 TemplateNameKind isTemplateName(Scope *S,
5932 bool hasTemplateKeyword,
5933 UnqualifiedId &Name,
5934 ParsedType ObjectType,
5935 bool EnteringContext,
5936 TemplateTy &Template,
5937 bool &MemberOfUnknownSpecialization);
5939 /// Determine whether a particular identifier might be the name in a C++1z
5940 /// deduction-guide declaration.
5941 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5942 SourceLocation NameLoc,
5943 ParsedTemplateTy *Template = nullptr);
5945 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5946 SourceLocation IILoc,
5948 const CXXScopeSpec *SS,
5949 TemplateTy &SuggestedTemplate,
5950 TemplateNameKind &SuggestedKind);
5952 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5953 NamedDecl *Instantiation,
5954 bool InstantiatedFromMember,
5955 const NamedDecl *Pattern,
5956 const NamedDecl *PatternDef,
5957 TemplateSpecializationKind TSK,
5958 bool Complain = true);
5960 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5961 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5963 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5964 SourceLocation EllipsisLoc,
5965 SourceLocation KeyLoc,
5966 IdentifierInfo *ParamName,
5967 SourceLocation ParamNameLoc,
5968 unsigned Depth, unsigned Position,
5969 SourceLocation EqualLoc,
5970 ParsedType DefaultArg);
5972 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5973 SourceLocation Loc);
5974 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5976 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5979 SourceLocation EqualLoc,
5981 Decl *ActOnTemplateTemplateParameter(Scope *S,
5982 SourceLocation TmpLoc,
5983 TemplateParameterList *Params,
5984 SourceLocation EllipsisLoc,
5985 IdentifierInfo *ParamName,
5986 SourceLocation ParamNameLoc,
5989 SourceLocation EqualLoc,
5990 ParsedTemplateArgument DefaultArg);
5992 TemplateParameterList *
5993 ActOnTemplateParameterList(unsigned Depth,
5994 SourceLocation ExportLoc,
5995 SourceLocation TemplateLoc,
5996 SourceLocation LAngleLoc,
5997 ArrayRef<Decl *> Params,
5998 SourceLocation RAngleLoc,
5999 Expr *RequiresClause);
6001 /// \brief The context in which we are checking a template parameter list.
6002 enum TemplateParamListContext {
6005 TPC_FunctionTemplate,
6006 TPC_ClassTemplateMember,
6007 TPC_FriendClassTemplate,
6008 TPC_FriendFunctionTemplate,
6009 TPC_FriendFunctionTemplateDefinition,
6010 TPC_TypeAliasTemplate
6013 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6014 TemplateParameterList *OldParams,
6015 TemplateParamListContext TPC);
6016 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6017 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6018 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6019 ArrayRef<TemplateParameterList *> ParamLists,
6020 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6022 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6023 SourceLocation KWLoc, CXXScopeSpec &SS,
6024 IdentifierInfo *Name, SourceLocation NameLoc,
6025 AttributeList *Attr,
6026 TemplateParameterList *TemplateParams,
6028 SourceLocation ModulePrivateLoc,
6029 SourceLocation FriendLoc,
6030 unsigned NumOuterTemplateParamLists,
6031 TemplateParameterList **OuterTemplateParamLists,
6032 SkipBodyInfo *SkipBody = nullptr);
6034 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6036 SourceLocation Loc);
6038 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6039 TemplateArgumentListInfo &Out);
6041 void NoteAllFoundTemplates(TemplateName Name);
6043 QualType CheckTemplateIdType(TemplateName Template,
6044 SourceLocation TemplateLoc,
6045 TemplateArgumentListInfo &TemplateArgs);
6048 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6049 TemplateTy Template, IdentifierInfo *TemplateII,
6050 SourceLocation TemplateIILoc,
6051 SourceLocation LAngleLoc,
6052 ASTTemplateArgsPtr TemplateArgs,
6053 SourceLocation RAngleLoc,
6054 bool IsCtorOrDtorName = false,
6055 bool IsClassName = false);
6057 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6058 /// such as \c class T::template apply<U>.
6059 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6060 TypeSpecifierType TagSpec,
6061 SourceLocation TagLoc,
6063 SourceLocation TemplateKWLoc,
6064 TemplateTy TemplateD,
6065 SourceLocation TemplateLoc,
6066 SourceLocation LAngleLoc,
6067 ASTTemplateArgsPtr TemplateArgsIn,
6068 SourceLocation RAngleLoc);
6070 DeclResult ActOnVarTemplateSpecialization(
6071 Scope *S, Declarator &D, TypeSourceInfo *DI,
6072 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6073 StorageClass SC, bool IsPartialSpecialization);
6075 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6076 SourceLocation TemplateLoc,
6077 SourceLocation TemplateNameLoc,
6078 const TemplateArgumentListInfo &TemplateArgs);
6080 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6081 const DeclarationNameInfo &NameInfo,
6082 VarTemplateDecl *Template,
6083 SourceLocation TemplateLoc,
6084 const TemplateArgumentListInfo *TemplateArgs);
6086 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6087 SourceLocation TemplateKWLoc,
6090 const TemplateArgumentListInfo *TemplateArgs);
6092 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6093 SourceLocation TemplateKWLoc,
6094 const DeclarationNameInfo &NameInfo,
6095 const TemplateArgumentListInfo *TemplateArgs);
6097 TemplateNameKind ActOnDependentTemplateName(
6098 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6099 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6100 TemplateTy &Template, bool AllowInjectedClassName = false);
6103 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6104 SourceLocation KWLoc,
6105 SourceLocation ModulePrivateLoc,
6106 TemplateIdAnnotation &TemplateId,
6107 AttributeList *Attr,
6108 MultiTemplateParamsArg TemplateParameterLists,
6109 SkipBodyInfo *SkipBody = nullptr);
6111 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6112 TemplateDecl *PrimaryTemplate,
6113 unsigned NumExplicitArgs,
6114 ArrayRef<TemplateArgument> Args);
6115 void CheckTemplatePartialSpecialization(
6116 ClassTemplatePartialSpecializationDecl *Partial);
6117 void CheckTemplatePartialSpecialization(
6118 VarTemplatePartialSpecializationDecl *Partial);
6120 Decl *ActOnTemplateDeclarator(Scope *S,
6121 MultiTemplateParamsArg TemplateParameterLists,
6125 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6126 TemplateSpecializationKind NewTSK,
6127 NamedDecl *PrevDecl,
6128 TemplateSpecializationKind PrevTSK,
6129 SourceLocation PrevPtOfInstantiation,
6132 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6133 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6134 LookupResult &Previous);
6136 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6137 TemplateArgumentListInfo *ExplicitTemplateArgs,
6138 LookupResult &Previous);
6139 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6140 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6143 ActOnExplicitInstantiation(Scope *S,
6144 SourceLocation ExternLoc,
6145 SourceLocation TemplateLoc,
6147 SourceLocation KWLoc,
6148 const CXXScopeSpec &SS,
6149 TemplateTy Template,
6150 SourceLocation TemplateNameLoc,
6151 SourceLocation LAngleLoc,
6152 ASTTemplateArgsPtr TemplateArgs,
6153 SourceLocation RAngleLoc,
6154 AttributeList *Attr);
6157 ActOnExplicitInstantiation(Scope *S,
6158 SourceLocation ExternLoc,
6159 SourceLocation TemplateLoc,
6161 SourceLocation KWLoc,
6163 IdentifierInfo *Name,
6164 SourceLocation NameLoc,
6165 AttributeList *Attr);
6167 DeclResult ActOnExplicitInstantiation(Scope *S,
6168 SourceLocation ExternLoc,
6169 SourceLocation TemplateLoc,
6173 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6174 SourceLocation TemplateLoc,
6175 SourceLocation RAngleLoc,
6177 SmallVectorImpl<TemplateArgument>
6179 bool &HasDefaultArg);
6181 /// \brief Specifies the context in which a particular template
6182 /// argument is being checked.
6183 enum CheckTemplateArgumentKind {
6184 /// \brief The template argument was specified in the code or was
6185 /// instantiated with some deduced template arguments.
6188 /// \brief The template argument was deduced via template argument
6192 /// \brief The template argument was deduced from an array bound
6193 /// via template argument deduction.
6194 CTAK_DeducedFromArrayBound
6197 bool CheckTemplateArgument(NamedDecl *Param,
6198 TemplateArgumentLoc &Arg,
6199 NamedDecl *Template,
6200 SourceLocation TemplateLoc,
6201 SourceLocation RAngleLoc,
6202 unsigned ArgumentPackIndex,
6203 SmallVectorImpl<TemplateArgument> &Converted,
6204 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6206 /// \brief Check that the given template arguments can be be provided to
6207 /// the given template, converting the arguments along the way.
6209 /// \param Template The template to which the template arguments are being
6212 /// \param TemplateLoc The location of the template name in the source.
6214 /// \param TemplateArgs The list of template arguments. If the template is
6215 /// a template template parameter, this function may extend the set of
6216 /// template arguments to also include substituted, defaulted template
6219 /// \param PartialTemplateArgs True if the list of template arguments is
6220 /// intentionally partial, e.g., because we're checking just the initial
6221 /// set of template arguments.
6223 /// \param Converted Will receive the converted, canonicalized template
6226 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6227 /// contain the converted forms of the template arguments as written.
6228 /// Otherwise, \p TemplateArgs will not be modified.
6230 /// \returns true if an error occurred, false otherwise.
6231 bool CheckTemplateArgumentList(TemplateDecl *Template,
6232 SourceLocation TemplateLoc,
6233 TemplateArgumentListInfo &TemplateArgs,
6234 bool PartialTemplateArgs,
6235 SmallVectorImpl<TemplateArgument> &Converted,
6236 bool UpdateArgsWithConversions = true);
6238 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6239 TemplateArgumentLoc &Arg,
6240 SmallVectorImpl<TemplateArgument> &Converted);
6242 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6243 TypeSourceInfo *Arg);
6244 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6245 QualType InstantiatedParamType, Expr *Arg,
6246 TemplateArgument &Converted,
6247 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6248 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6249 TemplateArgumentLoc &Arg,
6250 unsigned ArgumentPackIndex);
6253 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6255 SourceLocation Loc);
6257 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6258 SourceLocation Loc);
6260 /// \brief Enumeration describing how template parameter lists are compared
6262 enum TemplateParameterListEqualKind {
6263 /// \brief We are matching the template parameter lists of two templates
6264 /// that might be redeclarations.
6267 /// template<typename T> struct X;
6268 /// template<typename T> struct X;
6272 /// \brief We are matching the template parameter lists of two template
6273 /// template parameters as part of matching the template parameter lists
6274 /// of two templates that might be redeclarations.
6277 /// template<template<int I> class TT> struct X;
6278 /// template<template<int Value> class Other> struct X;
6280 TPL_TemplateTemplateParmMatch,
6282 /// \brief We are matching the template parameter lists of a template
6283 /// template argument against the template parameter lists of a template
6284 /// template parameter.
6287 /// template<template<int Value> class Metafun> struct X;
6288 /// template<int Value> struct integer_c;
6289 /// X<integer_c> xic;
6291 TPL_TemplateTemplateArgumentMatch
6294 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6295 TemplateParameterList *Old,
6297 TemplateParameterListEqualKind Kind,
6298 SourceLocation TemplateArgLoc
6299 = SourceLocation());
6301 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6303 /// \brief Called when the parser has parsed a C++ typename
6304 /// specifier, e.g., "typename T::type".
6306 /// \param S The scope in which this typename type occurs.
6307 /// \param TypenameLoc the location of the 'typename' keyword
6308 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6309 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6310 /// \param IdLoc the location of the identifier.
6312 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6313 const CXXScopeSpec &SS, const IdentifierInfo &II,
6314 SourceLocation IdLoc);
6316 /// \brief Called when the parser has parsed a C++ typename
6317 /// specifier that ends in a template-id, e.g.,
6318 /// "typename MetaFun::template apply<T1, T2>".
6320 /// \param S The scope in which this typename type occurs.
6321 /// \param TypenameLoc the location of the 'typename' keyword
6322 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6323 /// \param TemplateLoc the location of the 'template' keyword, if any.
6324 /// \param TemplateName The template name.
6325 /// \param TemplateII The identifier used to name the template.
6326 /// \param TemplateIILoc The location of the template name.
6327 /// \param LAngleLoc The location of the opening angle bracket ('<').
6328 /// \param TemplateArgs The template arguments.
6329 /// \param RAngleLoc The location of the closing angle bracket ('>').
6331 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6332 const CXXScopeSpec &SS,
6333 SourceLocation TemplateLoc,
6334 TemplateTy TemplateName,
6335 IdentifierInfo *TemplateII,
6336 SourceLocation TemplateIILoc,
6337 SourceLocation LAngleLoc,
6338 ASTTemplateArgsPtr TemplateArgs,
6339 SourceLocation RAngleLoc);
6341 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6342 SourceLocation KeywordLoc,
6343 NestedNameSpecifierLoc QualifierLoc,
6344 const IdentifierInfo &II,
6345 SourceLocation IILoc);
6347 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6349 DeclarationName Name);
6350 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6352 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6353 bool RebuildTemplateParamsInCurrentInstantiation(
6354 TemplateParameterList *Params);
6357 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6358 const TemplateArgumentList &Args);
6361 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6362 const TemplateArgument *Args,
6365 //===--------------------------------------------------------------------===//
6366 // C++ Variadic Templates (C++0x [temp.variadic])
6367 //===--------------------------------------------------------------------===//
6369 /// Determine whether an unexpanded parameter pack might be permitted in this
6370 /// location. Useful for error recovery.
6371 bool isUnexpandedParameterPackPermitted();
6373 /// \brief The context in which an unexpanded parameter pack is
6374 /// being diagnosed.
6376 /// Note that the values of this enumeration line up with the first
6377 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6378 enum UnexpandedParameterPackContext {
6379 /// \brief An arbitrary expression.
6380 UPPC_Expression = 0,
6382 /// \brief The base type of a class type.
6385 /// \brief The type of an arbitrary declaration.
6386 UPPC_DeclarationType,
6388 /// \brief The type of a data member.
6389 UPPC_DataMemberType,
6391 /// \brief The size of a bit-field.
6394 /// \brief The expression in a static assertion.
6395 UPPC_StaticAssertExpression,
6397 /// \brief The fixed underlying type of an enumeration.
6398 UPPC_FixedUnderlyingType,
6400 /// \brief The enumerator value.
6401 UPPC_EnumeratorValue,
6403 /// \brief A using declaration.
6404 UPPC_UsingDeclaration,
6406 /// \brief A friend declaration.
6407 UPPC_FriendDeclaration,
6409 /// \brief A declaration qualifier.
6410 UPPC_DeclarationQualifier,
6412 /// \brief An initializer.
6415 /// \brief A default argument.
6416 UPPC_DefaultArgument,
6418 /// \brief The type of a non-type template parameter.
6419 UPPC_NonTypeTemplateParameterType,
6421 /// \brief The type of an exception.
6424 /// \brief Partial specialization.
6425 UPPC_PartialSpecialization,
6427 /// \brief Microsoft __if_exists.
6430 /// \brief Microsoft __if_not_exists.
6433 /// \brief Lambda expression.
6436 /// \brief Block expression,
6440 /// \brief Diagnose unexpanded parameter packs.
6442 /// \param Loc The location at which we should emit the diagnostic.
6444 /// \param UPPC The context in which we are diagnosing unexpanded
6445 /// parameter packs.
6447 /// \param Unexpanded the set of unexpanded parameter packs.
6449 /// \returns true if an error occurred, false otherwise.
6450 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6451 UnexpandedParameterPackContext UPPC,
6452 ArrayRef<UnexpandedParameterPack> Unexpanded);
6454 /// \brief If the given type contains an unexpanded parameter pack,
6455 /// diagnose the error.
6457 /// \param Loc The source location where a diagnostc should be emitted.
6459 /// \param T The type that is being checked for unexpanded parameter
6462 /// \returns true if an error occurred, false otherwise.
6463 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6464 UnexpandedParameterPackContext UPPC);
6466 /// \brief If the given expression contains an unexpanded parameter
6467 /// pack, diagnose the error.
6469 /// \param E The expression that is being checked for unexpanded
6470 /// parameter packs.
6472 /// \returns true if an error occurred, false otherwise.
6473 bool DiagnoseUnexpandedParameterPack(Expr *E,
6474 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6476 /// \brief If the given nested-name-specifier contains an unexpanded
6477 /// parameter pack, diagnose the error.
6479 /// \param SS The nested-name-specifier that is being checked for
6480 /// unexpanded parameter packs.
6482 /// \returns true if an error occurred, false otherwise.
6483 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6484 UnexpandedParameterPackContext UPPC);
6486 /// \brief If the given name contains an unexpanded parameter pack,
6487 /// diagnose the error.
6489 /// \param NameInfo The name (with source location information) that
6490 /// is being checked for unexpanded parameter packs.
6492 /// \returns true if an error occurred, false otherwise.
6493 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6494 UnexpandedParameterPackContext UPPC);
6496 /// \brief If the given template name contains an unexpanded parameter pack,
6497 /// diagnose the error.
6499 /// \param Loc The location of the template name.
6501 /// \param Template The template name that is being checked for unexpanded
6502 /// parameter packs.
6504 /// \returns true if an error occurred, false otherwise.
6505 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6506 TemplateName Template,
6507 UnexpandedParameterPackContext UPPC);
6509 /// \brief If the given template argument contains an unexpanded parameter
6510 /// pack, diagnose the error.
6512 /// \param Arg The template argument that is being checked for unexpanded
6513 /// parameter packs.
6515 /// \returns true if an error occurred, false otherwise.
6516 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6517 UnexpandedParameterPackContext UPPC);
6519 /// \brief Collect the set of unexpanded parameter packs within the given
6520 /// template argument.
6522 /// \param Arg The template argument that will be traversed to find
6523 /// unexpanded parameter packs.
6524 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6525 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6527 /// \brief Collect the set of unexpanded parameter packs within the given
6528 /// template argument.
6530 /// \param Arg The template argument that will be traversed to find
6531 /// unexpanded parameter packs.
6532 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6533 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6535 /// \brief Collect the set of unexpanded parameter packs within the given
6538 /// \param T The type that will be traversed to find
6539 /// unexpanded parameter packs.
6540 void collectUnexpandedParameterPacks(QualType T,
6541 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6543 /// \brief Collect the set of unexpanded parameter packs within the given
6546 /// \param TL The type that will be traversed to find
6547 /// unexpanded parameter packs.
6548 void collectUnexpandedParameterPacks(TypeLoc TL,
6549 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6551 /// \brief Collect the set of unexpanded parameter packs within the given
6552 /// nested-name-specifier.
6554 /// \param NNS The nested-name-specifier that will be traversed to find
6555 /// unexpanded parameter packs.
6556 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6557 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6559 /// \brief Collect the set of unexpanded parameter packs within the given
6562 /// \param NameInfo The name that will be traversed to find
6563 /// unexpanded parameter packs.
6564 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6565 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6567 /// \brief Invoked when parsing a template argument followed by an
6568 /// ellipsis, which creates a pack expansion.
6570 /// \param Arg The template argument preceding the ellipsis, which
6571 /// may already be invalid.
6573 /// \param EllipsisLoc The location of the ellipsis.
6574 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6575 SourceLocation EllipsisLoc);
6577 /// \brief Invoked when parsing a type followed by an ellipsis, which
6578 /// creates a pack expansion.
6580 /// \param Type The type preceding the ellipsis, which will become
6581 /// the pattern of the pack expansion.
6583 /// \param EllipsisLoc The location of the ellipsis.
6584 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6586 /// \brief Construct a pack expansion type from the pattern of the pack
6588 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6589 SourceLocation EllipsisLoc,
6590 Optional<unsigned> NumExpansions);
6592 /// \brief Construct a pack expansion type from the pattern of the pack
6594 QualType CheckPackExpansion(QualType Pattern,
6595 SourceRange PatternRange,
6596 SourceLocation EllipsisLoc,
6597 Optional<unsigned> NumExpansions);
6599 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6600 /// creates a pack expansion.
6602 /// \param Pattern The expression preceding the ellipsis, which will become
6603 /// the pattern of the pack expansion.
6605 /// \param EllipsisLoc The location of the ellipsis.
6606 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6608 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6609 /// creates a pack expansion.
6611 /// \param Pattern The expression preceding the ellipsis, which will become
6612 /// the pattern of the pack expansion.
6614 /// \param EllipsisLoc The location of the ellipsis.
6615 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6616 Optional<unsigned> NumExpansions);
6618 /// \brief Determine whether we could expand a pack expansion with the
6619 /// given set of parameter packs into separate arguments by repeatedly
6620 /// transforming the pattern.
6622 /// \param EllipsisLoc The location of the ellipsis that identifies the
6625 /// \param PatternRange The source range that covers the entire pattern of
6626 /// the pack expansion.
6628 /// \param Unexpanded The set of unexpanded parameter packs within the
6631 /// \param ShouldExpand Will be set to \c true if the transformer should
6632 /// expand the corresponding pack expansions into separate arguments. When
6633 /// set, \c NumExpansions must also be set.
6635 /// \param RetainExpansion Whether the caller should add an unexpanded
6636 /// pack expansion after all of the expanded arguments. This is used
6637 /// when extending explicitly-specified template argument packs per
6638 /// C++0x [temp.arg.explicit]p9.
6640 /// \param NumExpansions The number of separate arguments that will be in
6641 /// the expanded form of the corresponding pack expansion. This is both an
6642 /// input and an output parameter, which can be set by the caller if the
6643 /// number of expansions is known a priori (e.g., due to a prior substitution)
6644 /// and will be set by the callee when the number of expansions is known.
6645 /// The callee must set this value when \c ShouldExpand is \c true; it may
6646 /// set this value in other cases.
6648 /// \returns true if an error occurred (e.g., because the parameter packs
6649 /// are to be instantiated with arguments of different lengths), false
6650 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6652 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6653 SourceRange PatternRange,
6654 ArrayRef<UnexpandedParameterPack> Unexpanded,
6655 const MultiLevelTemplateArgumentList &TemplateArgs,
6657 bool &RetainExpansion,
6658 Optional<unsigned> &NumExpansions);
6660 /// \brief Determine the number of arguments in the given pack expansion
6663 /// This routine assumes that the number of arguments in the expansion is
6664 /// consistent across all of the unexpanded parameter packs in its pattern.
6666 /// Returns an empty Optional if the type can't be expanded.
6667 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6668 const MultiLevelTemplateArgumentList &TemplateArgs);
6670 /// \brief Determine whether the given declarator contains any unexpanded
6671 /// parameter packs.
6673 /// This routine is used by the parser to disambiguate function declarators
6674 /// with an ellipsis prior to the ')', e.g.,
6680 /// To determine whether we have an (unnamed) function parameter pack or
6681 /// a variadic function.
6683 /// \returns true if the declarator contains any unexpanded parameter packs,
6684 /// false otherwise.
6685 bool containsUnexpandedParameterPacks(Declarator &D);
6687 /// \brief Returns the pattern of the pack expansion for a template argument.
6689 /// \param OrigLoc The template argument to expand.
6691 /// \param Ellipsis Will be set to the location of the ellipsis.
6693 /// \param NumExpansions Will be set to the number of expansions that will
6694 /// be generated from this pack expansion, if known a priori.
6695 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6696 TemplateArgumentLoc OrigLoc,
6697 SourceLocation &Ellipsis,
6698 Optional<unsigned> &NumExpansions) const;
6700 /// Given a template argument that contains an unexpanded parameter pack, but
6701 /// which has already been substituted, attempt to determine the number of
6702 /// elements that will be produced once this argument is fully-expanded.
6704 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6705 /// avoid actually expanding the pack where possible.
6706 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6708 //===--------------------------------------------------------------------===//
6709 // C++ Template Argument Deduction (C++ [temp.deduct])
6710 //===--------------------------------------------------------------------===//
6712 /// Adjust the type \p ArgFunctionType to match the calling convention,
6713 /// noreturn, and optionally the exception specification of \p FunctionType.
6714 /// Deduction often wants to ignore these properties when matching function
6716 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6717 bool AdjustExceptionSpec = false);
6719 /// \brief Describes the result of template argument deduction.
6721 /// The TemplateDeductionResult enumeration describes the result of
6722 /// template argument deduction, as returned from
6723 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6724 /// structure provides additional information about the results of
6725 /// template argument deduction, e.g., the deduced template argument
6726 /// list (if successful) or the specific template parameters or
6727 /// deduced arguments that were involved in the failure.
6728 enum TemplateDeductionResult {
6729 /// \brief Template argument deduction was successful.
6731 /// \brief The declaration was invalid; do nothing.
6733 /// \brief Template argument deduction exceeded the maximum template
6734 /// instantiation depth (which has already been diagnosed).
6735 TDK_InstantiationDepth,
6736 /// \brief Template argument deduction did not deduce a value
6737 /// for every template parameter.
6739 /// \brief Template argument deduction produced inconsistent
6740 /// deduced values for the given template parameter.
6742 /// \brief Template argument deduction failed due to inconsistent
6743 /// cv-qualifiers on a template parameter type that would
6744 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6745 /// but were given a non-const "X".
6747 /// \brief Substitution of the deduced template argument values
6748 /// resulted in an error.
6749 TDK_SubstitutionFailure,
6750 /// \brief After substituting deduced template arguments, a dependent
6751 /// parameter type did not match the corresponding argument.
6752 TDK_DeducedMismatch,
6753 /// \brief After substituting deduced template arguments, an element of
6754 /// a dependent parameter type did not match the corresponding element
6755 /// of the corresponding argument (when deducing from an initializer list).
6756 TDK_DeducedMismatchNested,
6757 /// \brief A non-depnedent component of the parameter did not match the
6758 /// corresponding component of the argument.
6759 TDK_NonDeducedMismatch,
6760 /// \brief When performing template argument deduction for a function
6761 /// template, there were too many call arguments.
6762 TDK_TooManyArguments,
6763 /// \brief When performing template argument deduction for a function
6764 /// template, there were too few call arguments.
6765 TDK_TooFewArguments,
6766 /// \brief The explicitly-specified template arguments were not valid
6767 /// template arguments for the given template.
6768 TDK_InvalidExplicitArguments,
6769 /// \brief Checking non-dependent argument conversions failed.
6770 TDK_NonDependentConversionFailure,
6771 /// \brief Deduction failed; that's all we know.
6772 TDK_MiscellaneousDeductionFailure,
6773 /// \brief CUDA Target attributes do not match.
6774 TDK_CUDATargetMismatch
6777 TemplateDeductionResult
6778 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6779 const TemplateArgumentList &TemplateArgs,
6780 sema::TemplateDeductionInfo &Info);
6782 TemplateDeductionResult
6783 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6784 const TemplateArgumentList &TemplateArgs,
6785 sema::TemplateDeductionInfo &Info);
6787 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6788 FunctionTemplateDecl *FunctionTemplate,
6789 TemplateArgumentListInfo &ExplicitTemplateArgs,
6790 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6791 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6792 sema::TemplateDeductionInfo &Info);
6794 /// brief A function argument from which we performed template argument
6795 // deduction for a call.
6796 struct OriginalCallArg {
6797 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6798 unsigned ArgIdx, QualType OriginalArgType)
6799 : OriginalParamType(OriginalParamType),
6800 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6801 OriginalArgType(OriginalArgType) {}
6803 QualType OriginalParamType;
6804 bool DecomposedParam;
6806 QualType OriginalArgType;
6809 TemplateDeductionResult FinishTemplateArgumentDeduction(
6810 FunctionTemplateDecl *FunctionTemplate,
6811 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6812 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6813 sema::TemplateDeductionInfo &Info,
6814 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6815 bool PartialOverloading = false,
6816 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6818 TemplateDeductionResult DeduceTemplateArguments(
6819 FunctionTemplateDecl *FunctionTemplate,
6820 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6821 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6822 bool PartialOverloading,
6823 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6825 TemplateDeductionResult
6826 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6827 TemplateArgumentListInfo *ExplicitTemplateArgs,
6828 QualType ArgFunctionType,
6829 FunctionDecl *&Specialization,
6830 sema::TemplateDeductionInfo &Info,
6831 bool IsAddressOfFunction = false);
6833 TemplateDeductionResult
6834 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6836 CXXConversionDecl *&Specialization,
6837 sema::TemplateDeductionInfo &Info);
6839 TemplateDeductionResult
6840 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6841 TemplateArgumentListInfo *ExplicitTemplateArgs,
6842 FunctionDecl *&Specialization,
6843 sema::TemplateDeductionInfo &Info,
6844 bool IsAddressOfFunction = false);
6846 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6847 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6848 /// \brief Substitute Replacement for auto in TypeWithAuto
6849 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6850 QualType Replacement);
6851 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6852 /// \p Replacement. This does not retain any \c auto type sugar.
6853 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6855 /// \brief Result type of DeduceAutoType.
6856 enum DeduceAutoResult {
6859 DAR_FailedAlreadyDiagnosed
6863 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6864 Optional<unsigned> DependentDeductionDepth = None);
6866 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6867 Optional<unsigned> DependentDeductionDepth = None);
6868 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6869 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6870 bool Diagnose = true);
6872 /// \brief Declare implicit deduction guides for a class template if we've
6873 /// not already done so.
6874 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6875 SourceLocation Loc);
6877 QualType DeduceTemplateSpecializationFromInitializer(
6878 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6879 const InitializationKind &Kind, MultiExprArg Init);
6881 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6882 QualType Type, TypeSourceInfo *TSI,
6883 SourceRange Range, bool DirectInit,
6886 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6888 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6889 SourceLocation ReturnLoc,
6890 Expr *&RetExpr, AutoType *AT);
6892 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6893 FunctionTemplateDecl *FT2,
6895 TemplatePartialOrderingContext TPOC,
6896 unsigned NumCallArguments1,
6897 unsigned NumCallArguments2);
6898 UnresolvedSetIterator
6899 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6900 TemplateSpecCandidateSet &FailedCandidates,
6902 const PartialDiagnostic &NoneDiag,
6903 const PartialDiagnostic &AmbigDiag,
6904 const PartialDiagnostic &CandidateDiag,
6905 bool Complain = true, QualType TargetType = QualType());
6907 ClassTemplatePartialSpecializationDecl *
6908 getMoreSpecializedPartialSpecialization(
6909 ClassTemplatePartialSpecializationDecl *PS1,
6910 ClassTemplatePartialSpecializationDecl *PS2,
6911 SourceLocation Loc);
6913 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6914 sema::TemplateDeductionInfo &Info);
6916 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6917 VarTemplatePartialSpecializationDecl *PS1,
6918 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6920 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6921 sema::TemplateDeductionInfo &Info);
6923 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6924 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6926 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6929 llvm::SmallBitVector &Used);
6930 void MarkDeducedTemplateParameters(
6931 const FunctionTemplateDecl *FunctionTemplate,
6932 llvm::SmallBitVector &Deduced) {
6933 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6935 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6936 const FunctionTemplateDecl *FunctionTemplate,
6937 llvm::SmallBitVector &Deduced);
6939 //===--------------------------------------------------------------------===//
6940 // C++ Template Instantiation
6943 MultiLevelTemplateArgumentList
6944 getTemplateInstantiationArgs(NamedDecl *D,
6945 const TemplateArgumentList *Innermost = nullptr,
6946 bool RelativeToPrimary = false,
6947 const FunctionDecl *Pattern = nullptr);
6949 /// A context in which code is being synthesized (where a source location
6950 /// alone is not sufficient to identify the context). This covers template
6951 /// instantiation and various forms of implicitly-generated functions.
6952 struct CodeSynthesisContext {
6953 /// \brief The kind of template instantiation we are performing
6954 enum SynthesisKind {
6955 /// We are instantiating a template declaration. The entity is
6956 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6957 TemplateInstantiation,
6959 /// We are instantiating a default argument for a template
6960 /// parameter. The Entity is the template parameter whose argument is
6961 /// being instantiated, the Template is the template, and the
6962 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6964 DefaultTemplateArgumentInstantiation,
6966 /// We are instantiating a default argument for a function.
6967 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6968 /// provides the template arguments as specified.
6969 DefaultFunctionArgumentInstantiation,
6971 /// We are substituting explicit template arguments provided for
6972 /// a function template. The entity is a FunctionTemplateDecl.
6973 ExplicitTemplateArgumentSubstitution,
6975 /// We are substituting template argument determined as part of
6976 /// template argument deduction for either a class template
6977 /// partial specialization or a function template. The
6978 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6980 DeducedTemplateArgumentSubstitution,
6982 /// We are substituting prior template arguments into a new
6983 /// template parameter. The template parameter itself is either a
6984 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6985 PriorTemplateArgumentSubstitution,
6987 /// We are checking the validity of a default template argument that
6988 /// has been used when naming a template-id.
6989 DefaultTemplateArgumentChecking,
6991 /// We are instantiating the exception specification for a function
6992 /// template which was deferred until it was needed.
6993 ExceptionSpecInstantiation,
6995 /// We are declaring an implicit special member function.
6996 DeclaringSpecialMember,
6998 /// We are defining a synthesized function (such as a defaulted special
7000 DefiningSynthesizedFunction,
7003 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7004 bool SavedInNonInstantiationSFINAEContext;
7006 /// \brief The point of instantiation or synthesis within the source code.
7007 SourceLocation PointOfInstantiation;
7009 /// \brief The entity that is being synthesized.
7012 /// \brief The template (or partial specialization) in which we are
7013 /// performing the instantiation, for substitutions of prior template
7015 NamedDecl *Template;
7017 /// \brief The list of template arguments we are substituting, if they
7018 /// are not part of the entity.
7019 const TemplateArgument *TemplateArgs;
7021 // FIXME: Wrap this union around more members, or perhaps store the
7022 // kind-specific members in the RAII object owning the context.
7024 /// \brief The number of template arguments in TemplateArgs.
7025 unsigned NumTemplateArgs;
7027 /// \brief The special member being declared or defined.
7028 CXXSpecialMember SpecialMember;
7031 ArrayRef<TemplateArgument> template_arguments() const {
7032 assert(Kind != DeclaringSpecialMember);
7033 return {TemplateArgs, NumTemplateArgs};
7036 /// \brief The template deduction info object associated with the
7037 /// substitution or checking of explicit or deduced template arguments.
7038 sema::TemplateDeductionInfo *DeductionInfo;
7040 /// \brief The source range that covers the construct that cause
7041 /// the instantiation, e.g., the template-id that causes a class
7042 /// template instantiation.
7043 SourceRange InstantiationRange;
7045 CodeSynthesisContext()
7046 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7047 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7049 /// \brief Determines whether this template is an actual instantiation
7050 /// that should be counted toward the maximum instantiation depth.
7051 bool isInstantiationRecord() const;
7054 /// \brief List of active code synthesis contexts.
7056 /// This vector is treated as a stack. As synthesis of one entity requires
7057 /// synthesis of another, additional contexts are pushed onto the stack.
7058 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7060 /// Specializations whose definitions are currently being instantiated.
7061 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7063 /// Non-dependent types used in templates that have already been instantiated
7064 /// by some template instantiation.
7065 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7067 /// \brief Extra modules inspected when performing a lookup during a template
7068 /// instantiation. Computed lazily.
7069 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7071 /// \brief Cache of additional modules that should be used for name lookup
7072 /// within the current template instantiation. Computed lazily; use
7073 /// getLookupModules() to get a complete set.
7074 llvm::DenseSet<Module*> LookupModulesCache;
7076 /// \brief Get the set of additional modules that should be checked during
7077 /// name lookup. A module and its imports become visible when instanting a
7078 /// template defined within it.
7079 llvm::DenseSet<Module*> &getLookupModules();
7081 /// \brief Map from the most recent declaration of a namespace to the most
7082 /// recent visible declaration of that namespace.
7083 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7085 /// \brief Whether we are in a SFINAE context that is not associated with
7086 /// template instantiation.
7088 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7089 /// of a template instantiation or template argument deduction.
7090 bool InNonInstantiationSFINAEContext;
7092 /// \brief The number of \p CodeSynthesisContexts that are not template
7093 /// instantiations and, therefore, should not be counted as part of the
7094 /// instantiation depth.
7096 /// When the instantiation depth reaches the user-configurable limit
7097 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7098 // FIXME: Should we have a similar limit for other forms of synthesis?
7099 unsigned NonInstantiationEntries;
7101 /// \brief The depth of the context stack at the point when the most recent
7102 /// error or warning was produced.
7104 /// This value is used to suppress printing of redundant context stacks
7105 /// when there are multiple errors or warnings in the same instantiation.
7106 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7107 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7109 /// \brief The current index into pack expansion arguments that will be
7110 /// used for substitution of parameter packs.
7112 /// The pack expansion index will be -1 to indicate that parameter packs
7113 /// should be instantiated as themselves. Otherwise, the index specifies
7114 /// which argument within the parameter pack will be used for substitution.
7115 int ArgumentPackSubstitutionIndex;
7117 /// \brief RAII object used to change the argument pack substitution index
7118 /// within a \c Sema object.
7120 /// See \c ArgumentPackSubstitutionIndex for more information.
7121 class ArgumentPackSubstitutionIndexRAII {
7123 int OldSubstitutionIndex;
7126 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7127 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7128 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7131 ~ArgumentPackSubstitutionIndexRAII() {
7132 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7136 friend class ArgumentPackSubstitutionRAII;
7138 /// \brief For each declaration that involved template argument deduction, the
7139 /// set of diagnostics that were suppressed during that template argument
7142 /// FIXME: Serialize this structure to the AST file.
7143 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7144 SuppressedDiagnosticsMap;
7145 SuppressedDiagnosticsMap SuppressedDiagnostics;
7147 /// \brief A stack object to be created when performing template
7150 /// Construction of an object of type \c InstantiatingTemplate
7151 /// pushes the current instantiation onto the stack of active
7152 /// instantiations. If the size of this stack exceeds the maximum
7153 /// number of recursive template instantiations, construction
7154 /// produces an error and evaluates true.
7156 /// Destruction of this object will pop the named instantiation off
7158 struct InstantiatingTemplate {
7159 /// \brief Note that we are instantiating a class template,
7160 /// function template, variable template, alias template,
7161 /// or a member thereof.
7162 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7164 SourceRange InstantiationRange = SourceRange());
7166 struct ExceptionSpecification {};
7167 /// \brief Note that we are instantiating an exception specification
7168 /// of a function template.
7169 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7170 FunctionDecl *Entity, ExceptionSpecification,
7171 SourceRange InstantiationRange = SourceRange());
7173 /// \brief Note that we are instantiating a default argument in a
7175 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7176 TemplateParameter Param, TemplateDecl *Template,
7177 ArrayRef<TemplateArgument> TemplateArgs,
7178 SourceRange InstantiationRange = SourceRange());
7180 /// \brief Note that we are substituting either explicitly-specified or
7181 /// deduced template arguments during function template argument deduction.
7182 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7183 FunctionTemplateDecl *FunctionTemplate,
7184 ArrayRef<TemplateArgument> TemplateArgs,
7185 CodeSynthesisContext::SynthesisKind Kind,
7186 sema::TemplateDeductionInfo &DeductionInfo,
7187 SourceRange InstantiationRange = SourceRange());
7189 /// \brief Note that we are instantiating as part of template
7190 /// argument deduction for a class template declaration.
7191 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7192 TemplateDecl *Template,
7193 ArrayRef<TemplateArgument> TemplateArgs,
7194 sema::TemplateDeductionInfo &DeductionInfo,
7195 SourceRange InstantiationRange = SourceRange());
7197 /// \brief Note that we are instantiating as part of template
7198 /// argument deduction for a class template partial
7200 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7201 ClassTemplatePartialSpecializationDecl *PartialSpec,
7202 ArrayRef<TemplateArgument> TemplateArgs,
7203 sema::TemplateDeductionInfo &DeductionInfo,
7204 SourceRange InstantiationRange = SourceRange());
7206 /// \brief Note that we are instantiating as part of template
7207 /// argument deduction for a variable template partial
7209 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7210 VarTemplatePartialSpecializationDecl *PartialSpec,
7211 ArrayRef<TemplateArgument> TemplateArgs,
7212 sema::TemplateDeductionInfo &DeductionInfo,
7213 SourceRange InstantiationRange = SourceRange());
7215 /// \brief Note that we are instantiating a default argument for a function
7217 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7219 ArrayRef<TemplateArgument> TemplateArgs,
7220 SourceRange InstantiationRange = SourceRange());
7222 /// \brief Note that we are substituting prior template arguments into a
7223 /// non-type parameter.
7224 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7225 NamedDecl *Template,
7226 NonTypeTemplateParmDecl *Param,
7227 ArrayRef<TemplateArgument> TemplateArgs,
7228 SourceRange InstantiationRange);
7230 /// \brief Note that we are substituting prior template arguments into a
7231 /// template template parameter.
7232 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7233 NamedDecl *Template,
7234 TemplateTemplateParmDecl *Param,
7235 ArrayRef<TemplateArgument> TemplateArgs,
7236 SourceRange InstantiationRange);
7238 /// \brief Note that we are checking the default template argument
7239 /// against the template parameter for a given template-id.
7240 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7241 TemplateDecl *Template,
7243 ArrayRef<TemplateArgument> TemplateArgs,
7244 SourceRange InstantiationRange);
7247 /// \brief Note that we have finished instantiating this template.
7250 ~InstantiatingTemplate() { Clear(); }
7252 /// \brief Determines whether we have exceeded the maximum
7253 /// recursive template instantiations.
7254 bool isInvalid() const { return Invalid; }
7256 /// \brief Determine whether we are already instantiating this
7257 /// specialization in some surrounding active instantiation.
7258 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7263 bool AlreadyInstantiating;
7264 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7265 SourceRange InstantiationRange);
7267 InstantiatingTemplate(
7268 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7269 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7270 Decl *Entity, NamedDecl *Template = nullptr,
7271 ArrayRef<TemplateArgument> TemplateArgs = None,
7272 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7274 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7276 InstantiatingTemplate&
7277 operator=(const InstantiatingTemplate&) = delete;
7280 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7281 void popCodeSynthesisContext();
7283 /// Determine whether we are currently performing template instantiation.
7284 bool inTemplateInstantiation() const {
7285 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7288 void PrintContextStack() {
7289 if (!CodeSynthesisContexts.empty() &&
7290 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7291 PrintInstantiationStack();
7292 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7294 if (PragmaAttributeCurrentTargetDecl)
7295 PrintPragmaAttributeInstantiationPoint();
7297 void PrintInstantiationStack();
7299 void PrintPragmaAttributeInstantiationPoint();
7301 /// \brief Determines whether we are currently in a context where
7302 /// template argument substitution failures are not considered
7305 /// \returns An empty \c Optional if we're not in a SFINAE context.
7306 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7307 /// template-deduction context object, which can be used to capture
7308 /// diagnostics that will be suppressed.
7309 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7311 /// \brief Determines whether we are currently in a context that
7312 /// is not evaluated as per C++ [expr] p5.
7313 bool isUnevaluatedContext() const {
7314 assert(!ExprEvalContexts.empty() &&
7315 "Must be in an expression evaluation context");
7316 return ExprEvalContexts.back().isUnevaluated();
7319 /// \brief RAII class used to determine whether SFINAE has
7320 /// trapped any errors that occur during template argument
7324 unsigned PrevSFINAEErrors;
7325 bool PrevInNonInstantiationSFINAEContext;
7326 bool PrevAccessCheckingSFINAE;
7329 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7330 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7331 PrevInNonInstantiationSFINAEContext(
7332 SemaRef.InNonInstantiationSFINAEContext),
7333 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7335 if (!SemaRef.isSFINAEContext())
7336 SemaRef.InNonInstantiationSFINAEContext = true;
7337 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7341 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7342 SemaRef.InNonInstantiationSFINAEContext
7343 = PrevInNonInstantiationSFINAEContext;
7344 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7347 /// \brief Determine whether any SFINAE errors have been trapped.
7348 bool hasErrorOccurred() const {
7349 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7353 /// \brief RAII class used to indicate that we are performing provisional
7354 /// semantic analysis to determine the validity of a construct, so
7355 /// typo-correction and diagnostics in the immediate context (not within
7356 /// implicitly-instantiated templates) should be suppressed.
7357 class TentativeAnalysisScope {
7359 // FIXME: Using a SFINAETrap for this is a hack.
7361 bool PrevDisableTypoCorrection;
7363 explicit TentativeAnalysisScope(Sema &SemaRef)
7364 : SemaRef(SemaRef), Trap(SemaRef, true),
7365 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7366 SemaRef.DisableTypoCorrection = true;
7368 ~TentativeAnalysisScope() {
7369 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7373 /// \brief The current instantiation scope used to store local
7375 LocalInstantiationScope *CurrentInstantiationScope;
7377 /// \brief Tracks whether we are in a context where typo correction is
7379 bool DisableTypoCorrection;
7381 /// \brief The number of typos corrected by CorrectTypo.
7382 unsigned TyposCorrected;
7384 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7385 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7387 /// \brief A cache containing identifiers for which typo correction failed and
7388 /// their locations, so that repeated attempts to correct an identifier in a
7389 /// given location are ignored if typo correction already failed for it.
7390 IdentifierSourceLocations TypoCorrectionFailures;
7392 /// \brief Worker object for performing CFG-based warnings.
7393 sema::AnalysisBasedWarnings AnalysisWarnings;
7394 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7396 /// \brief An entity for which implicit template instantiation is required.
7398 /// The source location associated with the declaration is the first place in
7399 /// the source code where the declaration was "used". It is not necessarily
7400 /// the point of instantiation (which will be either before or after the
7401 /// namespace-scope declaration that triggered this implicit instantiation),
7402 /// However, it is the location that diagnostics should generally refer to,
7403 /// because users will need to know what code triggered the instantiation.
7404 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7406 /// \brief The queue of implicit template instantiations that are required
7407 /// but have not yet been performed.
7408 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7410 class GlobalEagerInstantiationScope {
7412 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7413 : S(S), Enabled(Enabled) {
7414 if (!Enabled) return;
7416 SavedPendingInstantiations.swap(S.PendingInstantiations);
7417 SavedVTableUses.swap(S.VTableUses);
7422 S.DefineUsedVTables();
7423 S.PerformPendingInstantiations();
7427 ~GlobalEagerInstantiationScope() {
7428 if (!Enabled) return;
7430 // Restore the set of pending vtables.
7431 assert(S.VTableUses.empty() &&
7432 "VTableUses should be empty before it is discarded.");
7433 S.VTableUses.swap(SavedVTableUses);
7435 // Restore the set of pending implicit instantiations.
7436 assert(S.PendingInstantiations.empty() &&
7437 "PendingInstantiations should be empty before it is discarded.");
7438 S.PendingInstantiations.swap(SavedPendingInstantiations);
7443 SmallVector<VTableUse, 16> SavedVTableUses;
7444 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7448 /// \brief The queue of implicit template instantiations that are required
7449 /// and must be performed within the current local scope.
7451 /// This queue is only used for member functions of local classes in
7452 /// templates, which must be instantiated in the same scope as their
7453 /// enclosing function, so that they can reference function-local
7454 /// types, static variables, enumerators, etc.
7455 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7457 class LocalEagerInstantiationScope {
7459 LocalEagerInstantiationScope(Sema &S) : S(S) {
7460 SavedPendingLocalImplicitInstantiations.swap(
7461 S.PendingLocalImplicitInstantiations);
7464 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7466 ~LocalEagerInstantiationScope() {
7467 assert(S.PendingLocalImplicitInstantiations.empty() &&
7468 "there shouldn't be any pending local implicit instantiations");
7469 SavedPendingLocalImplicitInstantiations.swap(
7470 S.PendingLocalImplicitInstantiations);
7475 std::deque<PendingImplicitInstantiation>
7476 SavedPendingLocalImplicitInstantiations;
7479 /// A helper class for building up ExtParameterInfos.
7480 class ExtParameterInfoBuilder {
7481 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7482 bool HasInteresting = false;
7485 /// Set the ExtParameterInfo for the parameter at the given index,
7487 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7488 assert(Infos.size() <= index);
7489 Infos.resize(index);
7490 Infos.push_back(info);
7492 if (!HasInteresting)
7493 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7496 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7497 /// ExtParameterInfo array we've built up.
7498 const FunctionProtoType::ExtParameterInfo *
7499 getPointerOrNull(unsigned numParams) {
7500 if (!HasInteresting) return nullptr;
7501 Infos.resize(numParams);
7502 return Infos.data();
7506 void PerformPendingInstantiations(bool LocalOnly = false);
7508 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7509 const MultiLevelTemplateArgumentList &TemplateArgs,
7510 SourceLocation Loc, DeclarationName Entity,
7511 bool AllowDeducedTST = false);
7513 QualType SubstType(QualType T,
7514 const MultiLevelTemplateArgumentList &TemplateArgs,
7515 SourceLocation Loc, DeclarationName Entity);
7517 TypeSourceInfo *SubstType(TypeLoc TL,
7518 const MultiLevelTemplateArgumentList &TemplateArgs,
7519 SourceLocation Loc, DeclarationName Entity);
7521 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7522 const MultiLevelTemplateArgumentList &TemplateArgs,
7524 DeclarationName Entity,
7525 CXXRecordDecl *ThisContext,
7526 unsigned ThisTypeQuals);
7527 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7528 const MultiLevelTemplateArgumentList &Args);
7529 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7530 const MultiLevelTemplateArgumentList &TemplateArgs,
7531 int indexAdjustment,
7532 Optional<unsigned> NumExpansions,
7533 bool ExpectParameterPack);
7534 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7535 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7536 const MultiLevelTemplateArgumentList &TemplateArgs,
7537 SmallVectorImpl<QualType> &ParamTypes,
7538 SmallVectorImpl<ParmVarDecl *> *OutParams,
7539 ExtParameterInfoBuilder &ParamInfos);
7540 ExprResult SubstExpr(Expr *E,
7541 const MultiLevelTemplateArgumentList &TemplateArgs);
7543 /// \brief Substitute the given template arguments into a list of
7544 /// expressions, expanding pack expansions if required.
7546 /// \param Exprs The list of expressions to substitute into.
7548 /// \param IsCall Whether this is some form of call, in which case
7549 /// default arguments will be dropped.
7551 /// \param TemplateArgs The set of template arguments to substitute.
7553 /// \param Outputs Will receive all of the substituted arguments.
7555 /// \returns true if an error occurred, false otherwise.
7556 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7557 const MultiLevelTemplateArgumentList &TemplateArgs,
7558 SmallVectorImpl<Expr *> &Outputs);
7560 StmtResult SubstStmt(Stmt *S,
7561 const MultiLevelTemplateArgumentList &TemplateArgs);
7563 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7564 const MultiLevelTemplateArgumentList &TemplateArgs);
7566 ExprResult SubstInitializer(Expr *E,
7567 const MultiLevelTemplateArgumentList &TemplateArgs,
7568 bool CXXDirectInit);
7571 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7572 CXXRecordDecl *Pattern,
7573 const MultiLevelTemplateArgumentList &TemplateArgs);
7576 InstantiateClass(SourceLocation PointOfInstantiation,
7577 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7578 const MultiLevelTemplateArgumentList &TemplateArgs,
7579 TemplateSpecializationKind TSK,
7580 bool Complain = true);
7582 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7583 EnumDecl *Instantiation, EnumDecl *Pattern,
7584 const MultiLevelTemplateArgumentList &TemplateArgs,
7585 TemplateSpecializationKind TSK);
7587 bool InstantiateInClassInitializer(
7588 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7589 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7591 struct LateInstantiatedAttribute {
7592 const Attr *TmplAttr;
7593 LocalInstantiationScope *Scope;
7596 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7598 : TmplAttr(A), Scope(S), NewDecl(D)
7601 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7603 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7604 const Decl *Pattern, Decl *Inst,
7605 LateInstantiatedAttrVec *LateAttrs = nullptr,
7606 LocalInstantiationScope *OuterMostScope = nullptr);
7609 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7610 const Decl *Pattern, Decl *Inst,
7611 LateInstantiatedAttrVec *LateAttrs = nullptr,
7612 LocalInstantiationScope *OuterMostScope = nullptr);
7615 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7616 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7617 TemplateSpecializationKind TSK,
7618 bool Complain = true);
7620 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7621 CXXRecordDecl *Instantiation,
7622 const MultiLevelTemplateArgumentList &TemplateArgs,
7623 TemplateSpecializationKind TSK);
7625 void InstantiateClassTemplateSpecializationMembers(
7626 SourceLocation PointOfInstantiation,
7627 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7628 TemplateSpecializationKind TSK);
7630 NestedNameSpecifierLoc
7631 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7632 const MultiLevelTemplateArgumentList &TemplateArgs);
7635 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7636 const MultiLevelTemplateArgumentList &TemplateArgs);
7638 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7640 const MultiLevelTemplateArgumentList &TemplateArgs);
7641 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7642 TemplateArgumentListInfo &Result,
7643 const MultiLevelTemplateArgumentList &TemplateArgs);
7645 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7646 FunctionDecl *Function);
7647 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7648 FunctionDecl *Function,
7649 bool Recursive = false,
7650 bool DefinitionRequired = false,
7651 bool AtEndOfTU = false);
7652 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7653 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7654 const TemplateArgumentList &TemplateArgList,
7655 const TemplateArgumentListInfo &TemplateArgsInfo,
7656 SmallVectorImpl<TemplateArgument> &Converted,
7657 SourceLocation PointOfInstantiation, void *InsertPos,
7658 LateInstantiatedAttrVec *LateAttrs = nullptr,
7659 LocalInstantiationScope *StartingScope = nullptr);
7660 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7661 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7662 const MultiLevelTemplateArgumentList &TemplateArgs);
7664 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7665 const MultiLevelTemplateArgumentList &TemplateArgs,
7666 LateInstantiatedAttrVec *LateAttrs,
7668 LocalInstantiationScope *StartingScope,
7669 bool InstantiatingVarTemplate = false);
7670 void InstantiateVariableInitializer(
7671 VarDecl *Var, VarDecl *OldVar,
7672 const MultiLevelTemplateArgumentList &TemplateArgs);
7673 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7674 VarDecl *Var, bool Recursive = false,
7675 bool DefinitionRequired = false,
7676 bool AtEndOfTU = false);
7677 void InstantiateStaticDataMemberDefinition(
7678 SourceLocation PointOfInstantiation,
7680 bool Recursive = false,
7681 bool DefinitionRequired = false);
7683 void InstantiateMemInitializers(CXXConstructorDecl *New,
7684 const CXXConstructorDecl *Tmpl,
7685 const MultiLevelTemplateArgumentList &TemplateArgs);
7687 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7688 const MultiLevelTemplateArgumentList &TemplateArgs);
7689 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7690 const MultiLevelTemplateArgumentList &TemplateArgs);
7692 // Objective-C declarations.
7693 enum ObjCContainerKind {
7700 OCK_CategoryImplementation
7702 ObjCContainerKind getObjCContainerKind() const;
7704 DeclResult actOnObjCTypeParam(Scope *S,
7705 ObjCTypeParamVariance variance,
7706 SourceLocation varianceLoc,
7708 IdentifierInfo *paramName,
7709 SourceLocation paramLoc,
7710 SourceLocation colonLoc,
7711 ParsedType typeBound);
7713 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7714 ArrayRef<Decl *> typeParams,
7715 SourceLocation rAngleLoc);
7716 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7718 Decl *ActOnStartClassInterface(Scope *S,
7719 SourceLocation AtInterfaceLoc,
7720 IdentifierInfo *ClassName,
7721 SourceLocation ClassLoc,
7722 ObjCTypeParamList *typeParamList,
7723 IdentifierInfo *SuperName,
7724 SourceLocation SuperLoc,
7725 ArrayRef<ParsedType> SuperTypeArgs,
7726 SourceRange SuperTypeArgsRange,
7727 Decl * const *ProtoRefs,
7728 unsigned NumProtoRefs,
7729 const SourceLocation *ProtoLocs,
7730 SourceLocation EndProtoLoc,
7731 AttributeList *AttrList);
7733 void ActOnSuperClassOfClassInterface(Scope *S,
7734 SourceLocation AtInterfaceLoc,
7735 ObjCInterfaceDecl *IDecl,
7736 IdentifierInfo *ClassName,
7737 SourceLocation ClassLoc,
7738 IdentifierInfo *SuperName,
7739 SourceLocation SuperLoc,
7740 ArrayRef<ParsedType> SuperTypeArgs,
7741 SourceRange SuperTypeArgsRange);
7743 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7744 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7745 IdentifierInfo *SuperName,
7746 SourceLocation SuperLoc);
7748 Decl *ActOnCompatibilityAlias(
7749 SourceLocation AtCompatibilityAliasLoc,
7750 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7751 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7753 bool CheckForwardProtocolDeclarationForCircularDependency(
7754 IdentifierInfo *PName,
7755 SourceLocation &PLoc, SourceLocation PrevLoc,
7756 const ObjCList<ObjCProtocolDecl> &PList);
7758 Decl *ActOnStartProtocolInterface(
7759 SourceLocation AtProtoInterfaceLoc,
7760 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7761 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7762 const SourceLocation *ProtoLocs,
7763 SourceLocation EndProtoLoc,
7764 AttributeList *AttrList);
7766 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7767 IdentifierInfo *ClassName,
7768 SourceLocation ClassLoc,
7769 ObjCTypeParamList *typeParamList,
7770 IdentifierInfo *CategoryName,
7771 SourceLocation CategoryLoc,
7772 Decl * const *ProtoRefs,
7773 unsigned NumProtoRefs,
7774 const SourceLocation *ProtoLocs,
7775 SourceLocation EndProtoLoc,
7776 AttributeList *AttrList);
7778 Decl *ActOnStartClassImplementation(
7779 SourceLocation AtClassImplLoc,
7780 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7781 IdentifierInfo *SuperClassname,
7782 SourceLocation SuperClassLoc);
7784 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7785 IdentifierInfo *ClassName,
7786 SourceLocation ClassLoc,
7787 IdentifierInfo *CatName,
7788 SourceLocation CatLoc);
7790 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7791 ArrayRef<Decl *> Decls);
7793 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7794 IdentifierInfo **IdentList,
7795 SourceLocation *IdentLocs,
7796 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7799 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7800 ArrayRef<IdentifierLocPair> IdentList,
7801 AttributeList *attrList);
7803 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7804 ArrayRef<IdentifierLocPair> ProtocolId,
7805 SmallVectorImpl<Decl *> &Protocols);
7807 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7808 SourceLocation ProtocolLoc,
7809 IdentifierInfo *TypeArgId,
7810 SourceLocation TypeArgLoc,
7811 bool SelectProtocolFirst = false);
7813 /// Given a list of identifiers (and their locations), resolve the
7814 /// names to either Objective-C protocol qualifiers or type
7815 /// arguments, as appropriate.
7816 void actOnObjCTypeArgsOrProtocolQualifiers(
7818 ParsedType baseType,
7819 SourceLocation lAngleLoc,
7820 ArrayRef<IdentifierInfo *> identifiers,
7821 ArrayRef<SourceLocation> identifierLocs,
7822 SourceLocation rAngleLoc,
7823 SourceLocation &typeArgsLAngleLoc,
7824 SmallVectorImpl<ParsedType> &typeArgs,
7825 SourceLocation &typeArgsRAngleLoc,
7826 SourceLocation &protocolLAngleLoc,
7827 SmallVectorImpl<Decl *> &protocols,
7828 SourceLocation &protocolRAngleLoc,
7829 bool warnOnIncompleteProtocols);
7831 /// Build a an Objective-C protocol-qualified 'id' type where no
7832 /// base type was specified.
7833 TypeResult actOnObjCProtocolQualifierType(
7834 SourceLocation lAngleLoc,
7835 ArrayRef<Decl *> protocols,
7836 ArrayRef<SourceLocation> protocolLocs,
7837 SourceLocation rAngleLoc);
7839 /// Build a specialized and/or protocol-qualified Objective-C type.
7840 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7843 ParsedType BaseType,
7844 SourceLocation TypeArgsLAngleLoc,
7845 ArrayRef<ParsedType> TypeArgs,
7846 SourceLocation TypeArgsRAngleLoc,
7847 SourceLocation ProtocolLAngleLoc,
7848 ArrayRef<Decl *> Protocols,
7849 ArrayRef<SourceLocation> ProtocolLocs,
7850 SourceLocation ProtocolRAngleLoc);
7852 /// Build an Objective-C type parameter type.
7853 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7854 SourceLocation ProtocolLAngleLoc,
7855 ArrayRef<ObjCProtocolDecl *> Protocols,
7856 ArrayRef<SourceLocation> ProtocolLocs,
7857 SourceLocation ProtocolRAngleLoc,
7858 bool FailOnError = false);
7860 /// Build an Objective-C object pointer type.
7861 QualType BuildObjCObjectType(QualType BaseType,
7863 SourceLocation TypeArgsLAngleLoc,
7864 ArrayRef<TypeSourceInfo *> TypeArgs,
7865 SourceLocation TypeArgsRAngleLoc,
7866 SourceLocation ProtocolLAngleLoc,
7867 ArrayRef<ObjCProtocolDecl *> Protocols,
7868 ArrayRef<SourceLocation> ProtocolLocs,
7869 SourceLocation ProtocolRAngleLoc,
7870 bool FailOnError = false);
7872 /// Check the application of the Objective-C '__kindof' qualifier to
7874 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7876 /// Ensure attributes are consistent with type.
7877 /// \param [in, out] Attributes The attributes to check; they will
7878 /// be modified to be consistent with \p PropertyTy.
7879 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7881 unsigned &Attributes,
7882 bool propertyInPrimaryClass);
7884 /// Process the specified property declaration and create decls for the
7885 /// setters and getters as needed.
7886 /// \param property The property declaration being processed
7887 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7890 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7891 ObjCPropertyDecl *SuperProperty,
7892 const IdentifierInfo *Name,
7893 bool OverridingProtocolProperty);
7895 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7896 ObjCInterfaceDecl *ID);
7898 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7899 ArrayRef<Decl *> allMethods = None,
7900 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7902 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7903 SourceLocation LParenLoc,
7904 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7905 Selector GetterSel, Selector SetterSel,
7906 tok::ObjCKeywordKind MethodImplKind,
7907 DeclContext *lexicalDC = nullptr);
7909 Decl *ActOnPropertyImplDecl(Scope *S,
7910 SourceLocation AtLoc,
7911 SourceLocation PropertyLoc,
7913 IdentifierInfo *PropertyId,
7914 IdentifierInfo *PropertyIvar,
7915 SourceLocation PropertyIvarLoc,
7916 ObjCPropertyQueryKind QueryKind);
7918 enum ObjCSpecialMethodKind {
7924 OSMK_NonRetainingInit
7927 struct ObjCArgInfo {
7928 IdentifierInfo *Name;
7929 SourceLocation NameLoc;
7930 // The Type is null if no type was specified, and the DeclSpec is invalid
7933 ObjCDeclSpec DeclSpec;
7935 /// ArgAttrs - Attribute list for this argument.
7936 AttributeList *ArgAttrs;
7939 Decl *ActOnMethodDeclaration(
7941 SourceLocation BeginLoc, // location of the + or -.
7942 SourceLocation EndLoc, // location of the ; or {.
7943 tok::TokenKind MethodType,
7944 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7945 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7946 // optional arguments. The number of types/arguments is obtained
7947 // from the Sel.getNumArgs().
7948 ObjCArgInfo *ArgInfo,
7949 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7950 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7951 bool isVariadic, bool MethodDefinition);
7953 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7954 const ObjCObjectPointerType *OPT,
7956 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7959 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7960 bool inferObjCARCLifetime(ValueDecl *decl);
7963 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7965 SourceLocation OpLoc,
7966 DeclarationName MemberName,
7967 SourceLocation MemberLoc,
7968 SourceLocation SuperLoc, QualType SuperType,
7972 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7973 IdentifierInfo &propertyName,
7974 SourceLocation receiverNameLoc,
7975 SourceLocation propertyNameLoc);
7977 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7979 /// \brief Describes the kind of message expression indicated by a message
7980 /// send that starts with an identifier.
7981 enum ObjCMessageKind {
7982 /// \brief The message is sent to 'super'.
7984 /// \brief The message is an instance message.
7985 ObjCInstanceMessage,
7986 /// \brief The message is a class message, and the identifier is a type
7991 ObjCMessageKind getObjCMessageKind(Scope *S,
7992 IdentifierInfo *Name,
7993 SourceLocation NameLoc,
7995 bool HasTrailingDot,
7996 ParsedType &ReceiverType);
7998 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8000 SourceLocation LBracLoc,
8001 ArrayRef<SourceLocation> SelectorLocs,
8002 SourceLocation RBracLoc,
8005 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8006 QualType ReceiverType,
8007 SourceLocation SuperLoc,
8009 ObjCMethodDecl *Method,
8010 SourceLocation LBracLoc,
8011 ArrayRef<SourceLocation> SelectorLocs,
8012 SourceLocation RBracLoc,
8014 bool isImplicit = false);
8016 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8017 bool isSuperReceiver,
8020 ObjCMethodDecl *Method,
8023 ExprResult ActOnClassMessage(Scope *S,
8024 ParsedType Receiver,
8026 SourceLocation LBracLoc,
8027 ArrayRef<SourceLocation> SelectorLocs,
8028 SourceLocation RBracLoc,
8031 ExprResult BuildInstanceMessage(Expr *Receiver,
8032 QualType ReceiverType,
8033 SourceLocation SuperLoc,
8035 ObjCMethodDecl *Method,
8036 SourceLocation LBracLoc,
8037 ArrayRef<SourceLocation> SelectorLocs,
8038 SourceLocation RBracLoc,
8040 bool isImplicit = false);
8042 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8043 QualType ReceiverType,
8046 ObjCMethodDecl *Method,
8049 ExprResult ActOnInstanceMessage(Scope *S,
8052 SourceLocation LBracLoc,
8053 ArrayRef<SourceLocation> SelectorLocs,
8054 SourceLocation RBracLoc,
8057 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8058 ObjCBridgeCastKind Kind,
8059 SourceLocation BridgeKeywordLoc,
8060 TypeSourceInfo *TSInfo,
8063 ExprResult ActOnObjCBridgedCast(Scope *S,
8064 SourceLocation LParenLoc,
8065 ObjCBridgeCastKind Kind,
8066 SourceLocation BridgeKeywordLoc,
8068 SourceLocation RParenLoc,
8071 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8073 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8075 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8078 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8079 QualType DestType, QualType SrcType,
8080 ObjCInterfaceDecl *&RelatedClass,
8081 ObjCMethodDecl *&ClassMethod,
8082 ObjCMethodDecl *&InstanceMethod,
8083 TypedefNameDecl *&TDNDecl,
8084 bool CfToNs, bool Diagnose = true);
8086 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8087 QualType DestType, QualType SrcType,
8088 Expr *&SrcExpr, bool Diagnose = true);
8090 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8091 bool Diagnose = true);
8093 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8095 /// \brief Check whether the given new method is a valid override of the
8096 /// given overridden method, and set any properties that should be inherited.
8097 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8098 const ObjCMethodDecl *Overridden);
8100 /// \brief Describes the compatibility of a result type with its method.
8101 enum ResultTypeCompatibilityKind {
8107 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8108 ObjCInterfaceDecl *CurrentClass,
8109 ResultTypeCompatibilityKind RTC);
8111 enum PragmaOptionsAlignKind {
8112 POAK_Native, // #pragma options align=native
8113 POAK_Natural, // #pragma options align=natural
8114 POAK_Packed, // #pragma options align=packed
8115 POAK_Power, // #pragma options align=power
8116 POAK_Mac68k, // #pragma options align=mac68k
8117 POAK_Reset // #pragma options align=reset
8120 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8121 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8122 SourceLocation PragmaLoc);
8124 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8125 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8126 StringRef SlotLabel, Expr *Alignment);
8128 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8129 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8131 /// ActOnPragmaMSComment - Called on well formed
8132 /// \#pragma comment(kind, "arg").
8133 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8136 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8137 /// pointers_to_members(representation method[, general purpose
8138 /// representation]).
8139 void ActOnPragmaMSPointersToMembers(
8140 LangOptions::PragmaMSPointersToMembersKind Kind,
8141 SourceLocation PragmaLoc);
8143 /// \brief Called on well formed \#pragma vtordisp().
8144 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8145 SourceLocation PragmaLoc,
8146 MSVtorDispAttr::Mode Value);
8148 enum PragmaSectionKind {
8155 bool UnifySection(StringRef SectionName,
8157 DeclaratorDecl *TheDecl);
8158 bool UnifySection(StringRef SectionName,
8160 SourceLocation PragmaSectionLocation);
8162 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8163 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8164 PragmaMsStackAction Action,
8165 llvm::StringRef StackSlotLabel,
8166 StringLiteral *SegmentName,
8167 llvm::StringRef PragmaName);
8169 /// \brief Called on well formed \#pragma section().
8170 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8171 int SectionFlags, StringLiteral *SegmentName);
8173 /// \brief Called on well-formed \#pragma init_seg().
8174 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8175 StringLiteral *SegmentName);
8177 /// \brief Called on #pragma clang __debug dump II
8178 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8180 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8181 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8184 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8185 void ActOnPragmaUnused(const Token &Identifier,
8187 SourceLocation PragmaLoc);
8189 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8190 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8191 SourceLocation PragmaLoc);
8193 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8194 SourceLocation Loc);
8195 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8197 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8198 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8199 SourceLocation PragmaLoc,
8200 SourceLocation WeakNameLoc);
8202 /// ActOnPragmaRedefineExtname - Called on well formed
8203 /// \#pragma redefine_extname oldname newname.
8204 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8205 IdentifierInfo* AliasName,
8206 SourceLocation PragmaLoc,
8207 SourceLocation WeakNameLoc,
8208 SourceLocation AliasNameLoc);
8210 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8211 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8212 IdentifierInfo* AliasName,
8213 SourceLocation PragmaLoc,
8214 SourceLocation WeakNameLoc,
8215 SourceLocation AliasNameLoc);
8217 /// ActOnPragmaFPContract - Called on well formed
8218 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8219 /// \#pragma clang fp contract
8220 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8222 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8223 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8224 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8226 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8227 void AddMsStructLayoutForRecord(RecordDecl *RD);
8229 /// FreePackedContext - Deallocate and null out PackContext.
8230 void FreePackedContext();
8232 /// PushNamespaceVisibilityAttr - Note that we've entered a
8233 /// namespace with a visibility attribute.
8234 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8235 SourceLocation Loc);
8237 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8238 /// add an appropriate visibility attribute.
8239 void AddPushedVisibilityAttribute(Decl *RD);
8241 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8242 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8243 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8245 /// FreeVisContext - Deallocate and null out VisContext.
8246 void FreeVisContext();
8248 /// AddCFAuditedAttribute - Check whether we're currently within
8249 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8250 /// the appropriate attribute.
8251 void AddCFAuditedAttribute(Decl *D);
8253 /// \brief Called on well-formed '\#pragma clang attribute push'.
8254 void ActOnPragmaAttributePush(AttributeList &Attribute,
8255 SourceLocation PragmaLoc,
8256 attr::ParsedSubjectMatchRuleSet Rules);
8258 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8259 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8261 /// \brief Adds the attributes that have been specified using the
8262 /// '\#pragma clang attribute push' directives to the given declaration.
8263 void AddPragmaAttributes(Scope *S, Decl *D);
8265 void DiagnoseUnterminatedPragmaAttribute();
8267 /// \brief Called on well formed \#pragma clang optimize.
8268 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8270 /// \brief Get the location for the currently active "\#pragma clang optimize
8271 /// off". If this location is invalid, then the state of the pragma is "on".
8272 SourceLocation getOptimizeOffPragmaLocation() const {
8273 return OptimizeOffPragmaLocation;
8276 /// \brief Only called on function definitions; if there is a pragma in scope
8277 /// with the effect of a range-based optnone, consider marking the function
8278 /// with attribute optnone.
8279 void AddRangeBasedOptnone(FunctionDecl *FD);
8281 /// \brief Adds the 'optnone' attribute to the function declaration if there
8282 /// are no conflicts; Loc represents the location causing the 'optnone'
8283 /// attribute to be added (usually because of a pragma).
8284 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8286 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8287 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8288 unsigned SpellingListIndex, bool IsPackExpansion);
8289 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8290 unsigned SpellingListIndex, bool IsPackExpansion);
8292 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8294 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8295 unsigned SpellingListIndex);
8297 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8299 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8300 unsigned SpellingListIndex);
8302 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8304 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8305 unsigned SpellingListIndex);
8307 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8309 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8310 Expr *MinBlocks, unsigned SpellingListIndex);
8312 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8313 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8314 unsigned SpellingListIndex, bool InInstantiation = false);
8316 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8317 ParameterABI ABI, unsigned SpellingListIndex);
8319 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8320 unsigned SpellingListIndex, bool isNSConsumed,
8321 bool isTemplateInstantiation);
8323 //===--------------------------------------------------------------------===//
8324 // C++ Coroutines TS
8326 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8327 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8328 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8330 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8331 bool IsImplicit = false);
8332 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8333 UnresolvedLookupExpr* Lookup);
8334 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8335 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8336 bool IsImplicit = false);
8337 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8338 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8339 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8341 //===--------------------------------------------------------------------===//
8342 // OpenCL extensions.
8345 std::string CurrOpenCLExtension;
8346 /// Extensions required by an OpenCL type.
8347 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8348 /// Extensions required by an OpenCL declaration.
8349 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8351 llvm::StringRef getCurrentOpenCLExtension() const {
8352 return CurrOpenCLExtension;
8354 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8355 CurrOpenCLExtension = Ext;
8358 /// \brief Set OpenCL extensions for a type which can only be used when these
8359 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8360 /// \param Exts A space separated list of OpenCL extensions.
8361 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8363 /// \brief Set OpenCL extensions for a declaration which can only be
8364 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8366 /// \param Exts A space separated list of OpenCL extensions.
8367 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8369 /// \brief Set current OpenCL extensions for a type which can only be used
8370 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8371 /// empty, do nothing.
8372 void setCurrentOpenCLExtensionForType(QualType T);
8374 /// \brief Set current OpenCL extensions for a declaration which
8375 /// can only be used when these OpenCL extensions are enabled. If current
8376 /// OpenCL extension is empty, do nothing.
8377 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8379 bool isOpenCLDisabledDecl(Decl *FD);
8381 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8382 /// is disabled due to required OpenCL extensions being disabled. If so,
8383 /// emit diagnostics.
8384 /// \return true if type is disabled.
8385 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8387 /// \brief Check if declaration \p D used by expression \p E
8388 /// is disabled due to required OpenCL extensions being disabled. If so,
8389 /// emit diagnostics.
8390 /// \return true if type is disabled.
8391 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8393 //===--------------------------------------------------------------------===//
8394 // OpenMP directives and clauses.
8397 void *VarDataSharingAttributesStack;
8398 /// Set to true inside '#pragma omp declare target' region.
8399 bool IsInOpenMPDeclareTargetContext = false;
8400 /// \brief Initialization of data-sharing attributes stack.
8401 void InitDataSharingAttributesStack();
8402 void DestroyDataSharingAttributesStack();
8404 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8405 bool StrictlyPositive = true);
8406 /// Returns OpenMP nesting level for current directive.
8407 unsigned getOpenMPNestingLevel() const;
8409 /// Push new OpenMP function region for non-capturing function.
8410 void pushOpenMPFunctionRegion();
8412 /// Pop OpenMP function region for non-capturing function.
8413 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8415 /// Checks if a type or a declaration is disabled due to the owning extension
8416 /// being disabled, and emits diagnostic messages if it is disabled.
8417 /// \param D type or declaration to be checked.
8418 /// \param DiagLoc source location for the diagnostic message.
8419 /// \param DiagInfo information to be emitted for the diagnostic message.
8420 /// \param SrcRange source range of the declaration.
8421 /// \param Map maps type or declaration to the extensions.
8422 /// \param Selector selects diagnostic message: 0 for type and 1 for
8424 /// \return true if the type or declaration is disabled.
8425 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8426 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8427 MapT &Map, unsigned Selector = 0,
8428 SourceRange SrcRange = SourceRange());
8431 /// \brief Return true if the provided declaration \a VD should be captured by
8433 /// \param Level Relative level of nested OpenMP construct for that the check
8435 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8437 /// \brief Check if the specified variable is used in one of the private
8438 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8440 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8441 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8442 ExprObjectKind OK, SourceLocation Loc);
8444 /// \brief Check if the specified variable is used in 'private' clause.
8445 /// \param Level Relative level of nested OpenMP construct for that the check
8447 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8449 /// \brief Check if the specified variable is captured by 'target' directive.
8450 /// \param Level Relative level of nested OpenMP construct for that the check
8452 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8454 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8456 /// \brief Called on start of new data sharing attribute block.
8457 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8458 const DeclarationNameInfo &DirName, Scope *CurScope,
8459 SourceLocation Loc);
8460 /// \brief Start analysis of clauses.
8461 void StartOpenMPClause(OpenMPClauseKind K);
8462 /// \brief End analysis of clauses.
8463 void EndOpenMPClause();
8464 /// \brief Called on end of data sharing attribute block.
8465 void EndOpenMPDSABlock(Stmt *CurDirective);
8467 /// \brief Check if the current region is an OpenMP loop region and if it is,
8468 /// mark loop control variable, used in \p Init for loop initialization, as
8469 /// private by default.
8470 /// \param Init First part of the for loop.
8471 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8473 // OpenMP directives and clauses.
8474 /// \brief Called on correct id-expression from the '#pragma omp
8476 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8477 CXXScopeSpec &ScopeSpec,
8478 const DeclarationNameInfo &Id);
8479 /// \brief Called on well-formed '#pragma omp threadprivate'.
8480 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8482 ArrayRef<Expr *> VarList);
8483 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8484 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8486 ArrayRef<Expr *> VarList);
8487 /// \brief Check if the specified type is allowed to be used in 'omp declare
8488 /// reduction' construct.
8489 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8490 TypeResult ParsedType);
8491 /// \brief Called on start of '#pragma omp declare reduction'.
8492 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8493 Scope *S, DeclContext *DC, DeclarationName Name,
8494 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8495 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8496 /// \brief Initialize declare reduction construct initializer.
8497 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8498 /// \brief Finish current declare reduction construct initializer.
8499 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8500 /// \brief Initialize declare reduction construct initializer.
8501 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8502 /// \brief Finish current declare reduction construct initializer.
8503 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8504 /// \brief Called at the end of '#pragma omp declare reduction'.
8505 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8506 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8508 /// Called on the start of target region i.e. '#pragma omp declare target'.
8509 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8510 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8511 void ActOnFinishOpenMPDeclareTargetDirective();
8512 /// Called on correct id-expression from the '#pragma omp declare target'.
8513 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8514 const DeclarationNameInfo &Id,
8515 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8516 NamedDeclSetType &SameDirectiveDecls);
8517 /// Check declaration inside target region.
8518 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8519 /// Return true inside OpenMP target region.
8520 bool isInOpenMPDeclareTargetContext() const {
8521 return IsInOpenMPDeclareTargetContext;
8524 /// Return the number of captured regions created for an OpenMP directive.
8525 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8527 /// \brief Initialization of captured region for OpenMP region.
8528 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8529 /// \brief End of OpenMP region.
8531 /// \param S Statement associated with the current OpenMP region.
8532 /// \param Clauses List of clauses for the current OpenMP region.
8534 /// \returns Statement for finished OpenMP region.
8535 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8536 StmtResult ActOnOpenMPExecutableDirective(
8537 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8538 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8539 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8540 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8541 /// of the associated statement.
8542 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8544 SourceLocation StartLoc,
8545 SourceLocation EndLoc);
8546 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8547 /// of the associated statement.
8548 StmtResult ActOnOpenMPSimdDirective(
8549 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8550 SourceLocation EndLoc,
8551 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8552 /// \brief Called on well-formed '\#pragma omp for' after parsing
8553 /// of the associated statement.
8554 StmtResult ActOnOpenMPForDirective(
8555 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8556 SourceLocation EndLoc,
8557 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8558 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8559 /// of the associated statement.
8560 StmtResult ActOnOpenMPForSimdDirective(
8561 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8562 SourceLocation EndLoc,
8563 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8564 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8565 /// of the associated statement.
8566 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8567 Stmt *AStmt, SourceLocation StartLoc,
8568 SourceLocation EndLoc);
8569 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8570 /// associated statement.
8571 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8572 SourceLocation EndLoc);
8573 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8574 /// associated statement.
8575 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8576 Stmt *AStmt, SourceLocation StartLoc,
8577 SourceLocation EndLoc);
8578 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8579 /// associated statement.
8580 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8581 SourceLocation EndLoc);
8582 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8583 /// associated statement.
8584 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8585 ArrayRef<OMPClause *> Clauses,
8586 Stmt *AStmt, SourceLocation StartLoc,
8587 SourceLocation EndLoc);
8588 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8589 /// of the associated statement.
8590 StmtResult ActOnOpenMPParallelForDirective(
8591 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8592 SourceLocation EndLoc,
8593 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8594 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8595 /// parsing of the associated statement.
8596 StmtResult ActOnOpenMPParallelForSimdDirective(
8597 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8598 SourceLocation EndLoc,
8599 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8600 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8601 /// parsing of the associated statement.
8602 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8604 SourceLocation StartLoc,
8605 SourceLocation EndLoc);
8606 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8607 /// associated statement.
8608 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8609 Stmt *AStmt, SourceLocation StartLoc,
8610 SourceLocation EndLoc);
8611 /// \brief Called on well-formed '\#pragma omp taskyield'.
8612 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8613 SourceLocation EndLoc);
8614 /// \brief Called on well-formed '\#pragma omp barrier'.
8615 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8616 SourceLocation EndLoc);
8617 /// \brief Called on well-formed '\#pragma omp taskwait'.
8618 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8619 SourceLocation EndLoc);
8620 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8621 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8622 SourceLocation EndLoc);
8623 /// \brief Called on well-formed '\#pragma omp flush'.
8624 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8625 SourceLocation StartLoc,
8626 SourceLocation EndLoc);
8627 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8628 /// associated statement.
8629 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8630 Stmt *AStmt, SourceLocation StartLoc,
8631 SourceLocation EndLoc);
8632 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8633 /// associated statement.
8634 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8635 Stmt *AStmt, SourceLocation StartLoc,
8636 SourceLocation EndLoc);
8637 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8638 /// associated statement.
8639 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8640 Stmt *AStmt, SourceLocation StartLoc,
8641 SourceLocation EndLoc);
8642 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8643 /// the associated statement.
8644 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8645 Stmt *AStmt, SourceLocation StartLoc,
8646 SourceLocation EndLoc);
8647 /// \brief Called on well-formed '\#pragma omp target enter data' after
8648 /// parsing of the associated statement.
8649 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8650 SourceLocation StartLoc,
8651 SourceLocation EndLoc);
8652 /// \brief Called on well-formed '\#pragma omp target exit data' after
8653 /// parsing of the associated statement.
8654 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8655 SourceLocation StartLoc,
8656 SourceLocation EndLoc);
8657 /// \brief Called on well-formed '\#pragma omp target parallel' after
8658 /// parsing of the associated statement.
8659 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8661 SourceLocation StartLoc,
8662 SourceLocation EndLoc);
8663 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8664 /// parsing of the associated statement.
8665 StmtResult ActOnOpenMPTargetParallelForDirective(
8666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8667 SourceLocation EndLoc,
8668 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8669 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8670 /// associated statement.
8671 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8672 Stmt *AStmt, SourceLocation StartLoc,
8673 SourceLocation EndLoc);
8674 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8676 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8677 SourceLocation EndLoc,
8678 OpenMPDirectiveKind CancelRegion);
8679 /// \brief Called on well-formed '\#pragma omp cancel'.
8680 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8681 SourceLocation StartLoc,
8682 SourceLocation EndLoc,
8683 OpenMPDirectiveKind CancelRegion);
8684 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8685 /// associated statement.
8686 StmtResult ActOnOpenMPTaskLoopDirective(
8687 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8688 SourceLocation EndLoc,
8689 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8690 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8691 /// the associated statement.
8692 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8693 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8694 SourceLocation EndLoc,
8695 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8696 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8697 /// of the associated statement.
8698 StmtResult ActOnOpenMPDistributeDirective(
8699 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8700 SourceLocation EndLoc,
8701 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8702 /// \brief Called on well-formed '\#pragma omp target update'.
8703 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8704 SourceLocation StartLoc,
8705 SourceLocation EndLoc);
8706 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8707 /// parsing of the associated statement.
8708 StmtResult ActOnOpenMPDistributeParallelForDirective(
8709 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8710 SourceLocation EndLoc,
8711 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8712 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8713 /// after parsing of the associated statement.
8714 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8715 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8716 SourceLocation EndLoc,
8717 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8718 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8719 /// parsing of the associated statement.
8720 StmtResult ActOnOpenMPDistributeSimdDirective(
8721 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8722 SourceLocation EndLoc,
8723 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8724 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8725 /// parsing of the associated statement.
8726 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8727 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8728 SourceLocation EndLoc,
8729 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8730 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8731 /// the associated statement.
8732 StmtResult ActOnOpenMPTargetSimdDirective(
8733 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8734 SourceLocation EndLoc,
8735 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8736 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8737 /// the associated statement.
8738 StmtResult ActOnOpenMPTeamsDistributeDirective(
8739 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8740 SourceLocation EndLoc,
8741 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8742 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8743 /// of the associated statement.
8744 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8745 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8746 SourceLocation EndLoc,
8747 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8748 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8749 /// after parsing of the associated statement.
8750 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8751 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8752 SourceLocation EndLoc,
8753 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8754 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8755 /// after parsing of the associated statement.
8756 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8758 SourceLocation EndLoc,
8759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8760 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8761 /// associated statement.
8762 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8764 SourceLocation StartLoc,
8765 SourceLocation EndLoc);
8766 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8767 /// of the associated statement.
8768 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8769 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8770 SourceLocation EndLoc,
8771 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8772 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8773 /// after parsing of the associated statement.
8774 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8775 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8776 SourceLocation EndLoc,
8777 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8778 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8779 /// simd' after parsing of the associated statement.
8780 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8781 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8782 SourceLocation EndLoc,
8783 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8784 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8785 /// parsing of the associated statement.
8786 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8787 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8788 SourceLocation EndLoc,
8789 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8791 /// Checks correctness of linear modifiers.
8792 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8793 SourceLocation LinLoc);
8794 /// Checks that the specified declaration matches requirements for the linear
8796 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8797 OpenMPLinearClauseKind LinKind, QualType Type);
8799 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8800 /// the associated method/function.
8801 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8802 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8803 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8804 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8805 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8807 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8809 SourceLocation StartLoc,
8810 SourceLocation LParenLoc,
8811 SourceLocation EndLoc);
8812 /// \brief Called on well-formed 'if' clause.
8813 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8814 Expr *Condition, SourceLocation StartLoc,
8815 SourceLocation LParenLoc,
8816 SourceLocation NameModifierLoc,
8817 SourceLocation ColonLoc,
8818 SourceLocation EndLoc);
8819 /// \brief Called on well-formed 'final' clause.
8820 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8821 SourceLocation LParenLoc,
8822 SourceLocation EndLoc);
8823 /// \brief Called on well-formed 'num_threads' clause.
8824 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8825 SourceLocation StartLoc,
8826 SourceLocation LParenLoc,
8827 SourceLocation EndLoc);
8828 /// \brief Called on well-formed 'safelen' clause.
8829 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8830 SourceLocation StartLoc,
8831 SourceLocation LParenLoc,
8832 SourceLocation EndLoc);
8833 /// \brief Called on well-formed 'simdlen' clause.
8834 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8835 SourceLocation LParenLoc,
8836 SourceLocation EndLoc);
8837 /// \brief Called on well-formed 'collapse' clause.
8838 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8839 SourceLocation StartLoc,
8840 SourceLocation LParenLoc,
8841 SourceLocation EndLoc);
8842 /// \brief Called on well-formed 'ordered' clause.
8844 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8845 SourceLocation LParenLoc = SourceLocation(),
8846 Expr *NumForLoops = nullptr);
8847 /// \brief Called on well-formed 'grainsize' clause.
8848 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8849 SourceLocation LParenLoc,
8850 SourceLocation EndLoc);
8851 /// \brief Called on well-formed 'num_tasks' clause.
8852 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8853 SourceLocation LParenLoc,
8854 SourceLocation EndLoc);
8855 /// \brief Called on well-formed 'hint' clause.
8856 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8857 SourceLocation LParenLoc,
8858 SourceLocation EndLoc);
8860 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8862 SourceLocation ArgumentLoc,
8863 SourceLocation StartLoc,
8864 SourceLocation LParenLoc,
8865 SourceLocation EndLoc);
8866 /// \brief Called on well-formed 'default' clause.
8867 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8868 SourceLocation KindLoc,
8869 SourceLocation StartLoc,
8870 SourceLocation LParenLoc,
8871 SourceLocation EndLoc);
8872 /// \brief Called on well-formed 'proc_bind' clause.
8873 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8874 SourceLocation KindLoc,
8875 SourceLocation StartLoc,
8876 SourceLocation LParenLoc,
8877 SourceLocation EndLoc);
8879 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8880 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8881 SourceLocation StartLoc, SourceLocation LParenLoc,
8882 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8883 SourceLocation EndLoc);
8884 /// \brief Called on well-formed 'schedule' clause.
8885 OMPClause *ActOnOpenMPScheduleClause(
8886 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8887 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8888 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8889 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8891 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8892 SourceLocation EndLoc);
8893 /// \brief Called on well-formed 'nowait' clause.
8894 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8895 SourceLocation EndLoc);
8896 /// \brief Called on well-formed 'untied' clause.
8897 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8898 SourceLocation EndLoc);
8899 /// \brief Called on well-formed 'mergeable' clause.
8900 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8901 SourceLocation EndLoc);
8902 /// \brief Called on well-formed 'read' clause.
8903 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8904 SourceLocation EndLoc);
8905 /// \brief Called on well-formed 'write' clause.
8906 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8907 SourceLocation EndLoc);
8908 /// \brief Called on well-formed 'update' clause.
8909 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8910 SourceLocation EndLoc);
8911 /// \brief Called on well-formed 'capture' clause.
8912 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8913 SourceLocation EndLoc);
8914 /// \brief Called on well-formed 'seq_cst' clause.
8915 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8916 SourceLocation EndLoc);
8917 /// \brief Called on well-formed 'threads' clause.
8918 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8919 SourceLocation EndLoc);
8920 /// \brief Called on well-formed 'simd' clause.
8921 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8922 SourceLocation EndLoc);
8923 /// \brief Called on well-formed 'nogroup' clause.
8924 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8925 SourceLocation EndLoc);
8927 OMPClause *ActOnOpenMPVarListClause(
8928 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8929 SourceLocation StartLoc, SourceLocation LParenLoc,
8930 SourceLocation ColonLoc, SourceLocation EndLoc,
8931 CXXScopeSpec &ReductionIdScopeSpec,
8932 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8933 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8934 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8935 SourceLocation DepLinMapLoc);
8936 /// \brief Called on well-formed 'private' clause.
8937 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8938 SourceLocation StartLoc,
8939 SourceLocation LParenLoc,
8940 SourceLocation EndLoc);
8941 /// \brief Called on well-formed 'firstprivate' clause.
8942 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8943 SourceLocation StartLoc,
8944 SourceLocation LParenLoc,
8945 SourceLocation EndLoc);
8946 /// \brief Called on well-formed 'lastprivate' clause.
8947 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8948 SourceLocation StartLoc,
8949 SourceLocation LParenLoc,
8950 SourceLocation EndLoc);
8951 /// \brief Called on well-formed 'shared' clause.
8952 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8953 SourceLocation StartLoc,
8954 SourceLocation LParenLoc,
8955 SourceLocation EndLoc);
8956 /// \brief Called on well-formed 'reduction' clause.
8957 OMPClause *ActOnOpenMPReductionClause(
8958 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8959 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8960 CXXScopeSpec &ReductionIdScopeSpec,
8961 const DeclarationNameInfo &ReductionId,
8962 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8963 /// \brief Called on well-formed 'linear' clause.
8965 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8966 SourceLocation StartLoc, SourceLocation LParenLoc,
8967 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8968 SourceLocation ColonLoc, SourceLocation EndLoc);
8969 /// \brief Called on well-formed 'aligned' clause.
8970 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8972 SourceLocation StartLoc,
8973 SourceLocation LParenLoc,
8974 SourceLocation ColonLoc,
8975 SourceLocation EndLoc);
8976 /// \brief Called on well-formed 'copyin' clause.
8977 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8978 SourceLocation StartLoc,
8979 SourceLocation LParenLoc,
8980 SourceLocation EndLoc);
8981 /// \brief Called on well-formed 'copyprivate' clause.
8982 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8983 SourceLocation StartLoc,
8984 SourceLocation LParenLoc,
8985 SourceLocation EndLoc);
8986 /// \brief Called on well-formed 'flush' pseudo clause.
8987 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8988 SourceLocation StartLoc,
8989 SourceLocation LParenLoc,
8990 SourceLocation EndLoc);
8991 /// \brief Called on well-formed 'depend' clause.
8993 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8994 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8995 SourceLocation StartLoc, SourceLocation LParenLoc,
8996 SourceLocation EndLoc);
8997 /// \brief Called on well-formed 'device' clause.
8998 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8999 SourceLocation LParenLoc,
9000 SourceLocation EndLoc);
9001 /// \brief Called on well-formed 'map' clause.
9003 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9004 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9005 SourceLocation MapLoc, SourceLocation ColonLoc,
9006 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9007 SourceLocation LParenLoc, SourceLocation EndLoc);
9008 /// \brief Called on well-formed 'num_teams' clause.
9009 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9010 SourceLocation LParenLoc,
9011 SourceLocation EndLoc);
9012 /// \brief Called on well-formed 'thread_limit' clause.
9013 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9014 SourceLocation StartLoc,
9015 SourceLocation LParenLoc,
9016 SourceLocation EndLoc);
9017 /// \brief Called on well-formed 'priority' clause.
9018 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9019 SourceLocation LParenLoc,
9020 SourceLocation EndLoc);
9021 /// \brief Called on well-formed 'dist_schedule' clause.
9022 OMPClause *ActOnOpenMPDistScheduleClause(
9023 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9024 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9025 SourceLocation CommaLoc, SourceLocation EndLoc);
9026 /// \brief Called on well-formed 'defaultmap' clause.
9027 OMPClause *ActOnOpenMPDefaultmapClause(
9028 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9029 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9030 SourceLocation KindLoc, SourceLocation EndLoc);
9031 /// \brief Called on well-formed 'to' clause.
9032 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9033 SourceLocation StartLoc,
9034 SourceLocation LParenLoc,
9035 SourceLocation EndLoc);
9036 /// \brief Called on well-formed 'from' clause.
9037 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9038 SourceLocation StartLoc,
9039 SourceLocation LParenLoc,
9040 SourceLocation EndLoc);
9041 /// Called on well-formed 'use_device_ptr' clause.
9042 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9043 SourceLocation StartLoc,
9044 SourceLocation LParenLoc,
9045 SourceLocation EndLoc);
9046 /// Called on well-formed 'is_device_ptr' clause.
9047 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9048 SourceLocation StartLoc,
9049 SourceLocation LParenLoc,
9050 SourceLocation EndLoc);
9052 /// \brief The kind of conversion being performed.
9053 enum CheckedConversionKind {
9054 /// \brief An implicit conversion.
9055 CCK_ImplicitConversion,
9056 /// \brief A C-style cast.
9058 /// \brief A functional-style cast.
9060 /// \brief A cast other than a C-style cast.
9064 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9065 /// cast. If there is already an implicit cast, merge into the existing one.
9066 /// If isLvalue, the result of the cast is an lvalue.
9067 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9068 ExprValueKind VK = VK_RValue,
9069 const CXXCastPath *BasePath = nullptr,
9070 CheckedConversionKind CCK
9071 = CCK_ImplicitConversion);
9073 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9074 /// to the conversion from scalar type ScalarTy to the Boolean type.
9075 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9077 /// IgnoredValueConversions - Given that an expression's result is
9078 /// syntactically ignored, perform any conversions that are
9080 ExprResult IgnoredValueConversions(Expr *E);
9082 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9083 // functions and arrays to their respective pointers (C99 6.3.2.1).
9084 ExprResult UsualUnaryConversions(Expr *E);
9086 /// CallExprUnaryConversions - a special case of an unary conversion
9087 /// performed on a function designator of a call expression.
9088 ExprResult CallExprUnaryConversions(Expr *E);
9090 // DefaultFunctionArrayConversion - converts functions and arrays
9091 // to their respective pointers (C99 6.3.2.1).
9092 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9094 // DefaultFunctionArrayLvalueConversion - converts functions and
9095 // arrays to their respective pointers and performs the
9096 // lvalue-to-rvalue conversion.
9097 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9098 bool Diagnose = true);
9100 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9101 // the operand. This is DefaultFunctionArrayLvalueConversion,
9102 // except that it assumes the operand isn't of function or array
9104 ExprResult DefaultLvalueConversion(Expr *E);
9106 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9107 // do not have a prototype. Integer promotions are performed on each
9108 // argument, and arguments that have type float are promoted to double.
9109 ExprResult DefaultArgumentPromotion(Expr *E);
9111 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9112 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9113 /// we don't have xvalues there.
9114 ExprResult TemporaryMaterializationConversion(Expr *E);
9116 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9117 enum VariadicCallType {
9121 VariadicConstructor,
9122 VariadicDoesNotApply
9125 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9126 const FunctionProtoType *Proto,
9129 // Used for determining in which context a type is allowed to be passed to a
9139 // Determines which VarArgKind fits an expression.
9140 VarArgKind isValidVarArgType(const QualType &Ty);
9142 /// Check to see if the given expression is a valid argument to a variadic
9143 /// function, issuing a diagnostic if not.
9144 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9146 /// Check to see if a given expression could have '.c_str()' called on it.
9147 bool hasCStrMethod(const Expr *E);
9149 /// GatherArgumentsForCall - Collector argument expressions for various
9150 /// form of call prototypes.
9151 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9152 const FunctionProtoType *Proto,
9153 unsigned FirstParam, ArrayRef<Expr *> Args,
9154 SmallVectorImpl<Expr *> &AllArgs,
9155 VariadicCallType CallType = VariadicDoesNotApply,
9156 bool AllowExplicit = false,
9157 bool IsListInitialization = false);
9159 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9160 // will create a runtime trap if the resulting type is not a POD type.
9161 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9162 FunctionDecl *FDecl);
9164 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9165 // operands and then handles various conversions that are common to binary
9166 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9167 // routine returns the first non-arithmetic type found. The client is
9168 // responsible for emitting appropriate error diagnostics.
9169 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9170 bool IsCompAssign = false);
9172 /// AssignConvertType - All of the 'assignment' semantic checks return this
9173 /// enum to indicate whether the assignment was allowed. These checks are
9174 /// done for simple assignments, as well as initialization, return from
9175 /// function, argument passing, etc. The query is phrased in terms of a
9176 /// source and destination type.
9177 enum AssignConvertType {
9178 /// Compatible - the types are compatible according to the standard.
9181 /// PointerToInt - The assignment converts a pointer to an int, which we
9182 /// accept as an extension.
9185 /// IntToPointer - The assignment converts an int to a pointer, which we
9186 /// accept as an extension.
9189 /// FunctionVoidPointer - The assignment is between a function pointer and
9190 /// void*, which the standard doesn't allow, but we accept as an extension.
9191 FunctionVoidPointer,
9193 /// IncompatiblePointer - The assignment is between two pointers types that
9194 /// are not compatible, but we accept them as an extension.
9195 IncompatiblePointer,
9197 /// IncompatiblePointerSign - The assignment is between two pointers types
9198 /// which point to integers which have a different sign, but are otherwise
9199 /// identical. This is a subset of the above, but broken out because it's by
9200 /// far the most common case of incompatible pointers.
9201 IncompatiblePointerSign,
9203 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9204 /// c/v/r qualifiers, which we accept as an extension.
9205 CompatiblePointerDiscardsQualifiers,
9207 /// IncompatiblePointerDiscardsQualifiers - The assignment
9208 /// discards qualifiers that we don't permit to be discarded,
9209 /// like address spaces.
9210 IncompatiblePointerDiscardsQualifiers,
9212 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9213 /// nested pointer types, and the qualifiers other than the first two
9214 /// levels differ e.g. char ** -> const char **, but we accept them as an
9216 IncompatibleNestedPointerQualifiers,
9218 /// IncompatibleVectors - The assignment is between two vector types that
9219 /// have the same size, which we accept as an extension.
9220 IncompatibleVectors,
9222 /// IntToBlockPointer - The assignment converts an int to a block
9223 /// pointer. We disallow this.
9226 /// IncompatibleBlockPointer - The assignment is between two block
9227 /// pointers types that are not compatible.
9228 IncompatibleBlockPointer,
9230 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9231 /// id type and something else (that is incompatible with it). For example,
9232 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9233 IncompatibleObjCQualifiedId,
9235 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9236 /// object with __weak qualifier.
9237 IncompatibleObjCWeakRef,
9239 /// Incompatible - We reject this conversion outright, it is invalid to
9240 /// represent it in the AST.
9244 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9245 /// assignment conversion type specified by ConvTy. This returns true if the
9246 /// conversion was invalid or false if the conversion was accepted.
9247 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9249 QualType DstType, QualType SrcType,
9250 Expr *SrcExpr, AssignmentAction Action,
9251 bool *Complained = nullptr);
9253 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9254 /// enum. If AllowMask is true, then we also allow the complement of a valid
9255 /// value, to be used as a mask.
9256 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9257 bool AllowMask) const;
9259 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9260 /// integer not in the range of enum values.
9261 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9264 /// CheckAssignmentConstraints - Perform type checking for assignment,
9265 /// argument passing, variable initialization, and function return values.
9267 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9271 /// Check assignment constraints and optionally prepare for a conversion of
9272 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9274 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9277 bool ConvertRHS = true);
9279 /// Check assignment constraints for an assignment of RHS to LHSType.
9281 /// \param LHSType The destination type for the assignment.
9282 /// \param RHS The source expression for the assignment.
9283 /// \param Diagnose If \c true, diagnostics may be produced when checking
9284 /// for assignability. If a diagnostic is produced, \p RHS will be
9285 /// set to ExprError(). Note that this function may still return
9286 /// without producing a diagnostic, even for an invalid assignment.
9287 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9288 /// in an audited Core Foundation API and does not need to be checked
9289 /// for ARC retain issues.
9290 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9291 /// conversions necessary to perform the assignment. If \c false,
9292 /// \p Diagnose must also be \c false.
9293 AssignConvertType CheckSingleAssignmentConstraints(
9294 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9295 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9297 // \brief If the lhs type is a transparent union, check whether we
9298 // can initialize the transparent union with the given expression.
9299 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9302 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9304 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9306 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9307 AssignmentAction Action,
9308 bool AllowExplicit = false);
9309 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9310 AssignmentAction Action,
9312 ImplicitConversionSequence& ICS);
9313 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9314 const ImplicitConversionSequence& ICS,
9315 AssignmentAction Action,
9316 CheckedConversionKind CCK
9317 = CCK_ImplicitConversion);
9318 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9319 const StandardConversionSequence& SCS,
9320 AssignmentAction Action,
9321 CheckedConversionKind CCK);
9323 /// the following "Check" methods will return a valid/converted QualType
9324 /// or a null QualType (indicating an error diagnostic was issued).
9326 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9327 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9329 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9331 QualType CheckPointerToMemberOperands( // C++ 5.5
9332 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9333 SourceLocation OpLoc, bool isIndirect);
9334 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9335 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9337 QualType CheckRemainderOperands( // C99 6.5.5
9338 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9339 bool IsCompAssign = false);
9340 QualType CheckAdditionOperands( // C99 6.5.6
9341 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9342 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9343 QualType CheckSubtractionOperands( // C99 6.5.6
9344 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9345 QualType* CompLHSTy = nullptr);
9346 QualType CheckShiftOperands( // C99 6.5.7
9347 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9348 BinaryOperatorKind Opc, bool IsCompAssign = false);
9349 QualType CheckCompareOperands( // C99 6.5.8/9
9350 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9351 BinaryOperatorKind Opc, bool isRelational);
9352 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9353 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9354 BinaryOperatorKind Opc);
9355 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9356 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9357 BinaryOperatorKind Opc);
9358 // CheckAssignmentOperands is used for both simple and compound assignment.
9359 // For simple assignment, pass both expressions and a null converted type.
9360 // For compound assignment, pass both expressions and the converted type.
9361 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9362 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9364 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9365 UnaryOperatorKind Opcode, Expr *Op);
9366 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9367 BinaryOperatorKind Opcode,
9368 Expr *LHS, Expr *RHS);
9369 ExprResult checkPseudoObjectRValue(Expr *E);
9370 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9372 QualType CheckConditionalOperands( // C99 6.5.15
9373 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9374 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9375 QualType CXXCheckConditionalOperands( // C++ 5.16
9376 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9377 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9378 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9379 bool ConvertArgs = true);
9380 QualType FindCompositePointerType(SourceLocation Loc,
9381 ExprResult &E1, ExprResult &E2,
9382 bool ConvertArgs = true) {
9383 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9384 QualType Composite =
9385 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9391 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9392 SourceLocation QuestionLoc);
9394 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9395 SourceLocation QuestionLoc);
9397 void DiagnoseAlwaysNonNullPointer(Expr *E,
9398 Expr::NullPointerConstantKind NullType,
9399 bool IsEqual, SourceRange Range);
9401 /// type checking for vector binary operators.
9402 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9403 SourceLocation Loc, bool IsCompAssign,
9404 bool AllowBothBool, bool AllowBoolConversion);
9405 QualType GetSignedVectorType(QualType V);
9406 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9407 SourceLocation Loc, bool isRelational);
9408 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9409 SourceLocation Loc);
9411 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9412 bool isLaxVectorConversion(QualType srcType, QualType destType);
9414 /// type checking declaration initializers (C99 6.7.8)
9415 bool CheckForConstantInitializer(Expr *e, QualType t);
9417 // type checking C++ declaration initializers (C++ [dcl.init]).
9419 /// ReferenceCompareResult - Expresses the result of comparing two
9420 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9421 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9422 enum ReferenceCompareResult {
9423 /// Ref_Incompatible - The two types are incompatible, so direct
9424 /// reference binding is not possible.
9425 Ref_Incompatible = 0,
9426 /// Ref_Related - The two types are reference-related, which means
9427 /// that their unqualified forms (T1 and T2) are either the same
9428 /// or T1 is a base class of T2.
9430 /// Ref_Compatible - The two types are reference-compatible.
9434 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9435 QualType T1, QualType T2,
9436 bool &DerivedToBase,
9437 bool &ObjCConversion,
9438 bool &ObjCLifetimeConversion);
9440 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9441 Expr *CastExpr, CastKind &CastKind,
9442 ExprValueKind &VK, CXXCastPath &Path);
9444 /// \brief Force an expression with unknown-type to an expression of the
9446 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9448 /// \brief Type-check an expression that's being passed to an
9449 /// __unknown_anytype parameter.
9450 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9451 Expr *result, QualType ¶mType);
9453 // CheckVectorCast - check type constraints for vectors.
9454 // Since vectors are an extension, there are no C standard reference for this.
9455 // We allow casting between vectors and integer datatypes of the same size.
9456 // returns true if the cast is invalid
9457 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9460 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9461 /// implicit casts if necessary.
9462 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9464 // CheckExtVectorCast - check type constraints for extended vectors.
9465 // Since vectors are an extension, there are no C standard reference for this.
9466 // We allow casting between vectors and integer datatypes of the same size,
9467 // or vectors and the element type of that vector.
9468 // returns the cast expr
9469 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9472 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9473 SourceLocation LParenLoc,
9475 SourceLocation RParenLoc);
9477 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9479 /// \brief Checks for invalid conversions and casts between
9480 /// retainable pointers and other pointer kinds for ARC and Weak.
9481 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9482 QualType castType, Expr *&op,
9483 CheckedConversionKind CCK,
9484 bool Diagnose = true,
9485 bool DiagnoseCFAudited = false,
9486 BinaryOperatorKind Opc = BO_PtrMemD
9489 Expr *stripARCUnbridgedCast(Expr *e);
9490 void diagnoseARCUnbridgedCast(Expr *e);
9492 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9495 /// checkRetainCycles - Check whether an Objective-C message send
9496 /// might create an obvious retain cycle.
9497 void checkRetainCycles(ObjCMessageExpr *msg);
9498 void checkRetainCycles(Expr *receiver, Expr *argument);
9499 void checkRetainCycles(VarDecl *Var, Expr *Init);
9501 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9502 /// to weak/__unsafe_unretained type.
9503 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9505 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9506 /// to weak/__unsafe_unretained expression.
9507 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9509 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9510 /// \param Method - May be null.
9511 /// \param [out] ReturnType - The return type of the send.
9512 /// \return true iff there were any incompatible types.
9513 bool CheckMessageArgumentTypes(QualType ReceiverType,
9514 MultiExprArg Args, Selector Sel,
9515 ArrayRef<SourceLocation> SelectorLocs,
9516 ObjCMethodDecl *Method, bool isClassMessage,
9517 bool isSuperMessage,
9518 SourceLocation lbrac, SourceLocation rbrac,
9519 SourceRange RecRange,
9520 QualType &ReturnType, ExprValueKind &VK);
9522 /// \brief Determine the result of a message send expression based on
9523 /// the type of the receiver, the method expected to receive the message,
9524 /// and the form of the message send.
9525 QualType getMessageSendResultType(QualType ReceiverType,
9526 ObjCMethodDecl *Method,
9527 bool isClassMessage, bool isSuperMessage);
9529 /// \brief If the given expression involves a message send to a method
9530 /// with a related result type, emit a note describing what happened.
9531 void EmitRelatedResultTypeNote(const Expr *E);
9533 /// \brief Given that we had incompatible pointer types in a return
9534 /// statement, check whether we're in a method with a related result
9535 /// type, and if so, emit a note describing what happened.
9536 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9538 class ConditionResult {
9540 FullExprArg Condition;
9546 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9548 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9549 HasKnownValue(IsConstexpr && Condition.get() &&
9550 !Condition.get()->isValueDependent()),
9551 KnownValue(HasKnownValue &&
9552 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9553 explicit ConditionResult(bool Invalid)
9554 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9555 HasKnownValue(false), KnownValue(false) {}
9558 ConditionResult() : ConditionResult(false) {}
9559 bool isInvalid() const { return Invalid; }
9560 std::pair<VarDecl *, Expr *> get() const {
9561 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9564 llvm::Optional<bool> getKnownValue() const {
9570 static ConditionResult ConditionError() { return ConditionResult(true); }
9572 enum class ConditionKind {
9573 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9574 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9575 Switch ///< An integral condition for a 'switch' statement.
9578 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9579 Expr *SubExpr, ConditionKind CK);
9581 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9582 SourceLocation StmtLoc,
9585 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9587 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9588 SourceLocation StmtLoc,
9590 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9592 /// CheckBooleanCondition - Diagnose problems involving the use of
9593 /// the given expression as a boolean condition (e.g. in an if
9594 /// statement). Also performs the standard function and array
9595 /// decays, possibly changing the input variable.
9597 /// \param Loc - A location associated with the condition, e.g. the
9599 /// \return true iff there were any errors
9600 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9601 bool IsConstexpr = false);
9603 /// DiagnoseAssignmentAsCondition - Given that an expression is
9604 /// being used as a boolean condition, warn if it's an assignment.
9605 void DiagnoseAssignmentAsCondition(Expr *E);
9607 /// \brief Redundant parentheses over an equality comparison can indicate
9608 /// that the user intended an assignment used as condition.
9609 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9611 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9612 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9614 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9615 /// the specified width and sign. If an overflow occurs, detect it and emit
9616 /// the specified diagnostic.
9617 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9618 unsigned NewWidth, bool NewSign,
9619 SourceLocation Loc, unsigned DiagID);
9621 /// Checks that the Objective-C declaration is declared in the global scope.
9622 /// Emits an error and marks the declaration as invalid if it's not declared
9623 /// in the global scope.
9624 bool CheckObjCDeclScope(Decl *D);
9626 /// \brief Abstract base class used for diagnosing integer constant
9627 /// expression violations.
9628 class VerifyICEDiagnoser {
9632 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9634 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9635 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9636 virtual ~VerifyICEDiagnoser() { }
9639 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9640 /// and reports the appropriate diagnostics. Returns false on success.
9641 /// Can optionally return the value of the expression.
9642 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9643 VerifyICEDiagnoser &Diagnoser,
9644 bool AllowFold = true);
9645 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9647 bool AllowFold = true);
9648 ExprResult VerifyIntegerConstantExpression(Expr *E,
9649 llvm::APSInt *Result = nullptr);
9651 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9652 /// the correct width, and that the field type is valid.
9653 /// Returns false on success.
9654 /// Can optionally return whether the bit-field is of width 0
9655 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9656 QualType FieldTy, bool IsMsStruct,
9657 Expr *BitWidth, bool *ZeroWidth = nullptr);
9660 unsigned ForceCUDAHostDeviceDepth = 0;
9663 /// Increments our count of the number of times we've seen a pragma forcing
9664 /// functions to be __host__ __device__. So long as this count is greater
9665 /// than zero, all functions encountered will be __host__ __device__.
9666 void PushForceCUDAHostDevice();
9668 /// Decrements our count of the number of times we've seen a pragma forcing
9669 /// functions to be __host__ __device__. Returns false if the count is 0
9670 /// before incrementing, so you can emit an error.
9671 bool PopForceCUDAHostDevice();
9673 /// Diagnostics that are emitted only if we discover that the given function
9674 /// must be codegen'ed. Because handling these correctly adds overhead to
9675 /// compilation, this is currently only enabled for CUDA compilations.
9676 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9677 std::vector<PartialDiagnosticAt>>
9680 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9681 /// key in a hashtable, both the FD and location are hashed.
9682 struct FunctionDeclAndLoc {
9683 CanonicalDeclPtr<FunctionDecl> FD;
9687 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9688 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9689 /// same deferred diag twice.
9690 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9692 /// An inverse call graph, mapping known-emitted functions to one of their
9693 /// known-emitted callers (plus the location of the call).
9695 /// Functions that we can tell a priori must be emitted aren't added to this
9697 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9698 /* Caller = */ FunctionDeclAndLoc>
9699 CUDAKnownEmittedFns;
9701 /// A partial call graph maintained during CUDA compilation to support
9702 /// deferred diagnostics.
9704 /// Functions are only added here if, at the time they're considered, they are
9705 /// not known-emitted. As soon as we discover that a function is
9706 /// known-emitted, we remove it and everything it transitively calls from this
9707 /// set and add those functions to CUDAKnownEmittedFns.
9708 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9709 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9713 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9715 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9716 /// which are not allowed to appear inside __device__ functions and are
9717 /// allowed to appear in __host__ __device__ functions only if the host+device
9718 /// function is never codegen'ed.
9720 /// To handle this, we use the notion of "deferred diagnostics", where we
9721 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9723 /// This class lets you emit either a regular diagnostic, a deferred
9724 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9725 /// its constructor, thus simplifying the process of creating these "maybe
9726 /// deferred" diagnostics.
9727 class CUDADiagBuilder {
9730 /// Emit no diagnostics.
9732 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9734 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9735 /// emit a call stack showing how this function can be reached by an a
9736 /// priori known-emitted function.
9737 K_ImmediateWithCallStack,
9738 /// Create a deferred diagnostic, which is emitted only if the function
9739 /// it's attached to is codegen'ed. Also emit a call stack as with
9740 /// K_ImmediateWithCallStack.
9744 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9745 FunctionDecl *Fn, Sema &S);
9748 /// Convertible to bool: True if we immediately emitted an error, false if
9749 /// we didn't emit an error or we created a deferred error.
9753 /// if (CUDADiagBuilder(...) << foo << bar)
9754 /// return ExprError();
9756 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9757 /// want to use these instead of creating a CUDADiagBuilder yourself.
9758 operator bool() const { return ImmediateDiag.hasValue(); }
9760 template <typename T>
9761 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9763 if (Diag.ImmediateDiag.hasValue())
9764 *Diag.ImmediateDiag << Value;
9765 else if (Diag.PartialDiag.hasValue())
9766 *Diag.PartialDiag << Value;
9777 // Invariant: At most one of these Optionals has a value.
9778 // FIXME: Switch these to a Variant once that exists.
9779 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9780 llvm::Optional<PartialDiagnostic> PartialDiag;
9783 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9784 /// is "used as device code".
9786 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9787 /// - If CurContext is a __device__ or __global__ function, emits the
9788 /// diagnostics immediately.
9789 /// - If CurContext is a __host__ __device__ function and we are compiling for
9790 /// the device, creates a diagnostic which is emitted if and when we realize
9791 /// that the function will be codegen'ed.
9795 /// // Variable-length arrays are not allowed in CUDA device code.
9796 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9797 /// return ExprError();
9798 /// // Otherwise, continue parsing as normal.
9799 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9801 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9802 /// is "used as host code".
9804 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9805 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9807 enum CUDAFunctionTarget {
9815 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9818 /// Use this rather than examining the function's attributes yourself -- you
9819 /// will get it wrong. Returns CFT_Host if D is null.
9820 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9821 bool IgnoreImplicitHDAttr = false);
9822 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9824 /// Gets the CUDA target for the current context.
9825 CUDAFunctionTarget CurrentCUDATarget() {
9826 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9829 // CUDA function call preference. Must be ordered numerically from
9831 enum CUDAFunctionPreference {
9832 CFP_Never, // Invalid caller/callee combination.
9833 CFP_WrongSide, // Calls from host-device to host or device
9834 // function that do not match current compilation
9836 CFP_HostDevice, // Any calls to host/device functions.
9837 CFP_SameSide, // Calls from host-device to host or device
9838 // function matching current compilation mode.
9839 CFP_Native, // host-to-host or device-to-device calls.
9842 /// Identifies relative preference of a given Caller/Callee
9843 /// combination, based on their host/device attributes.
9844 /// \param Caller function which needs address of \p Callee.
9845 /// nullptr in case of global context.
9846 /// \param Callee target function
9848 /// \returns preference value for particular Caller/Callee combination.
9849 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9850 const FunctionDecl *Callee);
9852 /// Determines whether Caller may invoke Callee, based on their CUDA
9853 /// host/device attributes. Returns false if the call is not allowed.
9855 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9856 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9857 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9858 const FunctionDecl *Callee) {
9859 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9862 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9863 /// depending on FD and the current compilation settings.
9864 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9865 const LookupResult &Previous);
9868 /// Check whether we're allowed to call Callee from the current context.
9870 /// - If the call is never allowed in a semantically-correct program
9871 /// (CFP_Never), emits an error and returns false.
9873 /// - If the call is allowed in semantically-correct programs, but only if
9874 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9875 /// be emitted if and when the caller is codegen'ed, and returns true.
9877 /// Will only create deferred diagnostics for a given SourceLocation once,
9878 /// so you can safely call this multiple times without generating duplicate
9879 /// deferred errors.
9881 /// - Otherwise, returns true without emitting any diagnostics.
9882 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9884 /// Set __device__ or __host__ __device__ attributes on the given lambda
9885 /// operator() method.
9887 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9888 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9889 /// functions become __host__ __device__ themselves.
9890 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9892 /// Finds a function in \p Matches with highest calling priority
9893 /// from \p Caller context and erases all functions with lower
9894 /// calling priority.
9895 void EraseUnwantedCUDAMatches(
9896 const FunctionDecl *Caller,
9897 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9899 /// Given a implicit special member, infer its CUDA target from the
9900 /// calls it needs to make to underlying base/field special members.
9901 /// \param ClassDecl the class for which the member is being created.
9902 /// \param CSM the kind of special member.
9903 /// \param MemberDecl the special member itself.
9904 /// \param ConstRHS true if this is a copy operation with a const object on
9906 /// \param Diagnose true if this call should emit diagnostics.
9907 /// \return true if there was an error inferring.
9908 /// The result of this call is implicit CUDA target attribute(s) attached to
9909 /// the member declaration.
9910 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9911 CXXSpecialMember CSM,
9912 CXXMethodDecl *MemberDecl,
9916 /// \return true if \p CD can be considered empty according to CUDA
9917 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9918 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9919 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9921 /// Check whether NewFD is a valid overload for CUDA. Emits
9922 /// diagnostics and invalidates NewFD if not.
9923 void checkCUDATargetOverload(FunctionDecl *NewFD,
9924 const LookupResult &Previous);
9925 /// Copies target attributes from the template TD to the function FD.
9926 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9928 /// \name Code completion
9930 /// \brief Describes the context in which code completion occurs.
9931 enum ParserCompletionContext {
9932 /// \brief Code completion occurs at top-level or namespace context.
9934 /// \brief Code completion occurs within a class, struct, or union.
9936 /// \brief Code completion occurs within an Objective-C interface, protocol,
9939 /// \brief Code completion occurs within an Objective-C implementation or
9940 /// category implementation
9941 PCC_ObjCImplementation,
9942 /// \brief Code completion occurs within the list of instance variables
9943 /// in an Objective-C interface, protocol, category, or implementation.
9944 PCC_ObjCInstanceVariableList,
9945 /// \brief Code completion occurs following one or more template
9948 /// \brief Code completion occurs following one or more template
9949 /// headers within a class.
9951 /// \brief Code completion occurs within an expression.
9953 /// \brief Code completion occurs within a statement, which may
9954 /// also be an expression or a declaration.
9956 /// \brief Code completion occurs at the beginning of the
9957 /// initialization statement (or expression) in a for loop.
9959 /// \brief Code completion occurs within the condition of an if,
9960 /// while, switch, or for statement.
9962 /// \brief Code completion occurs within the body of a function on a
9963 /// recovery path, where we do not have a specific handle on our position
9965 PCC_RecoveryInFunction,
9966 /// \brief Code completion occurs where only a type is permitted.
9968 /// \brief Code completion occurs in a parenthesized expression, which
9969 /// might also be a type cast.
9970 PCC_ParenthesizedExpression,
9971 /// \brief Code completion occurs within a sequence of declaration
9972 /// specifiers within a function, method, or block.
9973 PCC_LocalDeclarationSpecifiers
9976 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9977 void CodeCompleteOrdinaryName(Scope *S,
9978 ParserCompletionContext CompletionContext);
9979 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9980 bool AllowNonIdentifiers,
9981 bool AllowNestedNameSpecifiers);
9983 struct CodeCompleteExpressionData;
9984 void CodeCompleteExpression(Scope *S,
9985 const CodeCompleteExpressionData &Data);
9986 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9987 SourceLocation OpLoc, bool IsArrow,
9988 bool IsBaseExprStatement);
9989 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9990 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9991 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9992 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9993 const VirtSpecifiers *VS = nullptr);
9994 void CodeCompleteBracketDeclarator(Scope *S);
9995 void CodeCompleteCase(Scope *S);
9996 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9997 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9998 ArrayRef<Expr *> Args);
9999 void CodeCompleteInitializer(Scope *S, Decl *D);
10000 void CodeCompleteReturn(Scope *S);
10001 void CodeCompleteAfterIf(Scope *S);
10002 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10004 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10005 bool EnteringContext);
10006 void CodeCompleteUsing(Scope *S);
10007 void CodeCompleteUsingDirective(Scope *S);
10008 void CodeCompleteNamespaceDecl(Scope *S);
10009 void CodeCompleteNamespaceAliasDecl(Scope *S);
10010 void CodeCompleteOperatorName(Scope *S);
10011 void CodeCompleteConstructorInitializer(
10013 ArrayRef<CXXCtorInitializer *> Initializers);
10015 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10016 bool AfterAmpersand);
10018 void CodeCompleteObjCAtDirective(Scope *S);
10019 void CodeCompleteObjCAtVisibility(Scope *S);
10020 void CodeCompleteObjCAtStatement(Scope *S);
10021 void CodeCompleteObjCAtExpression(Scope *S);
10022 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10023 void CodeCompleteObjCPropertyGetter(Scope *S);
10024 void CodeCompleteObjCPropertySetter(Scope *S);
10025 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10027 void CodeCompleteObjCMessageReceiver(Scope *S);
10028 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10029 ArrayRef<IdentifierInfo *> SelIdents,
10030 bool AtArgumentExpression);
10031 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10032 ArrayRef<IdentifierInfo *> SelIdents,
10033 bool AtArgumentExpression,
10034 bool IsSuper = false);
10035 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10036 ArrayRef<IdentifierInfo *> SelIdents,
10037 bool AtArgumentExpression,
10038 ObjCInterfaceDecl *Super = nullptr);
10039 void CodeCompleteObjCForCollection(Scope *S,
10040 DeclGroupPtrTy IterationVar);
10041 void CodeCompleteObjCSelector(Scope *S,
10042 ArrayRef<IdentifierInfo *> SelIdents);
10043 void CodeCompleteObjCProtocolReferences(
10044 ArrayRef<IdentifierLocPair> Protocols);
10045 void CodeCompleteObjCProtocolDecl(Scope *S);
10046 void CodeCompleteObjCInterfaceDecl(Scope *S);
10047 void CodeCompleteObjCSuperclass(Scope *S,
10048 IdentifierInfo *ClassName,
10049 SourceLocation ClassNameLoc);
10050 void CodeCompleteObjCImplementationDecl(Scope *S);
10051 void CodeCompleteObjCInterfaceCategory(Scope *S,
10052 IdentifierInfo *ClassName,
10053 SourceLocation ClassNameLoc);
10054 void CodeCompleteObjCImplementationCategory(Scope *S,
10055 IdentifierInfo *ClassName,
10056 SourceLocation ClassNameLoc);
10057 void CodeCompleteObjCPropertyDefinition(Scope *S);
10058 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10059 IdentifierInfo *PropertyName);
10060 void CodeCompleteObjCMethodDecl(Scope *S,
10061 bool IsInstanceMethod,
10062 ParsedType ReturnType);
10063 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10064 bool IsInstanceMethod,
10065 bool AtParameterName,
10066 ParsedType ReturnType,
10067 ArrayRef<IdentifierInfo *> SelIdents);
10068 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10069 SourceLocation ClassNameLoc,
10070 bool IsBaseExprStatement);
10071 void CodeCompletePreprocessorDirective(bool InConditional);
10072 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10073 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10074 void CodeCompletePreprocessorExpression();
10075 void CodeCompletePreprocessorMacroArgument(Scope *S,
10076 IdentifierInfo *Macro,
10077 MacroInfo *MacroInfo,
10078 unsigned Argument);
10079 void CodeCompleteNaturalLanguage();
10080 void CodeCompleteAvailabilityPlatformName();
10081 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10082 CodeCompletionTUInfo &CCTUInfo,
10083 SmallVectorImpl<CodeCompletionResult> &Results);
10086 //===--------------------------------------------------------------------===//
10087 // Extra semantic analysis beyond the C type system
10090 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10091 unsigned ByteNo) const;
10094 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10095 const ArraySubscriptExpr *ASE=nullptr,
10096 bool AllowOnePastEnd=true, bool IndexNegated=false);
10097 void CheckArrayAccess(const Expr *E);
10098 // Used to grab the relevant information from a FormatAttr and a
10099 // FunctionDeclaration.
10100 struct FormatStringInfo {
10101 unsigned FormatIdx;
10102 unsigned FirstDataArg;
10106 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10107 FormatStringInfo *FSI);
10108 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10109 const FunctionProtoType *Proto);
10110 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10111 ArrayRef<const Expr *> Args);
10112 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10113 const FunctionProtoType *Proto);
10114 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10115 void CheckConstructorCall(FunctionDecl *FDecl,
10116 ArrayRef<const Expr *> Args,
10117 const FunctionProtoType *Proto,
10118 SourceLocation Loc);
10120 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10121 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10122 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10123 VariadicCallType CallType);
10125 bool CheckObjCString(Expr *Arg);
10126 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10128 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10129 unsigned BuiltinID, CallExpr *TheCall);
10131 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10132 unsigned MaxWidth);
10133 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10134 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10136 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10137 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10138 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10139 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10140 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10141 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10142 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10144 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10145 bool SemaBuiltinVAStartARM(CallExpr *Call);
10146 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10147 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10148 bool SemaBuiltinVSX(CallExpr *TheCall);
10149 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10152 // Used by C++ template instantiation.
10153 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10154 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10155 SourceLocation BuiltinLoc,
10156 SourceLocation RParenLoc);
10159 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10160 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10161 bool SemaBuiltinAssume(CallExpr *TheCall);
10162 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10163 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10164 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10165 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10166 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10167 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10168 AtomicExpr::AtomicOp Op);
10169 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10170 llvm::APSInt &Result);
10171 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10172 int Low, int High);
10173 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10174 unsigned Multiple);
10175 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10176 int ArgNum, unsigned ExpectedFieldNum,
10179 enum FormatStringType {
10186 FST_FreeBSDKPrintf,
10191 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10193 bool FormatStringHasSArg(const StringLiteral *FExpr);
10195 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10198 bool CheckFormatArguments(const FormatAttr *Format,
10199 ArrayRef<const Expr *> Args,
10201 VariadicCallType CallType,
10202 SourceLocation Loc, SourceRange Range,
10203 llvm::SmallBitVector &CheckedVarArgs);
10204 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10205 bool HasVAListArg, unsigned format_idx,
10206 unsigned firstDataArg, FormatStringType Type,
10207 VariadicCallType CallType,
10208 SourceLocation Loc, SourceRange range,
10209 llvm::SmallBitVector &CheckedVarArgs);
10211 void CheckAbsoluteValueFunction(const CallExpr *Call,
10212 const FunctionDecl *FDecl);
10214 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10216 void CheckMemaccessArguments(const CallExpr *Call,
10218 IdentifierInfo *FnName);
10220 void CheckStrlcpycatArguments(const CallExpr *Call,
10221 IdentifierInfo *FnName);
10223 void CheckStrncatArguments(const CallExpr *Call,
10224 IdentifierInfo *FnName);
10226 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10227 SourceLocation ReturnLoc,
10228 bool isObjCMethod = false,
10229 const AttrVec *Attrs = nullptr,
10230 const FunctionDecl *FD = nullptr);
10232 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10233 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10234 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10235 void CheckUnsequencedOperations(Expr *E);
10237 /// \brief Perform semantic checks on a completed expression. This will either
10238 /// be a full-expression or a default argument expression.
10239 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10240 bool IsConstexpr = false);
10242 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10245 /// Check if there is a field shadowing.
10246 void CheckShadowInheritedFields(const SourceLocation &Loc,
10247 DeclarationName FieldName,
10248 const CXXRecordDecl *RD);
10250 /// \brief Check if the given expression contains 'break' or 'continue'
10251 /// statement that produces control flow different from GCC.
10252 void CheckBreakContinueBinding(Expr *E);
10254 /// \brief Check whether receiver is mutable ObjC container which
10255 /// attempts to add itself into the container
10256 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10258 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10259 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10260 bool DeleteWasArrayForm);
10262 /// \brief Register a magic integral constant to be used as a type tag.
10263 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10264 uint64_t MagicValue, QualType Type,
10265 bool LayoutCompatible, bool MustBeNull);
10267 struct TypeTagData {
10270 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10271 Type(Type), LayoutCompatible(LayoutCompatible),
10272 MustBeNull(MustBeNull)
10277 /// If true, \c Type should be compared with other expression's types for
10278 /// layout-compatibility.
10279 unsigned LayoutCompatible : 1;
10280 unsigned MustBeNull : 1;
10283 /// A pair of ArgumentKind identifier and magic value. This uniquely
10284 /// identifies the magic value.
10285 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10288 /// \brief A map from magic value to type information.
10289 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10290 TypeTagForDatatypeMagicValues;
10292 /// \brief Peform checks on a call of a function with argument_with_type_tag
10293 /// or pointer_with_type_tag attributes.
10294 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10295 const Expr * const *ExprArgs);
10297 /// \brief Check if we are taking the address of a packed field
10298 /// as this may be a problem if the pointer value is dereferenced.
10299 void CheckAddressOfPackedMember(Expr *rhs);
10301 /// \brief The parser's current scope.
10303 /// The parser maintains this state here.
10306 mutable IdentifierInfo *Ident_super;
10307 mutable IdentifierInfo *Ident___float128;
10309 /// Nullability type specifiers.
10310 IdentifierInfo *Ident__Nonnull = nullptr;
10311 IdentifierInfo *Ident__Nullable = nullptr;
10312 IdentifierInfo *Ident__Null_unspecified = nullptr;
10314 IdentifierInfo *Ident_NSError = nullptr;
10317 friend class Parser;
10318 friend class InitializationSequence;
10319 friend class ASTReader;
10320 friend class ASTDeclReader;
10321 friend class ASTWriter;
10324 /// Retrieve the keyword associated
10325 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10327 /// The struct behind the CFErrorRef pointer.
10328 RecordDecl *CFError = nullptr;
10330 /// Retrieve the identifier "NSError".
10331 IdentifierInfo *getNSErrorIdent();
10333 /// \brief Retrieve the parser's current scope.
10335 /// This routine must only be used when it is certain that semantic analysis
10336 /// and the parser are in precisely the same context, which is not the case
10337 /// when, e.g., we are performing any kind of template instantiation.
10338 /// Therefore, the only safe places to use this scope are in the parser
10339 /// itself and in routines directly invoked from the parser and *never* from
10340 /// template substitution or instantiation.
10341 Scope *getCurScope() const { return CurScope; }
10343 void incrementMSManglingNumber() const {
10344 return CurScope->incrementMSManglingNumber();
10347 IdentifierInfo *getSuperIdentifier() const;
10348 IdentifierInfo *getFloat128Identifier() const;
10350 Decl *getObjCDeclContext() const;
10352 DeclContext *getCurLexicalContext() const {
10353 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10356 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10358 /// \param D The declaration to check. Note that this may be altered to point
10359 /// to another declaration that \c D gets it's availability from. i.e., we
10360 /// walk the list of typedefs to find an availability attribute.
10362 /// \param Message If non-null, this will be populated with the message from
10363 /// the availability attribute that is selected.
10364 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10365 std::string *Message);
10367 const DeclContext *getCurObjCLexicalContext() const {
10368 const DeclContext *DC = getCurLexicalContext();
10369 // A category implicitly has the attribute of the interface.
10370 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10371 DC = CatD->getClassInterface();
10375 /// \brief To be used for checking whether the arguments being passed to
10376 /// function exceeds the number of parameters expected for it.
10377 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10378 bool PartialOverloading = false) {
10379 // We check whether we're just after a comma in code-completion.
10380 if (NumArgs > 0 && PartialOverloading)
10381 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10382 return NumArgs > NumParams;
10385 // Emitting members of dllexported classes is delayed until the class
10386 // (including field initializers) is fully parsed.
10387 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10390 /// \brief Helper class that collects misaligned member designations and
10391 /// their location info for delayed diagnostics.
10392 struct MisalignedMember {
10396 CharUnits Alignment;
10398 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10399 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10400 CharUnits Alignment)
10401 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10402 explicit MisalignedMember(Expr *E)
10403 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10405 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10407 /// \brief Small set of gathered accesses to potentially misaligned members
10408 /// due to the packed attribute.
10409 SmallVector<MisalignedMember, 4> MisalignedMembers;
10411 /// \brief Adds an expression to the set of gathered misaligned members.
10412 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10413 CharUnits Alignment);
10416 /// \brief Diagnoses the current set of gathered accesses. This typically
10417 /// happens at full expression level. The set is cleared after emitting the
10419 void DiagnoseMisalignedMembers();
10421 /// \brief This function checks if the expression is in the sef of potentially
10422 /// misaligned members and it is converted to some pointer type T with lower
10423 /// or equal alignment requirements. If so it removes it. This is used when
10424 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10426 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10428 /// \brief This function calls Action when it determines that E designates a
10429 /// misaligned member due to the packed attribute. This is used to emit
10430 /// local diagnostics like in reference binding.
10431 void RefersToMemberWithReducedAlignment(
10433 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10437 /// \brief RAII object that enters a new expression evaluation context.
10438 class EnterExpressionEvaluationContext {
10440 bool Entered = true;
10444 EnterExpressionEvaluationContext(Sema &Actions,
10445 Sema::ExpressionEvaluationContext NewContext,
10446 Decl *LambdaContextDecl = nullptr,
10447 bool IsDecltype = false,
10448 bool ShouldEnter = true)
10449 : Actions(Actions), Entered(ShouldEnter) {
10451 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10454 EnterExpressionEvaluationContext(Sema &Actions,
10455 Sema::ExpressionEvaluationContext NewContext,
10456 Sema::ReuseLambdaContextDecl_t,
10457 bool IsDecltype = false)
10458 : Actions(Actions) {
10459 Actions.PushExpressionEvaluationContext(NewContext,
10460 Sema::ReuseLambdaContextDecl,
10464 enum InitListTag { InitList };
10465 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10466 bool ShouldEnter = true)
10467 : Actions(Actions), Entered(false) {
10468 // In C++11 onwards, narrowing checks are performed on the contents of
10469 // braced-init-lists, even when they occur within unevaluated operands.
10470 // Therefore we still need to instantiate constexpr functions used in such
10472 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10473 Actions.getLangOpts().CPlusPlus11) {
10474 Actions.PushExpressionEvaluationContext(
10475 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10480 ~EnterExpressionEvaluationContext() {
10482 Actions.PopExpressionEvaluationContext();
10486 DeductionFailureInfo
10487 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10488 sema::TemplateDeductionInfo &Info);
10490 /// \brief Contains a late templated function.
10491 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10492 struct LateParsedTemplate {
10494 /// \brief The template function declaration to be late parsed.
10498 } // end namespace clang
10501 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10503 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10504 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10505 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10507 static FunctionDeclAndLoc getEmptyKey() {
10508 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10511 static FunctionDeclAndLoc getTombstoneKey() {
10512 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10515 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10516 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10517 FDL.Loc.getRawEncoding());
10520 static bool isEqual(const FunctionDeclAndLoc &LHS,
10521 const FunctionDeclAndLoc &RHS) {
10522 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10525 } // namespace llvm