Bug Summary

File:tools/clang/include/clang/Sema/Sema.h
Warning:line 269, column 7
Excessive padding in 'class clang::Sema' (67 padding bytes, where 3 is optimal). Optimal fields order: ExternalSource, LangOpts, PP, Context, Consumer, Diags, SourceMgr, CodeCompleter, CurContext, OriginalLexicalContext, VAListTagName, CurInitSeg, VisContext, PragmaAttributeCurrentTargetDecl, FieldCollector, PureVirtualClassDiagSet, LateTemplateParser, LateTemplateParserCleanup, OpaqueParser, DelayedDiagnostics, TUScope, StdNamespace, StdBadAlloc, StdAlignValT, StdExperimentalNamespaceCache, StdInitializerList, CXXTypeInfoDecl, MSVCGuidDecl, NSAPIObj, NSNumberDecl, NSValueDecl, NSNumberPointer, NSValuePointer, NSStringDecl, NSStringPointer, StringWithUTF8StringMethod, ValueWithBytesObjCTypeMethod, NSArrayDecl, ArrayWithObjectsMethod, NSDictionaryDecl, DictionaryWithObjectsMethod, QIDNSCopying, RespondsToSelectorSel, CXXThisTypeOverride, CurrentInstantiationScope, ThreadSafetyDeclCache, VarDataSharingAttributesStack, TypeTagForDatatypeMagicValues, CurScope, Ident_super, Ident___float128, Ident__Nonnull, Ident__Nullable, Ident__Null_unspecified, Ident_NSError, CFError, IdResolver, SpecialMemberCache, OpenCLFeatures, ExtnameUndeclaredIdentifiers, FlagBitsCache, UnparsedDefaultArgInstantiations, UnparsedDefaultArgLocs, MethodPool, VisibleModules, ShadowingDecls, VTablesUsed, InstantiatingSpecializations, InstantiatedNonDependentTypes, LookupModulesCache, VisibleNamespaceCache, SuppressedDiagnostics, TypoCorrectionFailures, CurrOpenCLExtension, OpenCLTypeExtMap, OpenCLDeclExtMap, CUDADeferredDiags, LocsWithCUDACallDiags, CUDAKnownEmittedFns, CUDACallGraph, CurrentSEHFinally, WeakTopLevelDecl, NullabilityMap, MaybeODRUseExprs, FunctionScopes, DeleteExprs, DelayedExceptionSpecChecks, DelayedDefaultedMemberExceptionSpecs, LateParsedTemplateMap, WeakUndeclaredIdentifiers, UndefinedButUsed, ReferencedSelectors, CurrentParameterCopyTypes, DelayedTypos, KnownNamespaces, DelayedDllExportClasses, ParsingInitForAutoVars, TypoCorrectedFunctionDefinitions, ExtVectorDecls, TentativeDefinitions, UnusedFileScopedDecls, DelegatingCtorDecls, PendingInstantiations, PendingLocalImplicitInstantiations, VtorDispStack, PackStack, ExprCleanupObjects, AnalysisWarnings, UnusedLocalTypedefNameCandidates, DataSegStack, BSSSegStack, ConstSegStack, CodeSegStack, NSNumberLiteralMethods, SpecialMembersBeingDeclared, BumpAlloc, PragmaAttributeStack, CodeSynthesisContextLookupModules, MisalignedMembers, VTableUses, UnusedPrivateFields, ModuleScopes, CodeSynthesisContexts, ExprEvalContexts, FPFeatures, MSPointerToMemberRepresentationMethod, ImplicitMSInheritanceAttrLoc, CurInitSegLoc, OptimizeOffPragmaLocation, TUKind, NumSFINAEErrors, NonInstantiationEntries, LastEmittedCodeSynthesisContextDepth, ArgumentPackSubstitutionIndex, TyposCorrected, ForceCUDAHostDeviceDepth, isMultiplexExternalSource, CollectStats, MSStructPragmaOn, IsBuildingRecoveryCallExpr, GlobalNewDeleteDeclared, AllowAbstractFieldReference, LoadedExternalKnownNamespaces, AccessCheckingSFINAE, InNonInstantiationSFINAEContext, DisableTypoCorrection, IsInOpenMPDeclareTargetContext, Cleanup, consider reordering the fields or adding explicit padding members

Annotated Source Code

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
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"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63 class APSInt;
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class SmallBitVector;
67 class InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class AttributeList;
79 class BindingDecl;
80 class BlockDecl;
81 class CapturedDecl;
82 class CXXBasePath;
83 class CXXBasePaths;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
88 class CXXDeleteExpr;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
92 class CXXMethodDecl;
93 class CXXScopeSpec;
94 class CXXTemporary;
95 class CXXTryStmt;
96 class CallExpr;
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;
106 class Decl;
107 class DeclAccessPair;
108 class DeclContext;
109 class DeclRefExpr;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
114 class Designation;
115 class EnableIfAttr;
116 class EnumConstantDecl;
117 class Expr;
118 class ExtVectorType;
119 class FormatAttr;
120 class FriendDecl;
121 class FunctionDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126 class InitListExpr;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
131 class LabelStmt;
132 class LambdaExpr;
133 class LangOptions;
134 class LocalInstantiationScope;
135 class LookupResult;
136 class MacroInfo;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138 class ModuleLoader;
139 class MultiLevelTemplateArgumentList;
140 class NamedDecl;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
145 class ObjCImplDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
148 class ObjCIvarDecl;
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;
157 class OMPClause;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
160 class OverloadExpr;
161 class ParenListExpr;
162 class ParmVarDecl;
163 class Preprocessor;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
166 class QualType;
167 class StandardConversionSequence;
168 class Stmt;
169 class StringLiteral;
170 class SwitchStmt;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
174 class TemplateDecl;
175 class TemplateParameterList;
176 class TemplatePartialOrderingContext;
177 class TemplateTemplateParmDecl;
178 class Token;
179 class TypeAliasDecl;
180 class TypedefDecl;
181 class TypedefNameDecl;
182 class TypeLoc;
183 class TypoCorrectionConsumer;
184 class UnqualifiedId;
185 class UnresolvedLookupExpr;
186 class UnresolvedMemberExpr;
187 class UnresolvedSetImpl;
188 class UnresolvedSetIterator;
189 class UsingDecl;
190 class UsingShadowDecl;
191 class ValueDecl;
192 class VarDecl;
193 class VarTemplateSpecializationDecl;
194 class VisibilityAttr;
195 class VisibleDeclConsumer;
196 class IndirectFieldDecl;
197 struct DeductionFailureInfo;
198 class TemplateSpecCandidateSet;
199
200namespace sema {
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;
212}
213
214namespace threadSafety {
215 class BeforeSet;
216 void threadSafetyCleanup(BeforeSet* Cache);
217}
218
219// FIXME: No way to easily map from TemplateTypeParmTypes to
220// TemplateTypeParmDecls, so we have this horrible PointerUnion.
221typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222 SourceLocation> UnexpandedParameterPack;
223
224/// Describes whether we've seen any nullability information for the given
225/// file.
226struct 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;
230
231 /// Which kind of pointer declarator we saw.
232 uint8_t PointerKind;
233
234 /// Whether we saw any type nullability annotations in the given file.
235 bool SawTypeNullability = false;
236};
237
238/// A mapping from file IDs to a record of whether we've seen nullability
239/// information in that file.
240class FileNullabilityMap {
241 /// A mapping from file IDs to the nullability information for each file ID.
242 llvm::DenseMap<FileID, FileNullability> Map;
243
244 /// A single-element cache based on the file ID.
245 struct {
246 FileID File;
247 FileNullability Nullability;
248 } Cache;
249
250public:
251 FileNullability &operator[](FileID file) {
252 // Check the single-element cache.
253 if (file == Cache.File)
254 return Cache.Nullability;
255
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;
259 }
260
261 // Pull this entry into the cache.
262 Cache.File = file;
263 Cache.Nullability = Map[file];
264 return Cache.Nullability;
265 }
266};
267
268/// Sema - This implements semantic analysis and AST building for C.
269class Sema {
Excessive padding in 'class clang::Sema' (67 padding bytes, where 3 is optimal). Optimal fields order: ExternalSource, LangOpts, PP, Context, Consumer, Diags, SourceMgr, CodeCompleter, CurContext, OriginalLexicalContext, VAListTagName, CurInitSeg, VisContext, PragmaAttributeCurrentTargetDecl, FieldCollector, PureVirtualClassDiagSet, LateTemplateParser, LateTemplateParserCleanup, OpaqueParser, DelayedDiagnostics, TUScope, StdNamespace, StdBadAlloc, StdAlignValT, StdExperimentalNamespaceCache, StdInitializerList, CXXTypeInfoDecl, MSVCGuidDecl, NSAPIObj, NSNumberDecl, NSValueDecl, NSNumberPointer, NSValuePointer, NSStringDecl, NSStringPointer, StringWithUTF8StringMethod, ValueWithBytesObjCTypeMethod, NSArrayDecl, ArrayWithObjectsMethod, NSDictionaryDecl, DictionaryWithObjectsMethod, QIDNSCopying, RespondsToSelectorSel, CXXThisTypeOverride, CurrentInstantiationScope, ThreadSafetyDeclCache, VarDataSharingAttributesStack, TypeTagForDatatypeMagicValues, CurScope, Ident_super, Ident___float128, Ident__Nonnull, Ident__Nullable, Ident__Null_unspecified, Ident_NSError, CFError, IdResolver, SpecialMemberCache, OpenCLFeatures, ExtnameUndeclaredIdentifiers, FlagBitsCache, UnparsedDefaultArgInstantiations, UnparsedDefaultArgLocs, MethodPool, VisibleModules, ShadowingDecls, VTablesUsed, InstantiatingSpecializations, InstantiatedNonDependentTypes, LookupModulesCache, VisibleNamespaceCache, SuppressedDiagnostics, TypoCorrectionFailures, CurrOpenCLExtension, OpenCLTypeExtMap, OpenCLDeclExtMap, CUDADeferredDiags, LocsWithCUDACallDiags, CUDAKnownEmittedFns, CUDACallGraph, CurrentSEHFinally, WeakTopLevelDecl, NullabilityMap, MaybeODRUseExprs, FunctionScopes, DeleteExprs, DelayedExceptionSpecChecks, DelayedDefaultedMemberExceptionSpecs, LateParsedTemplateMap, WeakUndeclaredIdentifiers, UndefinedButUsed, ReferencedSelectors, CurrentParameterCopyTypes, DelayedTypos, KnownNamespaces, DelayedDllExportClasses, ParsingInitForAutoVars, TypoCorrectedFunctionDefinitions, ExtVectorDecls, TentativeDefinitions, UnusedFileScopedDecls, DelegatingCtorDecls, PendingInstantiations, PendingLocalImplicitInstantiations, VtorDispStack, PackStack, ExprCleanupObjects, AnalysisWarnings, UnusedLocalTypedefNameCandidates, DataSegStack, BSSSegStack, ConstSegStack, CodeSegStack, NSNumberLiteralMethods, SpecialMembersBeingDeclared, BumpAlloc, PragmaAttributeStack, CodeSynthesisContextLookupModules, MisalignedMembers, VTableUses, UnusedPrivateFields, ModuleScopes, CodeSynthesisContexts, ExprEvalContexts, FPFeatures, MSPointerToMemberRepresentationMethod, ImplicitMSInheritanceAttrLoc, CurInitSegLoc, OptimizeOffPragmaLocation, TUKind, NumSFINAEErrors, NonInstantiationEntries, LastEmittedCodeSynthesisContextDepth, ArgumentPackSubstitutionIndex, TyposCorrected, ForceCUDAHostDeviceDepth, isMultiplexExternalSource, CollectStats, MSStructPragmaOn, IsBuildingRecoveryCallExpr, GlobalNewDeleteDeclared, AllowAbstractFieldReference, LoadedExternalKnownNamespaces, AccessCheckingSFINAE, InNonInstantiationSFINAEContext, DisableTypoCorrection, IsInOpenMPDeclareTargetContext, Cleanup, consider reordering the fields or adding explicit padding members
270 Sema(const Sema &) = delete;
271 void operator=(const Sema &) = delete;
272
273 ///\brief Source of additional semantic information.
274 ExternalSemaSource *ExternalSource;
275
276 ///\brief Whether Sema has generated a multiplexer and has to delete it.
277 bool isMultiplexExternalSource;
278
279 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
280
281 bool isVisibleSlow(const NamedDecl *D);
282
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();
292 }
293 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
294
295public:
296 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297 typedef OpaquePtr<TemplateName> TemplateTy;
298 typedef OpaquePtr<QualType> TypeTy;
299
300 OpenCLOptions OpenCLFeatures;
301 FPOptions FPFeatures;
302
303 const LangOptions &LangOpts;
304 Preprocessor &PP;
305 ASTContext &Context;
306 ASTConsumer &Consumer;
307 DiagnosticsEngine &Diags;
308 SourceManager &SourceMgr;
309
310 /// \brief Flag indicating whether or not to collect detailed statistics.
311 bool CollectStats;
312
313 /// \brief Code-completion consumer.
314 CodeCompleteConsumer *CodeCompleter;
315
316 /// CurContext - This is the current declaration context of parsing.
317 DeclContext *CurContext;
318
319 /// \brief Generally null except when we temporarily switch decl contexts,
320 /// like in \see ActOnObjCTemporaryExitContainerContext.
321 DeclContext *OriginalLexicalContext;
322
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;
326
327 bool MSStructPragmaOn; // True when \#pragma ms_struct on
328
329 /// \brief Controls member pointer representation format under the MS ABI.
330 LangOptions::PragmaMSPointersToMembersKind
331 MSPointerToMemberRepresentationMethod;
332
333 /// Stack of active SEH __finally scopes. Can be empty.
334 SmallVector<Scope*, 2> CurrentSEHFinally;
335
336 /// \brief Source location for newly created implicit MSInheritanceAttrs
337 SourceLocation ImplicitMSInheritanceAttrLoc;
338
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)
347 };
348
349 template<typename ValueType>
350 struct PragmaStack {
351 struct Slot {
352 llvm::StringRef StackSlotLabel;
353 ValueType Value;
354 SourceLocation PragmaLocation;
355 Slot(llvm::StringRef StackSlotLabel,
356 ValueType Value,
357 SourceLocation PragmaLocation)
358 : StackSlotLabel(StackSlotLabel), Value(Value),
359 PragmaLocation(PragmaLocation) {}
360 };
361 void Act(SourceLocation PragmaLocation,
362 PragmaMsStackAction Action,
363 llvm::StringRef StackSlotLabel,
364 ValueType Value);
365
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:
368 //
369 // struct S {
370 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
371 // void Method {}
372 // #pragma <name>(pop, InternalPragmaSlot)
373 // };
374 //
375 // It works even with #pragma vtordisp, although MSVC doesn't support
376 // #pragma vtordisp(push [, id], n)
377 // syntax.
378 //
379 // Push / pop a named sentinel slot.
380 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
381 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 382, __PRETTY_FUNCTION__))
382 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 382, __PRETTY_FUNCTION__))
;
383 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
384 }
385
386 // Constructors.
387 explicit PragmaStack(const ValueType &Default)
388 : DefaultValue(Default), CurrentValue(Default) {}
389
390 SmallVector<Slot, 2> Stack;
391 ValueType DefaultValue; // Value used for PSK_Reset action.
392 ValueType CurrentValue;
393 SourceLocation CurrentPragmaLocation;
394 };
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).
397
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:
400 ///
401 /// 0: Suppress all vtordisps
402 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
403 /// structors
404 /// 2: Always insert vtordisps to support RTTI on partially constructed
405 /// objects
406 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
407 // #pragma pack.
408 // Sentinel to represent when the stack is set to mac68k alignment.
409 static const unsigned kMac68kAlignmentSentinel = ~0U;
410 PragmaStack<unsigned> PackStack;
411 // Segment #pragmas.
412 PragmaStack<StringLiteral *> DataSegStack;
413 PragmaStack<StringLiteral *> BSSSegStack;
414 PragmaStack<StringLiteral *> ConstSegStack;
415 PragmaStack<StringLiteral *> CodeSegStack;
416
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 {
420 public:
421 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
422 ~PragmaStackSentinelRAII();
423
424 private:
425 Sema &S;
426 StringRef SlotLabel;
427 bool ShouldAct;
428 };
429
430 /// A mapping that describes the nullability we've seen in each header file.
431 FileNullabilityMap NullabilityMap;
432
433 /// Last section used with #pragma init_seg.
434 StringLiteral *CurInitSeg;
435 SourceLocation CurInitSegLoc;
436
437 /// VisContext - Manages the stack for \#pragma GCC visibility.
438 void *VisContext; // Really a "PragmaVisStack*"
439
440 /// \brief This represents the stack of attributes that were pushed by
441 /// \#pragma clang attribute.
442 struct PragmaAttributeEntry {
443 SourceLocation Loc;
444 AttributeList *Attribute;
445 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
446 bool IsUsed;
447 };
448 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
449
450 /// \brief The declaration that is currently receiving an attribute from the
451 /// #pragma attribute stack.
452 const Decl *PragmaAttributeCurrentTargetDecl;
453
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;
458
459 /// \brief Flag indicating if Sema is building a recovery call expression.
460 ///
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;
464
465 /// Used to control the generation of ExprWithCleanups.
466 CleanupInfo Cleanup;
467
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;
472
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
478 /// full expression.
479 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
480
481 /// \brief Stack containing information about each of the nested
482 /// function, block, and method scopes that are currently active.
483 ///
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;
488
489 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
490 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
491 ExtVectorDeclsType;
492
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;
497
498 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
499 std::unique_ptr<CXXFieldCollector> FieldCollector;
500
501 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
502
503 /// \brief Set containing all declared private fields that are not used.
504 NamedDeclSetType UnusedPrivateFields;
505
506 /// \brief Set containing all typedefs that are likely unused.
507 llvm::SmallSetVector<const TypedefNameDecl *, 4>
508 UnusedLocalTypedefNameCandidates;
509
510 /// \brief Delete-expressions to be analyzed at the end of translation unit
511 ///
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;
518
519 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
520
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;
525
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;
529
530 /// \brief Look for a locally scoped extern "C" declaration by the given name.
531 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
532
533 typedef LazyVector<VarDecl *, ExternalSemaSource,
534 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
535 TentativeDefinitionsType;
536
537 /// \brief All the tentative definitions encountered in the TU.
538 TentativeDefinitionsType TentativeDefinitions;
539
540 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
542 UnusedFileScopedDeclsType;
543
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;
547
548 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
549 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
550 DelegatingCtorDeclsType;
551
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;
555
556 /// \brief All the overriding functions seen during a class definition
557 /// that had their exception spec checks delayed, plus the overridden
558 /// function.
559 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
560 DelayedExceptionSpecChecks;
561
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;
571
572 typedef llvm::MapVector<const FunctionDecl *,
573 std::unique_ptr<LateParsedTemplate>>
574 LateParsedTemplateMapT;
575 LateParsedTemplateMapT LateParsedTemplateMap;
576
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;
582 void *OpaqueParser;
583
584 void SetLateTemplateParser(LateTemplateParserCB *LTP,
585 LateTemplateParserCleanupCB *LTPCleanup,
586 void *P) {
587 LateTemplateParser = LTP;
588 LateTemplateParserCleanup = LTPCleanup;
589 OpaqueParser = P;
590 }
591
592 class DelayedDiagnostics;
593
594 class DelayedDiagnosticsState {
595 sema::DelayedDiagnosticPool *SavedPool;
596 friend class Sema::DelayedDiagnostics;
597 };
598 typedef DelayedDiagnosticsState ParsingDeclState;
599 typedef DelayedDiagnosticsState ProcessingContextState;
600
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;
607
608 public:
609 DelayedDiagnostics() : CurPool(nullptr) {}
610
611 /// Adds a delayed diagnostic.
612 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
613
614 /// Determines whether diagnostics should be delayed.
615 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
616
617 /// Returns the current delayed-diagnostics pool.
618 sema::DelayedDiagnosticPool *getCurrentPool() const {
619 return CurPool;
620 }
621
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;
627 CurPool = &pool;
628 return state;
629 }
630
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;
636 }
637
638 /// Enter a new scope where access and deprecation diagnostics are
639 /// not delayed.
640 DelayedDiagnosticsState pushUndelayed() {
641 DelayedDiagnosticsState state;
642 state.SavedPool = CurPool;
643 CurPool = nullptr;
644 return state;
645 }
646
647 /// Undo a previous pushUndelayed().
648 void popUndelayed(DelayedDiagnosticsState state) {
649 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 649, __PRETTY_FUNCTION__))
;
650 CurPool = state.SavedPool;
651 }
652 } DelayedDiagnostics;
653
654 /// A RAII object to temporarily push a declaration context.
655 class ContextRAII {
656 private:
657 Sema &S;
658 DeclContext *SavedContext;
659 ProcessingContextState SavedContextState;
660 QualType SavedCXXThisTypeOverride;
661
662 public:
663 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
664 : S(S), SavedContext(S.CurContext),
665 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
666 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
667 {
668 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 668, __PRETTY_FUNCTION__))
;
669 S.CurContext = ContextToPush;
670 if (NewThisContext)
671 S.CXXThisTypeOverride = QualType();
672 }
673
674 void pop() {
675 if (!SavedContext) return;
676 S.CurContext = SavedContext;
677 S.DelayedDiagnostics.popUndelayed(SavedContextState);
678 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
679 SavedContext = nullptr;
680 }
681
682 ~ContextRAII() {
683 pop();
684 }
685 };
686
687 /// \brief RAII object to handle the state changes required to synthesize
688 /// a function body.
689 class SynthesizedFunctionScope {
690 Sema &S;
691 Sema::ContextRAII SavedContext;
692
693 public:
694 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
695 : S(S), SavedContext(S, DC)
696 {
697 S.PushFunctionScope();
698 S.PushExpressionEvaluationContext(
699 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
700 }
701
702 ~SynthesizedFunctionScope() {
703 S.PopExpressionEvaluationContext();
704 S.PopFunctionScopeInfo();
705 }
706 };
707
708 /// WeakUndeclaredIdentifiers - Identifiers contained in
709 /// \#pragma weak before declared. rare. may alias another
710 /// identifier, declared or undeclared
711 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
712
713 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
714 /// \#pragma redefine_extname before declared. Used in Solaris system headers
715 /// to define functions that occur in multiple standards to call the version
716 /// in the currently selected standard.
717 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
718
719
720 /// \brief Load weak undeclared identifiers from the external source.
721 void LoadExternalWeakUndeclaredIdentifiers();
722
723 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
724 /// \#pragma weak during processing of other Decls.
725 /// I couldn't figure out a clean way to generate these in-line, so
726 /// we store them here and handle separately -- which is a hack.
727 /// It would be best to refactor this.
728 SmallVector<Decl*,2> WeakTopLevelDecl;
729
730 IdentifierResolver IdResolver;
731
732 /// Translation Unit Scope - useful to Objective-C actions that need
733 /// to lookup file scope declarations in the "ordinary" C decl namespace.
734 /// For example, user-defined classes, built-in "id" type, etc.
735 Scope *TUScope;
736
737 /// \brief The C++ "std" namespace, where the standard library resides.
738 LazyDeclPtr StdNamespace;
739
740 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
741 /// standard library.
742 LazyDeclPtr StdBadAlloc;
743
744 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
745 /// standard library.
746 LazyDeclPtr StdAlignValT;
747
748 /// \brief The C++ "std::experimental" namespace, where the experimental parts
749 /// of the standard library resides.
750 NamespaceDecl *StdExperimentalNamespaceCache;
751
752 /// \brief The C++ "std::initializer_list" template, which is defined in
753 /// \<initializer_list>.
754 ClassTemplateDecl *StdInitializerList;
755
756 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
757 RecordDecl *CXXTypeInfoDecl;
758
759 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
760 RecordDecl *MSVCGuidDecl;
761
762 /// \brief Caches identifiers/selectors for NSFoundation APIs.
763 std::unique_ptr<NSAPI> NSAPIObj;
764
765 /// \brief The declaration of the Objective-C NSNumber class.
766 ObjCInterfaceDecl *NSNumberDecl;
767
768 /// \brief The declaration of the Objective-C NSValue class.
769 ObjCInterfaceDecl *NSValueDecl;
770
771 /// \brief Pointer to NSNumber type (NSNumber *).
772 QualType NSNumberPointer;
773
774 /// \brief Pointer to NSValue type (NSValue *).
775 QualType NSValuePointer;
776
777 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
778 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
779
780 /// \brief The declaration of the Objective-C NSString class.
781 ObjCInterfaceDecl *NSStringDecl;
782
783 /// \brief Pointer to NSString type (NSString *).
784 QualType NSStringPointer;
785
786 /// \brief The declaration of the stringWithUTF8String: method.
787 ObjCMethodDecl *StringWithUTF8StringMethod;
788
789 /// \brief The declaration of the valueWithBytes:objCType: method.
790 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
791
792 /// \brief The declaration of the Objective-C NSArray class.
793 ObjCInterfaceDecl *NSArrayDecl;
794
795 /// \brief The declaration of the arrayWithObjects:count: method.
796 ObjCMethodDecl *ArrayWithObjectsMethod;
797
798 /// \brief The declaration of the Objective-C NSDictionary class.
799 ObjCInterfaceDecl *NSDictionaryDecl;
800
801 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
802 ObjCMethodDecl *DictionaryWithObjectsMethod;
803
804 /// \brief id<NSCopying> type.
805 QualType QIDNSCopying;
806
807 /// \brief will hold 'respondsToSelector:'
808 Selector RespondsToSelectorSel;
809
810 /// A flag to remember whether the implicit forms of operator new and delete
811 /// have been declared.
812 bool GlobalNewDeleteDeclared;
813
814 /// A flag to indicate that we're in a context that permits abstract
815 /// references to fields. This is really a
816 bool AllowAbstractFieldReference;
817
818 /// \brief Describes how the expressions currently being parsed are
819 /// evaluated at run-time, if at all.
820 enum class ExpressionEvaluationContext {
821 /// \brief The current expression and its subexpressions occur within an
822 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
823 /// \c sizeof, where the type of the expression may be significant but
824 /// no code will be generated to evaluate the value of the expression at
825 /// run time.
826 Unevaluated,
827
828 /// \brief The current expression occurs within a braced-init-list within
829 /// an unevaluated operand. This is mostly like a regular unevaluated
830 /// context, except that we still instantiate constexpr functions that are
831 /// referenced here so that we can perform narrowing checks correctly.
832 UnevaluatedList,
833
834 /// \brief The current expression occurs within a discarded statement.
835 /// This behaves largely similarly to an unevaluated operand in preventing
836 /// definitions from being required, but not in other ways.
837 DiscardedStatement,
838
839 /// \brief The current expression occurs within an unevaluated
840 /// operand that unconditionally permits abstract references to
841 /// fields, such as a SIZE operator in MS-style inline assembly.
842 UnevaluatedAbstract,
843
844 /// \brief The current context is "potentially evaluated" in C++11 terms,
845 /// but the expression is evaluated at compile-time (like the values of
846 /// cases in a switch statement).
847 ConstantEvaluated,
848
849 /// \brief The current expression is potentially evaluated at run time,
850 /// which means that code may be generated to evaluate the value of the
851 /// expression at run time.
852 PotentiallyEvaluated,
853
854 /// \brief The current expression is potentially evaluated, but any
855 /// declarations referenced inside that expression are only used if
856 /// in fact the current expression is used.
857 ///
858 /// This value is used when parsing default function arguments, for which
859 /// we would like to provide diagnostics (e.g., passing non-POD arguments
860 /// through varargs) but do not want to mark declarations as "referenced"
861 /// until the default argument is used.
862 PotentiallyEvaluatedIfUsed
863 };
864
865 /// \brief Data structure used to record current or nested
866 /// expression evaluation contexts.
867 struct ExpressionEvaluationContextRecord {
868 /// \brief The expression evaluation context.
869 ExpressionEvaluationContext Context;
870
871 /// \brief Whether the enclosing context needed a cleanup.
872 CleanupInfo ParentCleanup;
873
874 /// \brief Whether we are in a decltype expression.
875 bool IsDecltype;
876
877 /// \brief The number of active cleanup objects when we entered
878 /// this expression evaluation context.
879 unsigned NumCleanupObjects;
880
881 /// \brief The number of typos encountered during this expression evaluation
882 /// context (i.e. the number of TypoExprs created).
883 unsigned NumTypos;
884
885 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
886
887 /// \brief The lambdas that are present within this context, if it
888 /// is indeed an unevaluated context.
889 SmallVector<LambdaExpr *, 2> Lambdas;
890
891 /// \brief The declaration that provides context for lambda expressions
892 /// and block literals if the normal declaration context does not
893 /// suffice, e.g., in a default function argument.
894 Decl *ManglingContextDecl;
895
896 /// \brief The context information used to mangle lambda expressions
897 /// and block literals within this context.
898 ///
899 /// This mangling information is allocated lazily, since most contexts
900 /// do not have lambda expressions or block literals.
901 std::unique_ptr<MangleNumberingContext> MangleNumbering;
902
903 /// \brief If we are processing a decltype type, a set of call expressions
904 /// for which we have deferred checking the completeness of the return type.
905 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
906
907 /// \brief If we are processing a decltype type, a set of temporary binding
908 /// expressions for which we have deferred checking the destructor.
909 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
910
911 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
912 unsigned NumCleanupObjects,
913 CleanupInfo ParentCleanup,
914 Decl *ManglingContextDecl,
915 bool IsDecltype)
916 : Context(Context), ParentCleanup(ParentCleanup),
917 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
918 NumTypos(0),
919 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
920
921 /// \brief Retrieve the mangling numbering context, used to consistently
922 /// number constructs like lambdas for mangling.
923 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
924
925 bool isUnevaluated() const {
926 return Context == ExpressionEvaluationContext::Unevaluated ||
927 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
928 Context == ExpressionEvaluationContext::UnevaluatedList;
929 }
930 bool isConstantEvaluated() const {
931 return Context == ExpressionEvaluationContext::ConstantEvaluated;
932 }
933 };
934
935 /// A stack of expression evaluation contexts.
936 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
937
938 /// \brief Compute the mangling number context for a lambda expression or
939 /// block literal.
940 ///
941 /// \param DC - The DeclContext containing the lambda expression or
942 /// block literal.
943 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
944 /// associated with the context, if relevant.
945 MangleNumberingContext *getCurrentMangleNumberContext(
946 const DeclContext *DC,
947 Decl *&ManglingContextDecl);
948
949
950 /// SpecialMemberOverloadResult - The overloading result for a special member
951 /// function.
952 ///
953 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
954 /// integer are used to determine whether overload resolution succeeded.
955 class SpecialMemberOverloadResult {
956 public:
957 enum Kind {
958 NoMemberOrDeleted,
959 Ambiguous,
960 Success
961 };
962
963 private:
964 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
965
966 public:
967 SpecialMemberOverloadResult() : Pair() {}
968 SpecialMemberOverloadResult(CXXMethodDecl *MD)
969 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
970
971 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
972 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
973
974 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
975 void setKind(Kind K) { Pair.setInt(K); }
976 };
977
978 class SpecialMemberOverloadResultEntry
979 : public llvm::FastFoldingSetNode,
980 public SpecialMemberOverloadResult {
981 public:
982 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
983 : FastFoldingSetNode(ID)
984 {}
985 };
986
987 /// \brief A cache of special member function overload resolution results
988 /// for C++ records.
989 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
990
991 /// \brief A cache of the flags available in enumerations with the flag_bits
992 /// attribute.
993 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
994
995 /// \brief The kind of translation unit we are processing.
996 ///
997 /// When we're processing a complete translation unit, Sema will perform
998 /// end-of-translation-unit semantic tasks (such as creating
999 /// initializers for tentative definitions in C) once parsing has
1000 /// completed. Modules and precompiled headers perform different kinds of
1001 /// checks.
1002 TranslationUnitKind TUKind;
1003
1004 llvm::BumpPtrAllocator BumpAlloc;
1005
1006 /// \brief The number of SFINAE diagnostics that have been trapped.
1007 unsigned NumSFINAEErrors;
1008
1009 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1010 UnparsedDefaultArgInstantiationsMap;
1011
1012 /// \brief A mapping from parameters with unparsed default arguments to the
1013 /// set of instantiations of each parameter.
1014 ///
1015 /// This mapping is a temporary data structure used when parsing
1016 /// nested class templates or nested classes of class templates,
1017 /// where we might end up instantiating an inner class before the
1018 /// default arguments of its methods have been parsed.
1019 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1020
1021 // Contains the locations of the beginning of unparsed default
1022 // argument locations.
1023 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1024
1025 /// UndefinedInternals - all the used, undefined objects which require a
1026 /// definition in this translation unit.
1027 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1028
1029 /// Obtain a sorted list of functions that are undefined but ODR-used.
1030 void getUndefinedButUsed(
1031 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1032
1033 /// Retrieves list of suspicious delete-expressions that will be checked at
1034 /// the end of translation unit.
1035 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1036 getMismatchingDeleteExpressions() const;
1037
1038 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1039 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1040
1041 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1042 /// We need to maintain a list, since selectors can have differing signatures
1043 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1044 /// of selectors are "overloaded").
1045 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1046 /// methods inside categories with a particular selector.
1047 GlobalMethodPool MethodPool;
1048
1049 /// Method selectors used in a \@selector expression. Used for implementation
1050 /// of -Wselector.
1051 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1052
1053 /// Kinds of C++ special members.
1054 enum CXXSpecialMember {
1055 CXXDefaultConstructor,
1056 CXXCopyConstructor,
1057 CXXMoveConstructor,
1058 CXXCopyAssignment,
1059 CXXMoveAssignment,
1060 CXXDestructor,
1061 CXXInvalid
1062 };
1063
1064 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1065
1066 /// The C++ special members which we are currently in the process of
1067 /// declaring. If this process recursively triggers the declaration of the
1068 /// same special member, we should act as if it is not yet declared.
1069 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1070
1071 /// The function definitions which were renamed as part of typo-correction
1072 /// to match their respective declarations. We want to keep track of them
1073 /// to ensure that we don't emit a "redefinition" error if we encounter a
1074 /// correctly named definition after the renamed definition.
1075 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1076
1077 /// Stack of types that correspond to the parameter entities that are
1078 /// currently being copy-initialized. Can be empty.
1079 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1080
1081 void ReadMethodPool(Selector Sel);
1082 void updateOutOfDateSelector(Selector Sel);
1083
1084 /// Private Helper predicate to check for 'self'.
1085 bool isSelfExpr(Expr *RExpr);
1086 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1087
1088 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1089 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1090 /// should not be used elsewhere.
1091 void EmitCurrentDiagnostic(unsigned DiagID);
1092
1093 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1094 /// statements.
1095 class FPContractStateRAII {
1096 public:
1097 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1098 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1099
1100 private:
1101 Sema& S;
1102 FPOptions OldFPFeaturesState;
1103 };
1104
1105 void addImplicitTypedef(StringRef Name, QualType T);
1106
1107public:
1108 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1109 TranslationUnitKind TUKind = TU_Complete,
1110 CodeCompleteConsumer *CompletionConsumer = nullptr);
1111 ~Sema();
1112
1113 /// \brief Perform initialization that occurs after the parser has been
1114 /// initialized but before it parses anything.
1115 void Initialize();
1116
1117 const LangOptions &getLangOpts() const { return LangOpts; }
1118 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1119 FPOptions &getFPOptions() { return FPFeatures; }
1120
1121 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1122 SourceManager &getSourceManager() const { return SourceMgr; }
1123 Preprocessor &getPreprocessor() const { return PP; }
1124 ASTContext &getASTContext() const { return Context; }
1125 ASTConsumer &getASTConsumer() const { return Consumer; }
1126 ASTMutationListener *getASTMutationListener() const;
1127 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1128
1129 ///\brief Registers an external source. If an external source already exists,
1130 /// creates a multiplex external source and appends to it.
1131 ///
1132 ///\param[in] E - A non-null external sema source.
1133 ///
1134 void addExternalSource(ExternalSemaSource *E);
1135
1136 void PrintStats() const;
1137
1138 /// \brief Helper class that creates diagnostics with optional
1139 /// template instantiation stacks.
1140 ///
1141 /// This class provides a wrapper around the basic DiagnosticBuilder
1142 /// class that emits diagnostics. SemaDiagnosticBuilder is
1143 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1144 /// does) and, if the diagnostic comes from inside a template
1145 /// instantiation, printing the template instantiation stack as
1146 /// well.
1147 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1148 Sema &SemaRef;
1149 unsigned DiagID;
1150
1151 public:
1152 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1153 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1154
1155 // This is a cunning lie. DiagnosticBuilder actually performs move
1156 // construction in its copy constructor (but due to varied uses, it's not
1157 // possible to conveniently express this as actual move construction). So
1158 // the default copy ctor here is fine, because the base class disables the
1159 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1160 // in that case anwyay.
1161 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1162
1163 ~SemaDiagnosticBuilder() {
1164 // If we aren't active, there is nothing to do.
1165 if (!isActive()) return;
1166
1167 // Otherwise, we need to emit the diagnostic. First flush the underlying
1168 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1169 // won't emit the diagnostic in its own destructor.
1170 //
1171 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1172 // do its own needless checks to see if the diagnostic needs to be
1173 // emitted. However, because we take care to ensure that the builder
1174 // objects never escape, a sufficiently smart compiler will be able to
1175 // eliminate that code.
1176 FlushCounts();
1177 Clear();
1178
1179 // Dispatch to Sema to emit the diagnostic.
1180 SemaRef.EmitCurrentDiagnostic(DiagID);
1181 }
1182
1183 /// Teach operator<< to produce an object of the correct type.
1184 template<typename T>
1185 friend const SemaDiagnosticBuilder &operator<<(
1186 const SemaDiagnosticBuilder &Diag, const T &Value) {
1187 const DiagnosticBuilder &BaseDiag = Diag;
1188 BaseDiag << Value;
1189 return Diag;
1190 }
1191 };
1192
1193 /// \brief Emit a diagnostic.
1194 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1195 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1196 return SemaDiagnosticBuilder(DB, *this, DiagID);
1197 }
1198
1199 /// \brief Emit a partial diagnostic.
1200 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1201
1202 /// \brief Build a partial diagnostic.
1203 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1204
1205 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1206
1207 /// \brief Get a string to suggest for zero-initialization of a type.
1208 std::string
1209 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1210 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1211
1212 /// \brief Calls \c Lexer::getLocForEndOfToken()
1213 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1214
1215 /// \brief Retrieve the module loader associated with the preprocessor.
1216 ModuleLoader &getModuleLoader() const;
1217
1218 void emitAndClearUnusedLocalTypedefWarnings();
1219
1220 void ActOnEndOfTranslationUnit();
1221
1222 void CheckDelegatingCtorCycles();
1223
1224 Scope *getScopeForContext(DeclContext *Ctx);
1225
1226 void PushFunctionScope();
1227 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1228 sema::LambdaScopeInfo *PushLambdaScope();
1229
1230 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1231 /// is during Parsing. Currently it is used to pass on the depth
1232 /// when parsing generic lambda 'auto' parameters.
1233 void RecordParsingTemplateParameterDepth(unsigned Depth);
1234
1235 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1236 RecordDecl *RD,
1237 CapturedRegionKind K);
1238 void
1239 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1240 const Decl *D = nullptr,
1241 const BlockExpr *blkExpr = nullptr);
1242
1243 sema::FunctionScopeInfo *getCurFunction() const {
1244 return FunctionScopes.back();
1245 }
1246
1247 sema::FunctionScopeInfo *getEnclosingFunction() const {
1248 if (FunctionScopes.empty())
1249 return nullptr;
1250
1251 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1252 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1253 continue;
1254 return FunctionScopes[e];
1255 }
1256 return nullptr;
1257 }
1258
1259 template <typename ExprT>
1260 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1261 if (!isUnevaluatedContext())
1262 getCurFunction()->recordUseOfWeak(E, IsRead);
1263 }
1264
1265 void PushCompoundScope();
1266 void PopCompoundScope();
1267
1268 sema::CompoundScopeInfo &getCurCompoundScope() const;
1269
1270 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1271
1272 /// \brief Retrieve the current block, if any.
1273 sema::BlockScopeInfo *getCurBlock();
1274
1275 /// Retrieve the current lambda scope info, if any.
1276 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1277 /// lambda scope info ignoring all inner capturing scopes that are not
1278 /// lambda scopes.
1279 sema::LambdaScopeInfo *
1280 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1281
1282 /// \brief Retrieve the current generic lambda info, if any.
1283 sema::LambdaScopeInfo *getCurGenericLambda();
1284
1285 /// \brief Retrieve the current captured region, if any.
1286 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1287
1288 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1289 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1290
1291 void ActOnComment(SourceRange Comment);
1292
1293 //===--------------------------------------------------------------------===//
1294 // Type Analysis / Processing: SemaType.cpp.
1295 //
1296
1297 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1298 const DeclSpec *DS = nullptr);
1299 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1300 const DeclSpec *DS = nullptr);
1301 QualType BuildPointerType(QualType T,
1302 SourceLocation Loc, DeclarationName Entity);
1303 QualType BuildReferenceType(QualType T, bool LValueRef,
1304 SourceLocation Loc, DeclarationName Entity);
1305 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1306 Expr *ArraySize, unsigned Quals,
1307 SourceRange Brackets, DeclarationName Entity);
1308 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1309 SourceLocation AttrLoc);
1310
1311 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1312
1313 /// \brief Build a function type.
1314 ///
1315 /// This routine checks the function type according to C++ rules and
1316 /// under the assumption that the result type and parameter types have
1317 /// just been instantiated from a template. It therefore duplicates
1318 /// some of the behavior of GetTypeForDeclarator, but in a much
1319 /// simpler form that is only suitable for this narrow use case.
1320 ///
1321 /// \param T The return type of the function.
1322 ///
1323 /// \param ParamTypes The parameter types of the function. This array
1324 /// will be modified to account for adjustments to the types of the
1325 /// function parameters.
1326 ///
1327 /// \param Loc The location of the entity whose type involves this
1328 /// function type or, if there is no such entity, the location of the
1329 /// type that will have function type.
1330 ///
1331 /// \param Entity The name of the entity that involves the function
1332 /// type, if known.
1333 ///
1334 /// \param EPI Extra information about the function type. Usually this will
1335 /// be taken from an existing function with the same prototype.
1336 ///
1337 /// \returns A suitable function type, if there are no errors. The
1338 /// unqualified type will always be a FunctionProtoType.
1339 /// Otherwise, returns a NULL type.
1340 QualType BuildFunctionType(QualType T,
1341 MutableArrayRef<QualType> ParamTypes,
1342 SourceLocation Loc, DeclarationName Entity,
1343 const FunctionProtoType::ExtProtoInfo &EPI);
1344
1345 QualType BuildMemberPointerType(QualType T, QualType Class,
1346 SourceLocation Loc,
1347 DeclarationName Entity);
1348 QualType BuildBlockPointerType(QualType T,
1349 SourceLocation Loc, DeclarationName Entity);
1350 QualType BuildParenType(QualType T);
1351 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1352 QualType BuildReadPipeType(QualType T,
1353 SourceLocation Loc);
1354 QualType BuildWritePipeType(QualType T,
1355 SourceLocation Loc);
1356
1357 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1358 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1359 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1360 TypeSourceInfo *ReturnTypeInfo);
1361
1362 /// \brief Package the given type and TSI into a ParsedType.
1363 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1364 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1365 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1366 static QualType GetTypeFromParser(ParsedType Ty,
1367 TypeSourceInfo **TInfo = nullptr);
1368 CanThrowResult canThrow(const Expr *E);
1369 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1370 const FunctionProtoType *FPT);
1371 void UpdateExceptionSpec(FunctionDecl *FD,
1372 const FunctionProtoType::ExceptionSpecInfo &ESI);
1373 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1374 bool CheckDistantExceptionSpec(QualType T);
1375 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1376 bool CheckEquivalentExceptionSpec(
1377 const FunctionProtoType *Old, SourceLocation OldLoc,
1378 const FunctionProtoType *New, SourceLocation NewLoc);
1379 bool CheckEquivalentExceptionSpec(
1380 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1381 const FunctionProtoType *Old, SourceLocation OldLoc,
1382 const FunctionProtoType *New, SourceLocation NewLoc);
1383 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1384 const PartialDiagnostic &NestedDiagID,
1385 const PartialDiagnostic &NoteID,
1386 const FunctionProtoType *Superset,
1387 SourceLocation SuperLoc,
1388 const FunctionProtoType *Subset,
1389 SourceLocation SubLoc);
1390 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1391 const PartialDiagnostic &NoteID,
1392 const FunctionProtoType *Target,
1393 SourceLocation TargetLoc,
1394 const FunctionProtoType *Source,
1395 SourceLocation SourceLoc);
1396
1397 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1398
1399 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1400 /// in an Objective-C message declaration. Return the appropriate type.
1401 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1402
1403 /// \brief Abstract class used to diagnose incomplete types.
1404 struct TypeDiagnoser {
1405 TypeDiagnoser() {}
1406
1407 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1408 virtual ~TypeDiagnoser() {}
1409 };
1410
1411 static int getPrintable(int I) { return I; }
1412 static unsigned getPrintable(unsigned I) { return I; }
1413 static bool getPrintable(bool B) { return B; }
1414 static const char * getPrintable(const char *S) { return S; }
1415 static StringRef getPrintable(StringRef S) { return S; }
1416 static const std::string &getPrintable(const std::string &S) { return S; }
1417 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1418 return II;
1419 }
1420 static DeclarationName getPrintable(DeclarationName N) { return N; }
1421 static QualType getPrintable(QualType T) { return T; }
1422 static SourceRange getPrintable(SourceRange R) { return R; }
1423 static SourceRange getPrintable(SourceLocation L) { return L; }
1424 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1425 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1426
1427 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1428 unsigned DiagID;
1429 std::tuple<const Ts &...> Args;
1430
1431 template <std::size_t... Is>
1432 void emit(const SemaDiagnosticBuilder &DB,
1433 llvm::index_sequence<Is...>) const {
1434 // Apply all tuple elements to the builder in order.
1435 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1436 (void)Dummy;
1437 }
1438
1439 public:
1440 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1441 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1442 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 1442, __PRETTY_FUNCTION__))
;
1443 }
1444
1445 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1446 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1447 emit(DB, llvm::index_sequence_for<Ts...>());
1448 DB << T;
1449 }
1450 };
1451
1452private:
1453 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1454 TypeDiagnoser *Diagnoser);
1455
1456 struct ModuleScope {
1457 clang::Module *Module;
1458 VisibleModuleSet OuterVisibleModules;
1459 };
1460 /// The modules we're currently parsing.
1461 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1462
1463 /// Get the module whose scope we are currently within.
1464 Module *getCurrentModule() const {
1465 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1466 }
1467
1468 VisibleModuleSet VisibleModules;
1469
1470public:
1471 /// \brief Get the module owning an entity.
1472 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1473
1474 /// \brief Make a merged definition of an existing hidden definition \p ND
1475 /// visible at the specified location.
1476 void makeMergedDefinitionVisible(NamedDecl *ND);
1477
1478 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1479
1480 /// Determine whether a declaration is visible to name lookup.
1481 bool isVisible(const NamedDecl *D) {
1482 return !D->isHidden() || isVisibleSlow(D);
1483 }
1484
1485 /// Determine whether any declaration of an entity is visible.
1486 bool
1487 hasVisibleDeclaration(const NamedDecl *D,
1488 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1489 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1490 }
1491 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1492 llvm::SmallVectorImpl<Module *> *Modules);
1493
1494 bool hasVisibleMergedDefinition(NamedDecl *Def);
1495
1496 /// Determine if \p D has a visible definition. If not, suggest a declaration
1497 /// that should be made visible to expose the definition.
1498 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1499 bool OnlyNeedComplete = false);
1500 bool hasVisibleDefinition(const NamedDecl *D) {
1501 NamedDecl *Hidden;
1502 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1503 }
1504
1505 /// Determine if the template parameter \p D has a visible default argument.
1506 bool
1507 hasVisibleDefaultArgument(const NamedDecl *D,
1508 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1509
1510 /// Determine if there is a visible declaration of \p D that is an explicit
1511 /// specialization declaration for a specialization of a template. (For a
1512 /// member specialization, use hasVisibleMemberSpecialization.)
1513 bool hasVisibleExplicitSpecialization(
1514 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1515
1516 /// Determine if there is a visible declaration of \p D that is a member
1517 /// specialization declaration (as opposed to an instantiated declaration).
1518 bool hasVisibleMemberSpecialization(
1519 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1520
1521 /// Determine if \p A and \p B are equivalent internal linkage declarations
1522 /// from different modules, and thus an ambiguity error can be downgraded to
1523 /// an extension warning.
1524 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1525 const NamedDecl *B);
1526 void diagnoseEquivalentInternalLinkageDeclarations(
1527 SourceLocation Loc, const NamedDecl *D,
1528 ArrayRef<const NamedDecl *> Equiv);
1529
1530 bool isCompleteType(SourceLocation Loc, QualType T) {
1531 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1532 }
1533 bool RequireCompleteType(SourceLocation Loc, QualType T,
1534 TypeDiagnoser &Diagnoser);
1535 bool RequireCompleteType(SourceLocation Loc, QualType T,
1536 unsigned DiagID);
1537
1538 template <typename... Ts>
1539 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1540 const Ts &...Args) {
1541 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1542 return RequireCompleteType(Loc, T, Diagnoser);
1543 }
1544
1545 void completeExprArrayBound(Expr *E);
1546 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1547 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1548
1549 template <typename... Ts>
1550 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1551 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1552 return RequireCompleteExprType(E, Diagnoser);
1553 }
1554
1555 bool RequireLiteralType(SourceLocation Loc, QualType T,
1556 TypeDiagnoser &Diagnoser);
1557 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1558
1559 template <typename... Ts>
1560 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1561 const Ts &...Args) {
1562 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1563 return RequireLiteralType(Loc, T, Diagnoser);
1564 }
1565
1566 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1567 const CXXScopeSpec &SS, QualType T);
1568
1569 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1570 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1571 /// context, such as when building a type for decltype(auto).
1572 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1573 bool AsUnevaluated = true);
1574 QualType BuildUnaryTransformType(QualType BaseType,
1575 UnaryTransformType::UTTKind UKind,
1576 SourceLocation Loc);
1577
1578 //===--------------------------------------------------------------------===//
1579 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1580 //
1581
1582 struct SkipBodyInfo {
1583 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1584 bool ShouldSkip;
1585 NamedDecl *Previous;
1586 };
1587
1588 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1589
1590 void DiagnoseUseOfUnimplementedSelectors();
1591
1592 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1593
1594 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1595 Scope *S, CXXScopeSpec *SS = nullptr,
1596 bool isClassName = false, bool HasTrailingDot = false,
1597 ParsedType ObjectType = nullptr,
1598 bool IsCtorOrDtorName = false,
1599 bool WantNontrivialTypeSourceInfo = false,
1600 bool IsClassTemplateDeductionContext = true,
1601 IdentifierInfo **CorrectedII = nullptr);
1602 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1603 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1604 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1605 SourceLocation IILoc,
1606 Scope *S,
1607 CXXScopeSpec *SS,
1608 ParsedType &SuggestedType,
1609 bool IsTemplateName = false);
1610
1611 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1612 /// type name has failed in a dependent context. In these situations, we
1613 /// automatically form a DependentTypeName that will retry lookup in a related
1614 /// scope during instantiation.
1615 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1616 SourceLocation NameLoc,
1617 bool IsTemplateTypeArg);
1618
1619 /// \brief Describes the result of the name lookup and resolution performed
1620 /// by \c ClassifyName().
1621 enum NameClassificationKind {
1622 NC_Unknown,
1623 NC_Error,
1624 NC_Keyword,
1625 NC_Type,
1626 NC_Expression,
1627 NC_NestedNameSpecifier,
1628 NC_TypeTemplate,
1629 NC_VarTemplate,
1630 NC_FunctionTemplate
1631 };
1632
1633 class NameClassification {
1634 NameClassificationKind Kind;
1635 ExprResult Expr;
1636 TemplateName Template;
1637 ParsedType Type;
1638 const IdentifierInfo *Keyword;
1639
1640 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1641
1642 public:
1643 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1644
1645 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1646
1647 NameClassification(const IdentifierInfo *Keyword)
1648 : Kind(NC_Keyword), Keyword(Keyword) { }
1649
1650 static NameClassification Error() {
1651 return NameClassification(NC_Error);
1652 }
1653
1654 static NameClassification Unknown() {
1655 return NameClassification(NC_Unknown);
1656 }
1657
1658 static NameClassification NestedNameSpecifier() {
1659 return NameClassification(NC_NestedNameSpecifier);
1660 }
1661
1662 static NameClassification TypeTemplate(TemplateName Name) {
1663 NameClassification Result(NC_TypeTemplate);
1664 Result.Template = Name;
1665 return Result;
1666 }
1667
1668 static NameClassification VarTemplate(TemplateName Name) {
1669 NameClassification Result(NC_VarTemplate);
1670 Result.Template = Name;
1671 return Result;
1672 }
1673
1674 static NameClassification FunctionTemplate(TemplateName Name) {
1675 NameClassification Result(NC_FunctionTemplate);
1676 Result.Template = Name;
1677 return Result;
1678 }
1679
1680 NameClassificationKind getKind() const { return Kind; }
1681
1682 ParsedType getType() const {
1683 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 1683, __PRETTY_FUNCTION__))
;
1684 return Type;
1685 }
1686
1687 ExprResult getExpression() const {
1688 assert(Kind == NC_Expression)((Kind == NC_Expression) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Expression", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 1688, __PRETTY_FUNCTION__))
;
1689 return Expr;
1690 }
1691
1692 TemplateName getTemplateName() const {
1693 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate) ? static_cast<void> (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 1694, __PRETTY_FUNCTION__))
1694 Kind == NC_VarTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate) ? static_cast<void> (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 1694, __PRETTY_FUNCTION__))
;
1695 return Template;
1696 }
1697
1698 TemplateNameKind getTemplateNameKind() const {
1699 switch (Kind) {
1700 case NC_TypeTemplate:
1701 return TNK_Type_template;
1702 case NC_FunctionTemplate:
1703 return TNK_Function_template;
1704 case NC_VarTemplate:
1705 return TNK_Var_template;
1706 default:
1707 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 1707)
;
1708 }
1709 }
1710 };
1711
1712 /// \brief Perform name lookup on the given name, classifying it based on
1713 /// the results of name lookup and the following token.
1714 ///
1715 /// This routine is used by the parser to resolve identifiers and help direct
1716 /// parsing. When the identifier cannot be found, this routine will attempt
1717 /// to correct the typo and classify based on the resulting name.
1718 ///
1719 /// \param S The scope in which we're performing name lookup.
1720 ///
1721 /// \param SS The nested-name-specifier that precedes the name.
1722 ///
1723 /// \param Name The identifier. If typo correction finds an alternative name,
1724 /// this pointer parameter will be updated accordingly.
1725 ///
1726 /// \param NameLoc The location of the identifier.
1727 ///
1728 /// \param NextToken The token following the identifier. Used to help
1729 /// disambiguate the name.
1730 ///
1731 /// \param IsAddressOfOperand True if this name is the operand of a unary
1732 /// address of ('&') expression, assuming it is classified as an
1733 /// expression.
1734 ///
1735 /// \param CCC The correction callback, if typo correction is desired.
1736 NameClassification
1737 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1738 SourceLocation NameLoc, const Token &NextToken,
1739 bool IsAddressOfOperand,
1740 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1741
1742 /// Describes the detailed kind of a template name. Used in diagnostics.
1743 enum class TemplateNameKindForDiagnostics {
1744 ClassTemplate,
1745 FunctionTemplate,
1746 VarTemplate,
1747 AliasTemplate,
1748 TemplateTemplateParam,
1749 DependentTemplate
1750 };
1751 TemplateNameKindForDiagnostics
1752 getTemplateNameKindForDiagnostics(TemplateName Name);
1753
1754 /// Determine whether it's plausible that E was intended to be a
1755 /// template-name.
1756 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1757 if (!getLangOpts().CPlusPlus || E.isInvalid())
1758 return false;
1759 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1760 return !DRE->hasExplicitTemplateArgs();
1761 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1762 return !ME->hasExplicitTemplateArgs();
1763 // Any additional cases recognized here should also be handled by
1764 // diagnoseExprIntendedAsTemplateName.
1765 return false;
1766 }
1767 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1768 SourceLocation Less,
1769 SourceLocation Greater);
1770
1771 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1772
1773 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1774 MultiTemplateParamsArg TemplateParameterLists);
1775 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1776 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1777 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1778 DeclarationName Name,
1779 SourceLocation Loc);
1780 void
1781 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1782 SourceLocation FallbackLoc,
1783 SourceLocation ConstQualLoc = SourceLocation(),
1784 SourceLocation VolatileQualLoc = SourceLocation(),
1785 SourceLocation RestrictQualLoc = SourceLocation(),
1786 SourceLocation AtomicQualLoc = SourceLocation(),
1787 SourceLocation UnalignedQualLoc = SourceLocation());
1788
1789 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1790 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1791 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1792 const LookupResult &R);
1793 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1794 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1795 const LookupResult &R);
1796 void CheckShadow(Scope *S, VarDecl *D);
1797
1798 /// Warn if 'E', which is an expression that is about to be modified, refers
1799 /// to a shadowing declaration.
1800 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1801
1802 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1803
1804private:
1805 /// Map of current shadowing declarations to shadowed declarations. Warn if
1806 /// it looks like the user is trying to modify the shadowing declaration.
1807 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1808
1809public:
1810 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1811 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1812 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1813 TypedefNameDecl *NewTD);
1814 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1815 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1816 TypeSourceInfo *TInfo,
1817 LookupResult &Previous);
1818 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1819 LookupResult &Previous, bool &Redeclaration);
1820 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1821 TypeSourceInfo *TInfo,
1822 LookupResult &Previous,
1823 MultiTemplateParamsArg TemplateParamLists,
1824 bool &AddToScope,
1825 ArrayRef<BindingDecl *> Bindings = None);
1826 NamedDecl *
1827 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1828 MultiTemplateParamsArg TemplateParamLists);
1829 // Returns true if the variable declaration is a redeclaration
1830 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1831 void CheckVariableDeclarationType(VarDecl *NewVD);
1832 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1833 Expr *Init);
1834 void CheckCompleteVariableDeclaration(VarDecl *VD);
1835 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1836 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1837
1838 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1839 TypeSourceInfo *TInfo,
1840 LookupResult &Previous,
1841 MultiTemplateParamsArg TemplateParamLists,
1842 bool &AddToScope);
1843 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1844
1845 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1846 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1847
1848 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1849 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1850 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1851 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1852 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1853 // Returns true if the function declaration is a redeclaration
1854 bool CheckFunctionDeclaration(Scope *S,
1855 FunctionDecl *NewFD, LookupResult &Previous,
1856 bool IsMemberSpecialization);
1857 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1858 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1859 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1860 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1861 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1862 SourceLocation Loc,
1863 QualType T);
1864 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1865 SourceLocation NameLoc, IdentifierInfo *Name,
1866 QualType T, TypeSourceInfo *TSInfo,
1867 StorageClass SC);
1868 void ActOnParamDefaultArgument(Decl *param,
1869 SourceLocation EqualLoc,
1870 Expr *defarg);
1871 void ActOnParamUnparsedDefaultArgument(Decl *param,
1872 SourceLocation EqualLoc,
1873 SourceLocation ArgLoc);
1874 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1875 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1876 SourceLocation EqualLoc);
1877
1878 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1879 void ActOnUninitializedDecl(Decl *dcl);
1880 void ActOnInitializerError(Decl *Dcl);
1881
1882 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1883 void ActOnCXXForRangeDecl(Decl *D);
1884 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1885 IdentifierInfo *Ident,
1886 ParsedAttributes &Attrs,
1887 SourceLocation AttrEnd);
1888 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1889 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1890 void FinalizeDeclaration(Decl *D);
1891 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1892 ArrayRef<Decl *> Group);
1893 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1894
1895 /// Should be called on all declarations that might have attached
1896 /// documentation comments.
1897 void ActOnDocumentableDecl(Decl *D);
1898 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1899
1900 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1901 SourceLocation LocAfterDecls);
1902 void CheckForFunctionRedefinition(
1903 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1904 SkipBodyInfo *SkipBody = nullptr);
1905 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1906 MultiTemplateParamsArg TemplateParamLists,
1907 SkipBodyInfo *SkipBody = nullptr);
1908 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1909 SkipBodyInfo *SkipBody = nullptr);
1910 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1911 bool isObjCMethodDecl(Decl *D) {
1912 return D && isa<ObjCMethodDecl>(D);
1913 }
1914
1915 /// \brief Determine whether we can delay parsing the body of a function or
1916 /// function template until it is used, assuming we don't care about emitting
1917 /// code for that function.
1918 ///
1919 /// This will be \c false if we may need the body of the function in the
1920 /// middle of parsing an expression (where it's impractical to switch to
1921 /// parsing a different function), for instance, if it's constexpr in C++11
1922 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1923 bool canDelayFunctionBody(const Declarator &D);
1924
1925 /// \brief Determine whether we can skip parsing the body of a function
1926 /// definition, assuming we don't care about analyzing its body or emitting
1927 /// code for that function.
1928 ///
1929 /// This will be \c false only if we may need the body of the function in
1930 /// order to parse the rest of the program (for instance, if it is
1931 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1932 bool canSkipFunctionBody(Decl *D);
1933
1934 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1935 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1936 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1937 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1938 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1939
1940 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1941 /// attribute for which parsing is delayed.
1942 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1943
1944 /// \brief Diagnose any unused parameters in the given sequence of
1945 /// ParmVarDecl pointers.
1946 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1947
1948 /// \brief Diagnose whether the size of parameters or return value of a
1949 /// function or obj-c method definition is pass-by-value and larger than a
1950 /// specified threshold.
1951 void
1952 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1953 QualType ReturnTy, NamedDecl *D);
1954
1955 void DiagnoseInvalidJumps(Stmt *Body);
1956 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1957 SourceLocation AsmLoc,
1958 SourceLocation RParenLoc);
1959
1960 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1961 Decl *ActOnEmptyDeclaration(Scope *S,
1962 AttributeList *AttrList,
1963 SourceLocation SemiLoc);
1964
1965 enum class ModuleDeclKind {
1966 Module, ///< 'module X;'
1967 Partition, ///< 'module partition X;'
1968 Implementation, ///< 'module implementation X;'
1969 };
1970
1971 /// The parser has processed a module-declaration that begins the definition
1972 /// of a module interface or implementation.
1973 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
1974 SourceLocation ModuleLoc, ModuleDeclKind MDK,
1975 ModuleIdPath Path);
1976
1977 /// \brief The parser has processed a module import declaration.
1978 ///
1979 /// \param AtLoc The location of the '@' symbol, if any.
1980 ///
1981 /// \param ImportLoc The location of the 'import' keyword.
1982 ///
1983 /// \param Path The module access path.
1984 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1985 ModuleIdPath Path);
1986
1987 /// \brief The parser has processed a module import translated from a
1988 /// #include or similar preprocessing directive.
1989 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1990 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1991
1992 /// \brief The parsed has entered a submodule.
1993 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1994 /// \brief The parser has left a submodule.
1995 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1996
1997 /// \brief Create an implicit import of the given module at the given
1998 /// source location, for error recovery, if possible.
1999 ///
2000 /// This routine is typically used when an entity found by name lookup
2001 /// is actually hidden within a module that we know about but the user
2002 /// has forgotten to import.
2003 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2004 Module *Mod);
2005
2006 /// Kinds of missing import. Note, the values of these enumerators correspond
2007 /// to %select values in diagnostics.
2008 enum class MissingImportKind {
2009 Declaration,
2010 Definition,
2011 DefaultArgument,
2012 ExplicitSpecialization,
2013 PartialSpecialization
2014 };
2015
2016 /// \brief Diagnose that the specified declaration needs to be visible but
2017 /// isn't, and suggest a module import that would resolve the problem.
2018 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2019 MissingImportKind MIK, bool Recover = true);
2020 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2021 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2022 MissingImportKind MIK, bool Recover);
2023
2024 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2025 SourceLocation LBraceLoc);
2026 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2027 SourceLocation RBraceLoc);
2028
2029 /// \brief We've found a use of a templated declaration that would trigger an
2030 /// implicit instantiation. Check that any relevant explicit specializations
2031 /// and partial specializations are visible, and diagnose if not.
2032 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2033
2034 /// \brief We've found a use of a template specialization that would select a
2035 /// partial specialization. Check that the partial specialization is visible,
2036 /// and diagnose if not.
2037 void checkPartialSpecializationVisibility(SourceLocation Loc,
2038 NamedDecl *Spec);
2039
2040 /// \brief Retrieve a suitable printing policy.
2041 PrintingPolicy getPrintingPolicy() const {
2042 return getPrintingPolicy(Context, PP);
2043 }
2044
2045 /// \brief Retrieve a suitable printing policy.
2046 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2047 const Preprocessor &PP);
2048
2049 /// Scope actions.
2050 void ActOnPopScope(SourceLocation Loc, Scope *S);
2051 void ActOnTranslationUnitScope(Scope *S);
2052
2053 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2054 RecordDecl *&AnonRecord);
2055 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2056 MultiTemplateParamsArg TemplateParams,
2057 bool IsExplicitInstantiation,
2058 RecordDecl *&AnonRecord);
2059
2060 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2061 AccessSpecifier AS,
2062 RecordDecl *Record,
2063 const PrintingPolicy &Policy);
2064
2065 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2066 RecordDecl *Record);
2067
2068 /// Common ways to introduce type names without a tag for use in diagnostics.
2069 /// Keep in sync with err_tag_reference_non_tag.
2070 enum NonTagKind {
2071 NTK_NonStruct,
2072 NTK_NonClass,
2073 NTK_NonUnion,
2074 NTK_NonEnum,
2075 NTK_Typedef,
2076 NTK_TypeAlias,
2077 NTK_Template,
2078 NTK_TypeAliasTemplate,
2079 NTK_TemplateTemplateArgument,
2080 };
2081
2082 /// Given a non-tag type declaration, returns an enum useful for indicating
2083 /// what kind of non-tag type this is.
2084 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2085
2086 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2087 TagTypeKind NewTag, bool isDefinition,
2088 SourceLocation NewTagLoc,
2089 const IdentifierInfo *Name);
2090
2091 enum TagUseKind {
2092 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2093 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2094 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2095 TUK_Friend // Friend declaration: 'friend struct foo;'
2096 };
2097
2098 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2099 SourceLocation KWLoc, CXXScopeSpec &SS,
2100 IdentifierInfo *Name, SourceLocation NameLoc,
2101 AttributeList *Attr, AccessSpecifier AS,
2102 SourceLocation ModulePrivateLoc,
2103 MultiTemplateParamsArg TemplateParameterLists,
2104 bool &OwnedDecl, bool &IsDependent,
2105 SourceLocation ScopedEnumKWLoc,
2106 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2107 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2108
2109 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2110 unsigned TagSpec, SourceLocation TagLoc,
2111 CXXScopeSpec &SS,
2112 IdentifierInfo *Name, SourceLocation NameLoc,
2113 AttributeList *Attr,
2114 MultiTemplateParamsArg TempParamLists);
2115
2116 TypeResult ActOnDependentTag(Scope *S,
2117 unsigned TagSpec,
2118 TagUseKind TUK,
2119 const CXXScopeSpec &SS,
2120 IdentifierInfo *Name,
2121 SourceLocation TagLoc,
2122 SourceLocation NameLoc);
2123
2124 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2125 IdentifierInfo *ClassName,
2126 SmallVectorImpl<Decl *> &Decls);
2127 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2128 Declarator &D, Expr *BitfieldWidth);
2129
2130 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2131 Declarator &D, Expr *BitfieldWidth,
2132 InClassInitStyle InitStyle,
2133 AccessSpecifier AS);
2134 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2135 SourceLocation DeclStart,
2136 Declarator &D, Expr *BitfieldWidth,
2137 InClassInitStyle InitStyle,
2138 AccessSpecifier AS,
2139 AttributeList *MSPropertyAttr);
2140
2141 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2142 TypeSourceInfo *TInfo,
2143 RecordDecl *Record, SourceLocation Loc,
2144 bool Mutable, Expr *BitfieldWidth,
2145 InClassInitStyle InitStyle,
2146 SourceLocation TSSL,
2147 AccessSpecifier AS, NamedDecl *PrevDecl,
2148 Declarator *D = nullptr);
2149
2150 bool CheckNontrivialField(FieldDecl *FD);
2151 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2152 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2153 bool Diagnose = false);
2154 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2155 void ActOnLastBitfield(SourceLocation DeclStart,
2156 SmallVectorImpl<Decl *> &AllIvarDecls);
2157 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2158 Declarator &D, Expr *BitfieldWidth,
2159 tok::ObjCKeywordKind visibility);
2160
2161 // This is used for both record definitions and ObjC interface declarations.
2162 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2163 ArrayRef<Decl *> Fields,
2164 SourceLocation LBrac, SourceLocation RBrac,
2165 AttributeList *AttrList);
2166
2167 /// ActOnTagStartDefinition - Invoked when we have entered the
2168 /// scope of a tag's definition (e.g., for an enumeration, class,
2169 /// struct, or union).
2170 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2171
2172 typedef void *SkippedDefinitionContext;
2173
2174 /// \brief Invoked when we enter a tag definition that we're skipping.
2175 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2176
2177 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2178
2179 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2180 /// C++ record definition's base-specifiers clause and are starting its
2181 /// member declarations.
2182 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2183 SourceLocation FinalLoc,
2184 bool IsFinalSpelledSealed,
2185 SourceLocation LBraceLoc);
2186
2187 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2188 /// the definition of a tag (enumeration, class, struct, or union).
2189 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2190 SourceRange BraceRange);
2191
2192 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2193
2194 void ActOnObjCContainerFinishDefinition();
2195
2196 /// \brief Invoked when we must temporarily exit the objective-c container
2197 /// scope for parsing/looking-up C constructs.
2198 ///
2199 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2200 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2201 void ActOnObjCReenterContainerContext(DeclContext *DC);
2202
2203 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2204 /// error parsing the definition of a tag.
2205 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2206
2207 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2208 EnumConstantDecl *LastEnumConst,
2209 SourceLocation IdLoc,
2210 IdentifierInfo *Id,
2211 Expr *val);
2212 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2213 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2214 QualType EnumUnderlyingTy,
2215 bool EnumUnderlyingIsImplicit,
2216 const EnumDecl *Prev);
2217
2218 /// Determine whether the body of an anonymous enumeration should be skipped.
2219 /// \param II The name of the first enumerator.
2220 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2221 SourceLocation IILoc);
2222
2223 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2224 SourceLocation IdLoc, IdentifierInfo *Id,
2225 AttributeList *Attrs,
2226 SourceLocation EqualLoc, Expr *Val);
2227 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2228 Decl *EnumDecl,
2229 ArrayRef<Decl *> Elements,
2230 Scope *S, AttributeList *Attr);
2231
2232 DeclContext *getContainingDC(DeclContext *DC);
2233
2234 /// Set the current declaration context until it gets popped.
2235 void PushDeclContext(Scope *S, DeclContext *DC);
2236 void PopDeclContext();
2237
2238 /// EnterDeclaratorContext - Used when we must lookup names in the context
2239 /// of a declarator's nested name specifier.
2240 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2241 void ExitDeclaratorContext(Scope *S);
2242
2243 /// Push the parameters of D, which must be a function, into scope.
2244 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2245 void ActOnExitFunctionContext();
2246
2247 DeclContext *getFunctionLevelDeclContext();
2248
2249 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2250 /// to the function decl for the function being parsed. If we're currently
2251 /// in a 'block', this returns the containing context.
2252 FunctionDecl *getCurFunctionDecl();
2253
2254 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2255 /// the method decl for the method being parsed. If we're currently
2256 /// in a 'block', this returns the containing context.
2257 ObjCMethodDecl *getCurMethodDecl();
2258
2259 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2260 /// or C function we're in, otherwise return null. If we're currently
2261 /// in a 'block', this returns the containing context.
2262 NamedDecl *getCurFunctionOrMethodDecl();
2263
2264 /// Add this decl to the scope shadowed decl chains.
2265 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2266
2267 /// \brief Make the given externally-produced declaration visible at the
2268 /// top level scope.
2269 ///
2270 /// \param D The externally-produced declaration to push.
2271 ///
2272 /// \param Name The name of the externally-produced declaration.
2273 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2274
2275 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2276 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2277 /// true if 'D' belongs to the given declaration context.
2278 ///
2279 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2280 /// enclosing namespace set of the context, rather than contained
2281 /// directly within it.
2282 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2283 bool AllowInlineNamespace = false);
2284
2285 /// Finds the scope corresponding to the given decl context, if it
2286 /// happens to be an enclosing scope. Otherwise return NULL.
2287 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2288
2289 /// Subroutines of ActOnDeclarator().
2290 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2291 TypeSourceInfo *TInfo);
2292 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2293
2294 /// \brief Describes the kind of merge to perform for availability
2295 /// attributes (including "deprecated", "unavailable", and "availability").
2296 enum AvailabilityMergeKind {
2297 /// \brief Don't merge availability attributes at all.
2298 AMK_None,
2299 /// \brief Merge availability attributes for a redeclaration, which requires
2300 /// an exact match.
2301 AMK_Redeclaration,
2302 /// \brief Merge availability attributes for an override, which requires
2303 /// an exact match or a weakening of constraints.
2304 AMK_Override,
2305 /// \brief Merge availability attributes for an implementation of
2306 /// a protocol requirement.
2307 AMK_ProtocolImplementation,
2308 };
2309
2310 /// Attribute merging methods. Return true if a new attribute was added.
2311 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2312 IdentifierInfo *Platform,
2313 bool Implicit,
2314 VersionTuple Introduced,
2315 VersionTuple Deprecated,
2316 VersionTuple Obsoleted,
2317 bool IsUnavailable,
2318 StringRef Message,
2319 bool IsStrict, StringRef Replacement,
2320 AvailabilityMergeKind AMK,
2321 unsigned AttrSpellingListIndex);
2322 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2323 TypeVisibilityAttr::VisibilityType Vis,
2324 unsigned AttrSpellingListIndex);
2325 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2326 VisibilityAttr::VisibilityType Vis,
2327 unsigned AttrSpellingListIndex);
2328 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2329 unsigned AttrSpellingListIndex, StringRef Uuid);
2330 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2331 unsigned AttrSpellingListIndex);
2332 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2333 unsigned AttrSpellingListIndex);
2334 MSInheritanceAttr *
2335 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2336 unsigned AttrSpellingListIndex,
2337 MSInheritanceAttr::Spelling SemanticSpelling);
2338 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2339 IdentifierInfo *Format, int FormatIdx,
2340 int FirstArg, unsigned AttrSpellingListIndex);
2341 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2342 unsigned AttrSpellingListIndex);
2343 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2344 IdentifierInfo *Ident,
2345 unsigned AttrSpellingListIndex);
2346 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2347 unsigned AttrSpellingListIndex);
2348 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2349 unsigned AttrSpellingListIndex);
2350 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2351 IdentifierInfo *Ident,
2352 unsigned AttrSpellingListIndex);
2353 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2354 unsigned AttrSpellingListIndex);
2355
2356 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2357 AvailabilityMergeKind AMK = AMK_Redeclaration);
2358 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2359 LookupResult &OldDecls);
2360 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2361 bool MergeTypeWithOld);
2362 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2363 Scope *S, bool MergeTypeWithOld);
2364 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2365 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2366 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2367 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2368 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2369 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2370 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2371
2372 // AssignmentAction - This is used by all the assignment diagnostic functions
2373 // to represent what is actually causing the operation
2374 enum AssignmentAction {
2375 AA_Assigning,
2376 AA_Passing,
2377 AA_Returning,
2378 AA_Converting,
2379 AA_Initializing,
2380 AA_Sending,
2381 AA_Casting,
2382 AA_Passing_CFAudited
2383 };
2384
2385 /// C++ Overloading.
2386 enum OverloadKind {
2387 /// This is a legitimate overload: the existing declarations are
2388 /// functions or function templates with different signatures.
2389 Ovl_Overload,
2390
2391 /// This is not an overload because the signature exactly matches
2392 /// an existing declaration.
2393 Ovl_Match,
2394
2395 /// This is not an overload because the lookup results contain a
2396 /// non-function.
2397 Ovl_NonFunction
2398 };
2399 OverloadKind CheckOverload(Scope *S,
2400 FunctionDecl *New,
2401 const LookupResult &OldDecls,
2402 NamedDecl *&OldDecl,
2403 bool IsForUsingDecl);
2404 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2405 bool ConsiderCudaAttrs = true);
2406
2407 /// \brief Checks availability of the function depending on the current
2408 /// function context.Inside an unavailable function,unavailability is ignored.
2409 ///
2410 /// \returns true if \p FD is unavailable and current context is inside
2411 /// an available function, false otherwise.
2412 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2413
2414 ImplicitConversionSequence
2415 TryImplicitConversion(Expr *From, QualType ToType,
2416 bool SuppressUserConversions,
2417 bool AllowExplicit,
2418 bool InOverloadResolution,
2419 bool CStyle,
2420 bool AllowObjCWritebackConversion);
2421
2422 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2423 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2424 bool IsComplexPromotion(QualType FromType, QualType ToType);
2425 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2426 bool InOverloadResolution,
2427 QualType& ConvertedType, bool &IncompatibleObjC);
2428 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2429 QualType& ConvertedType, bool &IncompatibleObjC);
2430 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2431 QualType &ConvertedType);
2432 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2433 QualType& ConvertedType);
2434 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2435 const FunctionProtoType *NewType,
2436 unsigned *ArgPos = nullptr);
2437 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2438 QualType FromType, QualType ToType);
2439
2440 void maybeExtendBlockObject(ExprResult &E);
2441 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2442 bool CheckPointerConversion(Expr *From, QualType ToType,
2443 CastKind &Kind,
2444 CXXCastPath& BasePath,
2445 bool IgnoreBaseAccess,
2446 bool Diagnose = true);
2447 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2448 bool InOverloadResolution,
2449 QualType &ConvertedType);
2450 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2451 CastKind &Kind,
2452 CXXCastPath &BasePath,
2453 bool IgnoreBaseAccess);
2454 bool IsQualificationConversion(QualType FromType, QualType ToType,
2455 bool CStyle, bool &ObjCLifetimeConversion);
2456 bool IsFunctionConversion(QualType FromType, QualType ToType,
2457 QualType &ResultTy);
2458 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2459 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2460
2461 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2462 const VarDecl *NRVOCandidate,
2463 QualType ResultType,
2464 Expr *Value,
2465 bool AllowNRVO = true);
2466
2467 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2468 ExprResult Init);
2469 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2470 SourceLocation EqualLoc,
2471 ExprResult Init,
2472 bool TopLevelOfInitList = false,
2473 bool AllowExplicit = false);
2474 ExprResult PerformObjectArgumentInitialization(Expr *From,
2475 NestedNameSpecifier *Qualifier,
2476 NamedDecl *FoundDecl,
2477 CXXMethodDecl *Method);
2478
2479 ExprResult PerformContextuallyConvertToBool(Expr *From);
2480 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2481
2482 /// Contexts in which a converted constant expression is required.
2483 enum CCEKind {
2484 CCEK_CaseValue, ///< Expression in a case label.
2485 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2486 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2487 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2488 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2489 };
2490 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2491 llvm::APSInt &Value, CCEKind CCE);
2492 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2493 APValue &Value, CCEKind CCE);
2494
2495 /// \brief Abstract base class used to perform a contextual implicit
2496 /// conversion from an expression to any type passing a filter.
2497 class ContextualImplicitConverter {
2498 public:
2499 bool Suppress;
2500 bool SuppressConversion;
2501
2502 ContextualImplicitConverter(bool Suppress = false,
2503 bool SuppressConversion = false)
2504 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2505
2506 /// \brief Determine whether the specified type is a valid destination type
2507 /// for this conversion.
2508 virtual bool match(QualType T) = 0;
2509
2510 /// \brief Emits a diagnostic complaining that the expression does not have
2511 /// integral or enumeration type.
2512 virtual SemaDiagnosticBuilder
2513 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2514
2515 /// \brief Emits a diagnostic when the expression has incomplete class type.
2516 virtual SemaDiagnosticBuilder
2517 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2518
2519 /// \brief Emits a diagnostic when the only matching conversion function
2520 /// is explicit.
2521 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2522 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2523
2524 /// \brief Emits a note for the explicit conversion function.
2525 virtual SemaDiagnosticBuilder
2526 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2527
2528 /// \brief Emits a diagnostic when there are multiple possible conversion
2529 /// functions.
2530 virtual SemaDiagnosticBuilder
2531 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2532
2533 /// \brief Emits a note for one of the candidate conversions.
2534 virtual SemaDiagnosticBuilder
2535 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2536
2537 /// \brief Emits a diagnostic when we picked a conversion function
2538 /// (for cases when we are not allowed to pick a conversion function).
2539 virtual SemaDiagnosticBuilder diagnoseConversion(
2540 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2541
2542 virtual ~ContextualImplicitConverter() {}
2543 };
2544
2545 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2546 bool AllowScopedEnumerations;
2547
2548 public:
2549 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2550 bool Suppress, bool SuppressConversion)
2551 : ContextualImplicitConverter(Suppress, SuppressConversion),
2552 AllowScopedEnumerations(AllowScopedEnumerations) {}
2553
2554 /// Match an integral or (possibly scoped) enumeration type.
2555 bool match(QualType T) override;
2556
2557 SemaDiagnosticBuilder
2558 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2559 return diagnoseNotInt(S, Loc, T);
2560 }
2561
2562 /// \brief Emits a diagnostic complaining that the expression does not have
2563 /// integral or enumeration type.
2564 virtual SemaDiagnosticBuilder
2565 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2566 };
2567
2568 /// Perform a contextual implicit conversion.
2569 ExprResult PerformContextualImplicitConversion(
2570 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2571
2572
2573 enum ObjCSubscriptKind {
2574 OS_Array,
2575 OS_Dictionary,
2576 OS_Error
2577 };
2578 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2579
2580 // Note that LK_String is intentionally after the other literals, as
2581 // this is used for diagnostics logic.
2582 enum ObjCLiteralKind {
2583 LK_Array,
2584 LK_Dictionary,
2585 LK_Numeric,
2586 LK_Boxed,
2587 LK_String,
2588 LK_Block,
2589 LK_None
2590 };
2591 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2592
2593 ExprResult PerformObjectMemberConversion(Expr *From,
2594 NestedNameSpecifier *Qualifier,
2595 NamedDecl *FoundDecl,
2596 NamedDecl *Member);
2597
2598 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2599 // TODO: make this is a typesafe union.
2600 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2601 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2602
2603 void AddOverloadCandidate(FunctionDecl *Function,
2604 DeclAccessPair FoundDecl,
2605 ArrayRef<Expr *> Args,
2606 OverloadCandidateSet &CandidateSet,
2607 bool SuppressUserConversions = false,
2608 bool PartialOverloading = false,
2609 bool AllowExplicit = false,
2610 ConversionSequenceList EarlyConversions = None);
2611 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2612 ArrayRef<Expr *> Args,
2613 OverloadCandidateSet &CandidateSet,
2614 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2615 bool SuppressUserConversions = false,
2616 bool PartialOverloading = false);
2617 void AddMethodCandidate(DeclAccessPair FoundDecl,
2618 QualType ObjectType,
2619 Expr::Classification ObjectClassification,
2620 ArrayRef<Expr *> Args,
2621 OverloadCandidateSet& CandidateSet,
2622 bool SuppressUserConversion = false);
2623 void AddMethodCandidate(CXXMethodDecl *Method,
2624 DeclAccessPair FoundDecl,
2625 CXXRecordDecl *ActingContext, QualType ObjectType,
2626 Expr::Classification ObjectClassification,
2627 ArrayRef<Expr *> Args,
2628 OverloadCandidateSet& CandidateSet,
2629 bool SuppressUserConversions = false,
2630 bool PartialOverloading = false,
2631 ConversionSequenceList EarlyConversions = None);
2632 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2633 DeclAccessPair FoundDecl,
2634 CXXRecordDecl *ActingContext,
2635 TemplateArgumentListInfo *ExplicitTemplateArgs,
2636 QualType ObjectType,
2637 Expr::Classification ObjectClassification,
2638 ArrayRef<Expr *> Args,
2639 OverloadCandidateSet& CandidateSet,
2640 bool SuppressUserConversions = false,
2641 bool PartialOverloading = false);
2642 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2643 DeclAccessPair FoundDecl,
2644 TemplateArgumentListInfo *ExplicitTemplateArgs,
2645 ArrayRef<Expr *> Args,
2646 OverloadCandidateSet& CandidateSet,
2647 bool SuppressUserConversions = false,
2648 bool PartialOverloading = false);
2649 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2650 ArrayRef<QualType> ParamTypes,
2651 ArrayRef<Expr *> Args,
2652 OverloadCandidateSet &CandidateSet,
2653 ConversionSequenceList &Conversions,
2654 bool SuppressUserConversions,
2655 CXXRecordDecl *ActingContext = nullptr,
2656 QualType ObjectType = QualType(),
2657 Expr::Classification
2658 ObjectClassification = {});
2659 void AddConversionCandidate(CXXConversionDecl *Conversion,
2660 DeclAccessPair FoundDecl,
2661 CXXRecordDecl *ActingContext,
2662 Expr *From, QualType ToType,
2663 OverloadCandidateSet& CandidateSet,
2664 bool AllowObjCConversionOnExplicit);
2665 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2666 DeclAccessPair FoundDecl,
2667 CXXRecordDecl *ActingContext,
2668 Expr *From, QualType ToType,
2669 OverloadCandidateSet &CandidateSet,
2670 bool AllowObjCConversionOnExplicit);
2671 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2672 DeclAccessPair FoundDecl,
2673 CXXRecordDecl *ActingContext,
2674 const FunctionProtoType *Proto,
2675 Expr *Object, ArrayRef<Expr *> Args,
2676 OverloadCandidateSet& CandidateSet);
2677 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2678 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2679 OverloadCandidateSet& CandidateSet,
2680 SourceRange OpRange = SourceRange());
2681 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2682 ArrayRef<Expr *> Args,
2683 OverloadCandidateSet& CandidateSet,
2684 bool IsAssignmentOperator = false,
2685 unsigned NumContextualBoolArguments = 0);
2686 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2687 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2688 OverloadCandidateSet& CandidateSet);
2689 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2690 SourceLocation Loc,
2691 ArrayRef<Expr *> Args,
2692 TemplateArgumentListInfo *ExplicitTemplateArgs,
2693 OverloadCandidateSet& CandidateSet,
2694 bool PartialOverloading = false);
2695
2696 // Emit as a 'note' the specific overload candidate
2697 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2698 QualType DestType = QualType(),
2699 bool TakingAddress = false);
2700
2701 // Emit as a series of 'note's all template and non-templates identified by
2702 // the expression Expr
2703 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2704 bool TakingAddress = false);
2705
2706 /// Check the enable_if expressions on the given function. Returns the first
2707 /// failing attribute, or NULL if they were all successful.
2708 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2709 bool MissingImplicitThis = false);
2710
2711 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2712 /// non-ArgDependent DiagnoseIfAttrs.
2713 ///
2714 /// Argument-dependent diagnose_if attributes should be checked each time a
2715 /// function is used as a direct callee of a function call.
2716 ///
2717 /// Returns true if any errors were emitted.
2718 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2719 const Expr *ThisArg,
2720 ArrayRef<const Expr *> Args,
2721 SourceLocation Loc);
2722
2723 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2724 /// ArgDependent DiagnoseIfAttrs.
2725 ///
2726 /// Argument-independent diagnose_if attributes should be checked on every use
2727 /// of a function.
2728 ///
2729 /// Returns true if any errors were emitted.
2730 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2731 SourceLocation Loc);
2732
2733 /// Returns whether the given function's address can be taken or not,
2734 /// optionally emitting a diagnostic if the address can't be taken.
2735 ///
2736 /// Returns false if taking the address of the function is illegal.
2737 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2738 bool Complain = false,
2739 SourceLocation Loc = SourceLocation());
2740
2741 // [PossiblyAFunctionType] --> [Return]
2742 // NonFunctionType --> NonFunctionType
2743 // R (A) --> R(A)
2744 // R (*)(A) --> R (A)
2745 // R (&)(A) --> R (A)
2746 // R (S::*)(A) --> R (A)
2747 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2748
2749 FunctionDecl *
2750 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2751 QualType TargetType,
2752 bool Complain,
2753 DeclAccessPair &Found,
2754 bool *pHadMultipleCandidates = nullptr);
2755
2756 FunctionDecl *
2757 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2758 DeclAccessPair &FoundResult);
2759
2760 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2761 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2762
2763 FunctionDecl *
2764 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2765 bool Complain = false,
2766 DeclAccessPair *Found = nullptr);
2767
2768 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2769 ExprResult &SrcExpr,
2770 bool DoFunctionPointerConverion = false,
2771 bool Complain = false,
2772 SourceRange OpRangeForComplaining = SourceRange(),
2773 QualType DestTypeForComplaining = QualType(),
2774 unsigned DiagIDForComplaining = 0);
2775
2776
2777 Expr *FixOverloadedFunctionReference(Expr *E,
2778 DeclAccessPair FoundDecl,
2779 FunctionDecl *Fn);
2780 ExprResult FixOverloadedFunctionReference(ExprResult,
2781 DeclAccessPair FoundDecl,
2782 FunctionDecl *Fn);
2783
2784 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2785 ArrayRef<Expr *> Args,
2786 OverloadCandidateSet &CandidateSet,
2787 bool PartialOverloading = false);
2788
2789 // An enum used to represent the different possible results of building a
2790 // range-based for loop.
2791 enum ForRangeStatus {
2792 FRS_Success,
2793 FRS_NoViableFunction,
2794 FRS_DiagnosticIssued
2795 };
2796
2797 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2798 SourceLocation RangeLoc,
2799 const DeclarationNameInfo &NameInfo,
2800 LookupResult &MemberLookup,
2801 OverloadCandidateSet *CandidateSet,
2802 Expr *Range, ExprResult *CallExpr);
2803
2804 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2805 UnresolvedLookupExpr *ULE,
2806 SourceLocation LParenLoc,
2807 MultiExprArg Args,
2808 SourceLocation RParenLoc,
2809 Expr *ExecConfig,
2810 bool AllowTypoCorrection=true,
2811 bool CalleesAddressIsTaken=false);
2812
2813 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2814 MultiExprArg Args, SourceLocation RParenLoc,
2815 OverloadCandidateSet *CandidateSet,
2816 ExprResult *Result);
2817
2818 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2819 UnaryOperatorKind Opc,
2820 const UnresolvedSetImpl &Fns,
2821 Expr *input);
2822
2823 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2824 BinaryOperatorKind Opc,
2825 const UnresolvedSetImpl &Fns,
2826 Expr *LHS, Expr *RHS);
2827
2828 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2829 SourceLocation RLoc,
2830 Expr *Base,Expr *Idx);
2831
2832 ExprResult
2833 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2834 SourceLocation LParenLoc,
2835 MultiExprArg Args,
2836 SourceLocation RParenLoc);
2837 ExprResult
2838 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2839 MultiExprArg Args,
2840 SourceLocation RParenLoc);
2841
2842 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2843 SourceLocation OpLoc,
2844 bool *NoArrowOperatorFound = nullptr);
2845
2846 /// CheckCallReturnType - Checks that a call expression's return type is
2847 /// complete. Returns true on failure. The location passed in is the location
2848 /// that best represents the call.
2849 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2850 CallExpr *CE, FunctionDecl *FD);
2851
2852 /// Helpers for dealing with blocks and functions.
2853 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2854 bool CheckParameterNames);
2855 void CheckCXXDefaultArguments(FunctionDecl *FD);
2856 void CheckExtraCXXDefaultArguments(Declarator &D);
2857 Scope *getNonFieldDeclScope(Scope *S);
2858
2859 /// \name Name lookup
2860 ///
2861 /// These routines provide name lookup that is used during semantic
2862 /// analysis to resolve the various kinds of names (identifiers,
2863 /// overloaded operator names, constructor names, etc.) into zero or
2864 /// more declarations within a particular scope. The major entry
2865 /// points are LookupName, which performs unqualified name lookup,
2866 /// and LookupQualifiedName, which performs qualified name lookup.
2867 ///
2868 /// All name lookup is performed based on some specific criteria,
2869 /// which specify what names will be visible to name lookup and how
2870 /// far name lookup should work. These criteria are important both
2871 /// for capturing language semantics (certain lookups will ignore
2872 /// certain names, for example) and for performance, since name
2873 /// lookup is often a bottleneck in the compilation of C++. Name
2874 /// lookup criteria is specified via the LookupCriteria enumeration.
2875 ///
2876 /// The results of name lookup can vary based on the kind of name
2877 /// lookup performed, the current language, and the translation
2878 /// unit. In C, for example, name lookup will either return nothing
2879 /// (no entity found) or a single declaration. In C++, name lookup
2880 /// can additionally refer to a set of overloaded functions or
2881 /// result in an ambiguity. All of the possible results of name
2882 /// lookup are captured by the LookupResult class, which provides
2883 /// the ability to distinguish among them.
2884 //@{
2885
2886 /// @brief Describes the kind of name lookup to perform.
2887 enum LookupNameKind {
2888 /// Ordinary name lookup, which finds ordinary names (functions,
2889 /// variables, typedefs, etc.) in C and most kinds of names
2890 /// (functions, variables, members, types, etc.) in C++.
2891 LookupOrdinaryName = 0,
2892 /// Tag name lookup, which finds the names of enums, classes,
2893 /// structs, and unions.
2894 LookupTagName,
2895 /// Label name lookup.
2896 LookupLabel,
2897 /// Member name lookup, which finds the names of
2898 /// class/struct/union members.
2899 LookupMemberName,
2900 /// Look up of an operator name (e.g., operator+) for use with
2901 /// operator overloading. This lookup is similar to ordinary name
2902 /// lookup, but will ignore any declarations that are class members.
2903 LookupOperatorName,
2904 /// Look up of a name that precedes the '::' scope resolution
2905 /// operator in C++. This lookup completely ignores operator, object,
2906 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2907 LookupNestedNameSpecifierName,
2908 /// Look up a namespace name within a C++ using directive or
2909 /// namespace alias definition, ignoring non-namespace names (C++
2910 /// [basic.lookup.udir]p1).
2911 LookupNamespaceName,
2912 /// Look up all declarations in a scope with the given name,
2913 /// including resolved using declarations. This is appropriate
2914 /// for checking redeclarations for a using declaration.
2915 LookupUsingDeclName,
2916 /// Look up an ordinary name that is going to be redeclared as a
2917 /// name with linkage. This lookup ignores any declarations that
2918 /// are outside of the current scope unless they have linkage. See
2919 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2920 LookupRedeclarationWithLinkage,
2921 /// Look up a friend of a local class. This lookup does not look
2922 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2923 LookupLocalFriendName,
2924 /// Look up the name of an Objective-C protocol.
2925 LookupObjCProtocolName,
2926 /// Look up implicit 'self' parameter of an objective-c method.
2927 LookupObjCImplicitSelfParam,
2928 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2929 LookupOMPReductionName,
2930 /// \brief Look up any declaration with any name.
2931 LookupAnyName
2932 };
2933
2934 /// \brief Specifies whether (or how) name lookup is being performed for a
2935 /// redeclaration (vs. a reference).
2936 enum RedeclarationKind {
2937 /// \brief The lookup is a reference to this name that is not for the
2938 /// purpose of redeclaring the name.
2939 NotForRedeclaration = 0,
2940 /// \brief The lookup results will be used for redeclaration of a name,
2941 /// if an entity by that name already exists.
2942 ForRedeclaration
2943 };
2944
2945 /// \brief The possible outcomes of name lookup for a literal operator.
2946 enum LiteralOperatorLookupResult {
2947 /// \brief The lookup resulted in an error.
2948 LOLR_Error,
2949 /// \brief The lookup found a single 'cooked' literal operator, which
2950 /// expects a normal literal to be built and passed to it.
2951 LOLR_Cooked,
2952 /// \brief The lookup found a single 'raw' literal operator, which expects
2953 /// a string literal containing the spelling of the literal token.
2954 LOLR_Raw,
2955 /// \brief The lookup found an overload set of literal operator templates,
2956 /// which expect the characters of the spelling of the literal token to be
2957 /// passed as a non-type template argument pack.
2958 LOLR_Template,
2959 /// \brief The lookup found an overload set of literal operator templates,
2960 /// which expect the character type and characters of the spelling of the
2961 /// string literal token to be passed as template arguments.
2962 LOLR_StringTemplate
2963 };
2964
2965 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2966 CXXSpecialMember SM,
2967 bool ConstArg,
2968 bool VolatileArg,
2969 bool RValueThis,
2970 bool ConstThis,
2971 bool VolatileThis);
2972
2973 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2974 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2975 TypoRecoveryCallback;
2976
2977private:
2978 bool CppLookupName(LookupResult &R, Scope *S);
2979
2980 struct TypoExprState {
2981 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2982 TypoDiagnosticGenerator DiagHandler;
2983 TypoRecoveryCallback RecoveryHandler;
2984 TypoExprState();
2985 TypoExprState(TypoExprState &&other) noexcept;
2986 TypoExprState &operator=(TypoExprState &&other) noexcept;
2987 };
2988
2989 /// \brief The set of unhandled TypoExprs and their associated state.
2990 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2991
2992 /// \brief Creates a new TypoExpr AST node.
2993 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2994 TypoDiagnosticGenerator TDG,
2995 TypoRecoveryCallback TRC);
2996
2997 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2998 //
2999 // The boolean value will be true to indicate that the namespace was loaded
3000 // from an AST/PCH file, or false otherwise.
3001 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3002
3003 /// \brief Whether we have already loaded known namespaces from an extenal
3004 /// source.
3005 bool LoadedExternalKnownNamespaces;
3006
3007 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3008 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3009 /// should be skipped entirely.
3010 std::unique_ptr<TypoCorrectionConsumer>
3011 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3012 Sema::LookupNameKind LookupKind, Scope *S,
3013 CXXScopeSpec *SS,
3014 std::unique_ptr<CorrectionCandidateCallback> CCC,
3015 DeclContext *MemberContext, bool EnteringContext,
3016 const ObjCObjectPointerType *OPT,
3017 bool ErrorRecovery);
3018
3019public:
3020 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3021
3022 /// \brief Clears the state of the given TypoExpr.
3023 void clearDelayedTypo(TypoExpr *TE);
3024
3025 /// \brief Look up a name, looking for a single declaration. Return
3026 /// null if the results were absent, ambiguous, or overloaded.
3027 ///
3028 /// It is preferable to use the elaborated form and explicitly handle
3029 /// ambiguity and overloaded.
3030 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3031 SourceLocation Loc,
3032 LookupNameKind NameKind,
3033 RedeclarationKind Redecl
3034 = NotForRedeclaration);
3035 bool LookupName(LookupResult &R, Scope *S,
3036 bool AllowBuiltinCreation = false);
3037 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3038 bool InUnqualifiedLookup = false);
3039 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3040 CXXScopeSpec &SS);
3041 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3042 bool AllowBuiltinCreation = false,
3043 bool EnteringContext = false);
3044 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3045 RedeclarationKind Redecl
3046 = NotForRedeclaration);
3047 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3048
3049 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3050 QualType T1, QualType T2,
3051 UnresolvedSetImpl &Functions);
3052
3053 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3054 SourceLocation GnuLabelLoc = SourceLocation());
3055
3056 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3057 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3058 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3059 unsigned Quals);
3060 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3061 bool RValueThis, unsigned ThisQuals);
3062 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3063 unsigned Quals);
3064 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3065 bool RValueThis, unsigned ThisQuals);
3066 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3067
3068 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3069 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3070 ArrayRef<QualType> ArgTys,
3071 bool AllowRaw,
3072 bool AllowTemplate,
3073 bool AllowStringTemplate);
3074 bool isKnownName(StringRef name);
3075
3076 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3077 ArrayRef<Expr *> Args, ADLResult &Functions);
3078
3079 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3080 VisibleDeclConsumer &Consumer,
3081 bool IncludeGlobalScope = true);
3082 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3083 VisibleDeclConsumer &Consumer,
3084 bool IncludeGlobalScope = true,
3085 bool IncludeDependentBases = false);
3086
3087 enum CorrectTypoKind {
3088 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3089 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3090 };
3091
3092 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3093 Sema::LookupNameKind LookupKind,
3094 Scope *S, CXXScopeSpec *SS,
3095 std::unique_ptr<CorrectionCandidateCallback> CCC,
3096 CorrectTypoKind Mode,
3097 DeclContext *MemberContext = nullptr,
3098 bool EnteringContext = false,
3099 const ObjCObjectPointerType *OPT = nullptr,
3100 bool RecordFailure = true);
3101
3102 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3103 Sema::LookupNameKind LookupKind, Scope *S,
3104 CXXScopeSpec *SS,
3105 std::unique_ptr<CorrectionCandidateCallback> CCC,
3106 TypoDiagnosticGenerator TDG,
3107 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3108 DeclContext *MemberContext = nullptr,
3109 bool EnteringContext = false,
3110 const ObjCObjectPointerType *OPT = nullptr);
3111
3112 /// \brief Process any TypoExprs in the given Expr and its children,
3113 /// generating diagnostics as appropriate and returning a new Expr if there
3114 /// were typos that were all successfully corrected and ExprError if one or
3115 /// more typos could not be corrected.
3116 ///
3117 /// \param E The Expr to check for TypoExprs.
3118 ///
3119 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3120 /// initializer.
3121 ///
3122 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3123 /// it is an acceptable/usable result from a single combination of typo
3124 /// corrections. As long as the filter returns ExprError, different
3125 /// combinations of corrections will be tried until all are exhausted.
3126 ExprResult
3127 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3128 llvm::function_ref<ExprResult(Expr *)> Filter =
3129 [](Expr *E) -> ExprResult { return E; });
3130
3131 ExprResult
3132 CorrectDelayedTyposInExpr(Expr *E,
3133 llvm::function_ref<ExprResult(Expr *)> Filter) {
3134 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3135 }
3136
3137 ExprResult
3138 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3139 llvm::function_ref<ExprResult(Expr *)> Filter =
3140 [](Expr *E) -> ExprResult { return E; }) {
3141 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3142 }
3143
3144 ExprResult
3145 CorrectDelayedTyposInExpr(ExprResult ER,
3146 llvm::function_ref<ExprResult(Expr *)> Filter) {
3147 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3148 }
3149
3150 void diagnoseTypo(const TypoCorrection &Correction,
3151 const PartialDiagnostic &TypoDiag,
3152 bool ErrorRecovery = true);
3153
3154 void diagnoseTypo(const TypoCorrection &Correction,
3155 const PartialDiagnostic &TypoDiag,
3156 const PartialDiagnostic &PrevNote,
3157 bool ErrorRecovery = true);
3158
3159 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3160
3161 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3162 ArrayRef<Expr *> Args,
3163 AssociatedNamespaceSet &AssociatedNamespaces,
3164 AssociatedClassSet &AssociatedClasses);
3165
3166 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3167 bool ConsiderLinkage, bool AllowInlineNamespace);
3168
3169 void DiagnoseAmbiguousLookup(LookupResult &Result);
3170 //@}
3171
3172 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3173 SourceLocation IdLoc,
3174 bool TypoCorrection = false);
3175 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3176 Scope *S, bool ForRedeclaration,
3177 SourceLocation Loc);
3178 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3179 Scope *S);
3180 void AddKnownFunctionAttributes(FunctionDecl *FD);
3181
3182 // More parsing and symbol table subroutines.
3183
3184 void ProcessPragmaWeak(Scope *S, Decl *D);
3185 // Decl attributes - this routine is the top level dispatcher.
3186 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3187 // Helper for delayed proccessing of attributes.
3188 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3189 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3190 bool IncludeCXX11Attributes = true);
3191 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3192 const AttributeList *AttrList);
3193
3194 void checkUnusedDeclAttributes(Declarator &D);
3195
3196 /// Determine if type T is a valid subject for a nonnull and similar
3197 /// attributes. By default, we look through references (the behavior used by
3198 /// nonnull), but if the second parameter is true, then we treat a reference
3199 /// type as valid.
3200 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3201
3202 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3203 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3204 const FunctionDecl *FD = nullptr);
3205 bool CheckNoReturnAttr(const AttributeList &attr);
3206 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3207 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3208 unsigned ArgNum, StringRef &Str,
3209 SourceLocation *ArgLocation = nullptr);
3210 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3211 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3212 bool checkMSInheritanceAttrOnDefinition(
3213 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3214 MSInheritanceAttr::Spelling SemanticSpelling);
3215
3216 void CheckAlignasUnderalignment(Decl *D);
3217
3218 /// Adjust the calling convention of a method to be the ABI default if it
3219 /// wasn't specified explicitly. This handles method types formed from
3220 /// function type typedefs and typename template arguments.
3221 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3222 SourceLocation Loc);
3223
3224 // Check if there is an explicit attribute, but only look through parens.
3225 // The intent is to look for an attribute on the current declarator, but not
3226 // one that came from a typedef.
3227 bool hasExplicitCallingConv(QualType &T);
3228
3229 /// Get the outermost AttributedType node that sets a calling convention.
3230 /// Valid types should not have multiple attributes with different CCs.
3231 const AttributedType *getCallingConvAttributedType(QualType T) const;
3232
3233 /// Check whether a nullability type specifier can be added to the given
3234 /// type.
3235 ///
3236 /// \param type The type to which the nullability specifier will be
3237 /// added. On success, this type will be updated appropriately.
3238 ///
3239 /// \param nullability The nullability specifier to add.
3240 ///
3241 /// \param nullabilityLoc The location of the nullability specifier.
3242 ///
3243 /// \param isContextSensitive Whether this nullability specifier was
3244 /// written as a context-sensitive keyword (in an Objective-C
3245 /// method) or an Objective-C property attribute, rather than as an
3246 /// underscored type specifier.
3247 ///
3248 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3249 /// array type (e.g., because it will decay to a pointer).
3250 ///
3251 /// \returns true if nullability cannot be applied, false otherwise.
3252 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3253 SourceLocation nullabilityLoc,
3254 bool isContextSensitive,
3255 bool allowArrayTypes);
3256
3257 /// \brief Stmt attributes - this routine is the top level dispatcher.
3258 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3259 SourceRange Range);
3260
3261 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3262 ObjCMethodDecl *MethodDecl,
3263 bool IsProtocolMethodDecl);
3264
3265 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3266 ObjCMethodDecl *Overridden,
3267 bool IsProtocolMethodDecl);
3268
3269 /// WarnExactTypedMethods - This routine issues a warning if method
3270 /// implementation declaration matches exactly that of its declaration.
3271 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3272 ObjCMethodDecl *MethodDecl,
3273 bool IsProtocolMethodDecl);
3274
3275 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3276
3277 /// CheckImplementationIvars - This routine checks if the instance variables
3278 /// listed in the implelementation match those listed in the interface.
3279 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3280 ObjCIvarDecl **Fields, unsigned nIvars,
3281 SourceLocation Loc);
3282
3283 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3284 /// remains unimplemented in the class or category \@implementation.
3285 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3286 ObjCContainerDecl* IDecl,
3287 bool IncompleteImpl = false);
3288
3289 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3290 /// which must be implemented by this implementation.
3291 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3292 ObjCContainerDecl *CDecl,
3293 bool SynthesizeProperties);
3294
3295 /// Diagnose any null-resettable synthesized setters.
3296 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3297
3298 /// DefaultSynthesizeProperties - This routine default synthesizes all
3299 /// properties which must be synthesized in the class's \@implementation.
3300 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3301 ObjCInterfaceDecl *IDecl);
3302 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3303
3304 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3305 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3306 /// declared in class 'IFace'.
3307 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3308 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3309
3310 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3311 /// backs the property is not used in the property's accessor.
3312 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3313 const ObjCImplementationDecl *ImplD);
3314
3315 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3316 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3317 /// It also returns ivar's property on success.
3318 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3319 const ObjCPropertyDecl *&PDecl) const;
3320
3321 /// Called by ActOnProperty to handle \@property declarations in
3322 /// class extensions.
3323 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3324 SourceLocation AtLoc,
3325 SourceLocation LParenLoc,
3326 FieldDeclarator &FD,
3327 Selector GetterSel,
3328 SourceLocation GetterNameLoc,
3329 Selector SetterSel,
3330 SourceLocation SetterNameLoc,
3331 const bool isReadWrite,
3332 unsigned &Attributes,
3333 const unsigned AttributesAsWritten,
3334 QualType T,
3335 TypeSourceInfo *TSI,
3336 tok::ObjCKeywordKind MethodImplKind);
3337
3338 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3339 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3340 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3341 ObjCContainerDecl *CDecl,
3342 SourceLocation AtLoc,
3343 SourceLocation LParenLoc,
3344 FieldDeclarator &FD,
3345 Selector GetterSel,
3346 SourceLocation GetterNameLoc,
3347 Selector SetterSel,
3348 SourceLocation SetterNameLoc,
3349 const bool isReadWrite,
3350 const unsigned Attributes,
3351 const unsigned AttributesAsWritten,
3352 QualType T,
3353 TypeSourceInfo *TSI,
3354 tok::ObjCKeywordKind MethodImplKind,
3355 DeclContext *lexicalDC = nullptr);
3356
3357 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3358 /// warning) when atomic property has one but not the other user-declared
3359 /// setter or getter.
3360 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3361 ObjCInterfaceDecl* IDecl);
3362
3363 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3364
3365 void DiagnoseMissingDesignatedInitOverrides(
3366 const ObjCImplementationDecl *ImplD,
3367 const ObjCInterfaceDecl *IFD);
3368
3369 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3370
3371 enum MethodMatchStrategy {
3372 MMS_loose,
3373 MMS_strict
3374 };
3375
3376 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3377 /// true, or false, accordingly.
3378 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3379 const ObjCMethodDecl *PrevMethod,
3380 MethodMatchStrategy strategy = MMS_strict);
3381
3382 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3383 /// or protocol against those declared in their implementations.
3384 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3385 const SelectorSet &ClsMap,
3386 SelectorSet &InsMapSeen,
3387 SelectorSet &ClsMapSeen,
3388 ObjCImplDecl* IMPDecl,
3389 ObjCContainerDecl* IDecl,
3390 bool &IncompleteImpl,
3391 bool ImmediateClass,
3392 bool WarnCategoryMethodImpl=false);
3393
3394 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3395 /// category matches with those implemented in its primary class and
3396 /// warns each time an exact match is found.
3397 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3398
3399 /// \brief Add the given method to the list of globally-known methods.
3400 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3401
3402private:
3403 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3404 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3405 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3406
3407 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3408 /// optionally warns if there are multiple signatures.
3409 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3410 bool receiverIdOrClass,
3411 bool instance);
3412
3413public:
3414 /// \brief - Returns instance or factory methods in global method pool for
3415 /// given selector. It checks the desired kind first, if none is found, and
3416 /// parameter checkTheOther is set, it then checks the other kind. If no such
3417 /// method or only one method is found, function returns false; otherwise, it
3418 /// returns true.
3419 bool
3420 CollectMultipleMethodsInGlobalPool(Selector Sel,
3421 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3422 bool InstanceFirst, bool CheckTheOther,
3423 const ObjCObjectType *TypeBound = nullptr);
3424
3425 bool
3426 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3427 SourceRange R, bool receiverIdOrClass,
3428 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3429
3430 void
3431 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3432 Selector Sel, SourceRange R,
3433 bool receiverIdOrClass);
3434
3435private:
3436 /// \brief - Returns a selector which best matches given argument list or
3437 /// nullptr if none could be found
3438 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3439 bool IsInstance,
3440 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3441
3442
3443 /// \brief Record the typo correction failure and return an empty correction.
3444 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3445 bool RecordFailure = true) {
3446 if (RecordFailure)
3447 TypoCorrectionFailures[Typo].insert(TypoLoc);
3448 return TypoCorrection();
3449 }
3450
3451public:
3452 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3453 /// unit are added to a global pool. This allows us to efficiently associate
3454 /// a selector with a method declaraation for purposes of typechecking
3455 /// messages sent to "id" (where the class of the object is unknown).
3456 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3457 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3458 }
3459
3460 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3461 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3462 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3463 }
3464
3465 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3466 /// pool.
3467 void AddAnyMethodToGlobalPool(Decl *D);
3468
3469 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3470 /// there are multiple signatures.
3471 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3472 bool receiverIdOrClass=false) {
3473 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3474 /*instance*/true);
3475 }
3476
3477 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3478 /// there are multiple signatures.
3479 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3480 bool receiverIdOrClass=false) {
3481 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3482 /*instance*/false);
3483 }
3484
3485 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3486 QualType ObjectType=QualType());
3487 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3488 /// implementation.
3489 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3490
3491 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3492 /// initialization.
3493 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3494 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3495
3496 //===--------------------------------------------------------------------===//
3497 // Statement Parsing Callbacks: SemaStmt.cpp.
3498public:
3499 class FullExprArg {
3500 public:
3501 FullExprArg() : E(nullptr) { }
3502 FullExprArg(Sema &actions) : E(nullptr) { }
3503
3504 ExprResult release() {
3505 return E;
3506 }
3507
3508 Expr *get() const { return E; }
3509
3510 Expr *operator->() {
3511 return E;
3512 }
3513
3514 private:
3515 // FIXME: No need to make the entire Sema class a friend when it's just
3516 // Sema::MakeFullExpr that needs access to the constructor below.
3517 friend class Sema;
3518
3519 explicit FullExprArg(Expr *expr) : E(expr) {}
3520
3521 Expr *E;
3522 };
3523
3524 FullExprArg MakeFullExpr(Expr *Arg) {
3525 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3526 }
3527 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3528 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3529 }
3530 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3531 ExprResult FE =
3532 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3533 /*DiscardedValue*/ true);
3534 return FullExprArg(FE.get());
3535 }
3536
3537 StmtResult ActOnExprStmt(ExprResult Arg);
3538 StmtResult ActOnExprStmtError();
3539
3540 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3541 bool HasLeadingEmptyMacro = false);
3542
3543 void ActOnStartOfCompoundStmt();
3544 void ActOnFinishOfCompoundStmt();
3545 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3546 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3547
3548 /// \brief A RAII object to enter scope of a compound statement.
3549 class CompoundScopeRAII {
3550 public:
3551 CompoundScopeRAII(Sema &S): S(S) {
3552 S.ActOnStartOfCompoundStmt();
3553 }
3554
3555 ~CompoundScopeRAII() {
3556 S.ActOnFinishOfCompoundStmt();
3557 }
3558
3559 private:
3560 Sema &S;
3561 };
3562
3563 /// An RAII helper that pops function a function scope on exit.
3564 struct FunctionScopeRAII {
3565 Sema &S;
3566 bool Active;
3567 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3568 ~FunctionScopeRAII() {
3569 if (Active)
3570 S.PopFunctionScopeInfo();
3571 }
3572 void disable() { Active = false; }
3573 };
3574
3575 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3576 SourceLocation StartLoc,
3577 SourceLocation EndLoc);
3578 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3579 StmtResult ActOnForEachLValueExpr(Expr *E);
3580 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3581 SourceLocation DotDotDotLoc, Expr *RHSVal,
3582 SourceLocation ColonLoc);
3583 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3584
3585 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3586 SourceLocation ColonLoc,
3587 Stmt *SubStmt, Scope *CurScope);
3588 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3589 SourceLocation ColonLoc, Stmt *SubStmt);
3590
3591 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3592 ArrayRef<const Attr*> Attrs,
3593 Stmt *SubStmt);
3594
3595 class ConditionResult;
3596 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3597 Stmt *InitStmt,
3598 ConditionResult Cond, Stmt *ThenVal,
3599 SourceLocation ElseLoc, Stmt *ElseVal);
3600 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3601 Stmt *InitStmt,
3602 ConditionResult Cond, Stmt *ThenVal,
3603 SourceLocation ElseLoc, Stmt *ElseVal);
3604 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3605 Stmt *InitStmt,
3606 ConditionResult Cond);
3607 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3608 Stmt *Switch, Stmt *Body);
3609 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3610 Stmt *Body);
3611 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3612 SourceLocation WhileLoc, SourceLocation CondLParen,
3613 Expr *Cond, SourceLocation CondRParen);
3614
3615 StmtResult ActOnForStmt(SourceLocation ForLoc,
3616 SourceLocation LParenLoc,
3617 Stmt *First,
3618 ConditionResult Second,
3619 FullExprArg Third,
3620 SourceLocation RParenLoc,
3621 Stmt *Body);
3622 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3623 Expr *collection);
3624 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3625 Stmt *First, Expr *collection,
3626 SourceLocation RParenLoc);
3627 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3628
3629 enum BuildForRangeKind {
3630 /// Initial building of a for-range statement.
3631 BFRK_Build,
3632 /// Instantiation or recovery rebuild of a for-range statement. Don't
3633 /// attempt any typo-correction.
3634 BFRK_Rebuild,
3635 /// Determining whether a for-range statement could be built. Avoid any
3636 /// unnecessary or irreversible actions.
3637 BFRK_Check
3638 };
3639
3640 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3641 SourceLocation CoawaitLoc,
3642 Stmt *LoopVar,
3643 SourceLocation ColonLoc, Expr *Collection,
3644 SourceLocation RParenLoc,
3645 BuildForRangeKind Kind);
3646 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3647 SourceLocation CoawaitLoc,
3648 SourceLocation ColonLoc,
3649 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3650 Expr *Cond, Expr *Inc,
3651 Stmt *LoopVarDecl,
3652 SourceLocation RParenLoc,
3653 BuildForRangeKind Kind);
3654 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3655
3656 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3657 SourceLocation LabelLoc,
3658 LabelDecl *TheDecl);
3659 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3660 SourceLocation StarLoc,
3661 Expr *DestExp);
3662 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3663 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3664
3665 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3666 CapturedRegionKind Kind, unsigned NumParams);
3667 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3668 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3669 CapturedRegionKind Kind,
3670 ArrayRef<CapturedParamNameType> Params);
3671 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3672 void ActOnCapturedRegionError();
3673 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3674 SourceLocation Loc,
3675 unsigned NumParams);
3676 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3677 bool AllowParamOrMoveConstructible);
3678 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3679 bool AllowParamOrMoveConstructible);
3680
3681 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3682 Scope *CurScope);
3683 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3684 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3685
3686 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3687 bool IsVolatile, unsigned NumOutputs,
3688 unsigned NumInputs, IdentifierInfo **Names,
3689 MultiExprArg Constraints, MultiExprArg Exprs,
3690 Expr *AsmString, MultiExprArg Clobbers,
3691 SourceLocation RParenLoc);
3692
3693 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3694 SourceLocation TemplateKWLoc,
3695 UnqualifiedId &Id,
3696 llvm::InlineAsmIdentifierInfo &Info,
3697 bool IsUnevaluatedContext);
3698 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3699 unsigned &Offset, SourceLocation AsmLoc);
3700 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3701 llvm::InlineAsmIdentifierInfo &Info,
3702 SourceLocation AsmLoc);
3703 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3704 ArrayRef<Token> AsmToks,
3705 StringRef AsmString,
3706 unsigned NumOutputs, unsigned NumInputs,
3707 ArrayRef<StringRef> Constraints,
3708 ArrayRef<StringRef> Clobbers,
3709 ArrayRef<Expr*> Exprs,
3710 SourceLocation EndLoc);
3711 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3712 SourceLocation Location,
3713 bool AlwaysCreate);
3714
3715 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3716 SourceLocation StartLoc,
3717 SourceLocation IdLoc, IdentifierInfo *Id,
3718 bool Invalid = false);
3719
3720 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3721
3722 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3723 Decl *Parm, Stmt *Body);
3724
3725 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3726
3727 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3728 MultiStmtArg Catch, Stmt *Finally);
3729
3730 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3731 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3732 Scope *CurScope);
3733 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3734 Expr *operand);
3735 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3736 Expr *SynchExpr,
3737 Stmt *SynchBody);
3738
3739 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3740
3741 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3742 SourceLocation StartLoc,
3743 SourceLocation IdLoc,
3744 IdentifierInfo *Id);
3745
3746 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3747
3748 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3749 Decl *ExDecl, Stmt *HandlerBlock);
3750 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3751 ArrayRef<Stmt *> Handlers);
3752
3753 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3754 SourceLocation TryLoc, Stmt *TryBlock,
3755 Stmt *Handler);
3756 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3757 Expr *FilterExpr,
3758 Stmt *Block);
3759 void ActOnStartSEHFinallyBlock();
3760 void ActOnAbortSEHFinallyBlock();
3761 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3762 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3763
3764 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3765
3766 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3767
3768 /// \brief If it's a file scoped decl that must warn if not used, keep track
3769 /// of it.
3770 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3771
3772 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3773 /// whose result is unused, warn.
3774 void DiagnoseUnusedExprResult(const Stmt *S);
3775 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3776 void DiagnoseUnusedDecl(const NamedDecl *ND);
3777
3778 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3779 /// statement as a \p Body, and it is located on the same line.
3780 ///
3781 /// This helps prevent bugs due to typos, such as:
3782 /// if (condition);
3783 /// do_stuff();
3784 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3785 const Stmt *Body,
3786 unsigned DiagID);
3787
3788 /// Warn if a for/while loop statement \p S, which is followed by
3789 /// \p PossibleBody, has a suspicious null statement as a body.
3790 void DiagnoseEmptyLoopBody(const Stmt *S,
3791 const Stmt *PossibleBody);
3792
3793 /// Warn if a value is moved to itself.
3794 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3795 SourceLocation OpLoc);
3796
3797 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3798 /// _Nonnull one.
3799 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3800 SourceLocation Loc);
3801
3802 /// Warn when implicitly casting 0 to nullptr.
3803 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3804
3805 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3806 return DelayedDiagnostics.push(pool);
3807 }
3808 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3809
3810 typedef ProcessingContextState ParsingClassState;
3811 ParsingClassState PushParsingClass() {
3812 return DelayedDiagnostics.pushUndelayed();
3813 }
3814 void PopParsingClass(ParsingClassState state) {
3815 DelayedDiagnostics.popUndelayed(state);
3816 }
3817
3818 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3819
3820 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3821 StringRef Message, SourceLocation Loc,
3822 const ObjCInterfaceDecl *UnknownObjCClass,
3823 const ObjCPropertyDecl *ObjCProperty,
3824 bool ObjCPropertyAccess);
3825
3826 bool makeUnavailableInSystemHeader(SourceLocation loc,
3827 UnavailableAttr::ImplicitReason reason);
3828
3829 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3830 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3831
3832 //===--------------------------------------------------------------------===//
3833 // Expression Parsing Callbacks: SemaExpr.cpp.
3834
3835 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3836 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3837 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3838 bool ObjCPropertyAccess=false);
3839 void NoteDeletedFunction(FunctionDecl *FD);
3840 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3841 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3842 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3843 ObjCMethodDecl *Getter,
3844 SourceLocation Loc);
3845 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3846 ArrayRef<Expr *> Args);
3847
3848 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3849 Decl *LambdaContextDecl = nullptr,
3850 bool IsDecltype = false);
3851 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3852 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3853 ReuseLambdaContextDecl_t,
3854 bool IsDecltype = false);
3855 void PopExpressionEvaluationContext();
3856
3857 void DiscardCleanupsInEvaluationContext();
3858
3859 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3860 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3861
3862 ExprResult ActOnConstantExpression(ExprResult Res);
3863
3864 // Functions for marking a declaration referenced. These functions also
3865 // contain the relevant logic for marking if a reference to a function or
3866 // variable is an odr-use (in the C++11 sense). There are separate variants
3867 // for expressions referring to a decl; these exist because odr-use marking
3868 // needs to be delayed for some constant variables when we build one of the
3869 // named expressions.
3870 //
3871 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3872 // should usually be true. This only needs to be set to false if the lack of
3873 // odr-use cannot be determined from the current context (for instance,
3874 // because the name denotes a virtual function and was written without an
3875 // explicit nested-name-specifier).
3876 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3877 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3878 bool MightBeOdrUse = true);
3879 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3880 void MarkDeclRefReferenced(DeclRefExpr *E);
3881 void MarkMemberReferenced(MemberExpr *E);
3882
3883 void UpdateMarkingForLValueToRValue(Expr *E);
3884 void CleanupVarDeclMarking();
3885
3886 enum TryCaptureKind {
3887 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3888 };
3889
3890 /// \brief Try to capture the given variable.
3891 ///
3892 /// \param Var The variable to capture.
3893 ///
3894 /// \param Loc The location at which the capture occurs.
3895 ///
3896 /// \param Kind The kind of capture, which may be implicit (for either a
3897 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3898 ///
3899 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3900 /// an explicit lambda capture.
3901 ///
3902 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3903 /// captures or diagnose errors. If false, this routine merely check whether
3904 /// the capture can occur without performing the capture itself or complaining
3905 /// if the variable cannot be captured.
3906 ///
3907 /// \param CaptureType Will be set to the type of the field used to capture
3908 /// this variable in the innermost block or lambda. Only valid when the
3909 /// variable can be captured.
3910 ///
3911 /// \param DeclRefType Will be set to the type of a reference to the capture
3912 /// from within the current scope. Only valid when the variable can be
3913 /// captured.
3914 ///
3915 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3916 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3917 /// This is useful when enclosing lambdas must speculatively capture
3918 /// variables that may or may not be used in certain specializations of
3919 /// a nested generic lambda.
3920 ///
3921 /// \returns true if an error occurred (i.e., the variable cannot be
3922 /// captured) and false if the capture succeeded.
3923 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3924 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3925 QualType &CaptureType,
3926 QualType &DeclRefType,
3927 const unsigned *const FunctionScopeIndexToStopAt);
3928
3929 /// \brief Try to capture the given variable.
3930 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3931 TryCaptureKind Kind = TryCapture_Implicit,
3932 SourceLocation EllipsisLoc = SourceLocation());
3933
3934 /// \brief Checks if the variable must be captured.
3935 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3936
3937 /// \brief Given a variable, determine the type that a reference to that
3938 /// variable will have in the given scope.
3939 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3940
3941 /// Mark all of the declarations referenced within a particular AST node as
3942 /// referenced. Used when template instantiation instantiates a non-dependent
3943 /// type -- entities referenced by the type are now referenced.
3944 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3945 void MarkDeclarationsReferencedInExpr(Expr *E,
3946 bool SkipLocalVariables = false);
3947
3948 /// \brief Try to recover by turning the given expression into a
3949 /// call. Returns true if recovery was attempted or an error was
3950 /// emitted; this may also leave the ExprResult invalid.
3951 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3952 bool ForceComplain = false,
3953 bool (*IsPlausibleResult)(QualType) = nullptr);
3954
3955 /// \brief Figure out if an expression could be turned into a call.
3956 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3957 UnresolvedSetImpl &NonTemplateOverloads);
3958
3959 /// \brief Conditionally issue a diagnostic based on the current
3960 /// evaluation context.
3961 ///
3962 /// \param Statement If Statement is non-null, delay reporting the
3963 /// diagnostic until the function body is parsed, and then do a basic
3964 /// reachability analysis to determine if the statement is reachable.
3965 /// If it is unreachable, the diagnostic will not be emitted.
3966 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3967 const PartialDiagnostic &PD);
3968
3969 // Primary Expressions.
3970 SourceRange getExprRange(Expr *E) const;
3971
3972 ExprResult ActOnIdExpression(
3973 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3974 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3975 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3976 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3977
3978 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3979 TemplateArgumentListInfo &Buffer,
3980 DeclarationNameInfo &NameInfo,
3981 const TemplateArgumentListInfo *&TemplateArgs);
3982
3983 bool
3984 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3985 std::unique_ptr<CorrectionCandidateCallback> CCC,
3986 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3987 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3988
3989 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3990 IdentifierInfo *II,
3991 bool AllowBuiltinCreation=false);
3992
3993 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3994 SourceLocation TemplateKWLoc,
3995 const DeclarationNameInfo &NameInfo,
3996 bool isAddressOfOperand,
3997 const TemplateArgumentListInfo *TemplateArgs);
3998
3999 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4000 ExprValueKind VK,
4001 SourceLocation Loc,
4002 const CXXScopeSpec *SS = nullptr);
4003 ExprResult
4004 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4005 const DeclarationNameInfo &NameInfo,
4006 const CXXScopeSpec *SS = nullptr,
4007 NamedDecl *FoundD = nullptr,
4008 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4009 ExprResult
4010 BuildAnonymousStructUnionMemberReference(
4011 const CXXScopeSpec &SS,
4012 SourceLocation nameLoc,
4013 IndirectFieldDecl *indirectField,
4014 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4015 Expr *baseObjectExpr = nullptr,
4016 SourceLocation opLoc = SourceLocation());
4017
4018 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4019 SourceLocation TemplateKWLoc,
4020 LookupResult &R,
4021 const TemplateArgumentListInfo *TemplateArgs,
4022 const Scope *S);
4023 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4024 SourceLocation TemplateKWLoc,
4025 LookupResult &R,
4026 const TemplateArgumentListInfo *TemplateArgs,
4027 bool IsDefiniteInstance,
4028 const Scope *S);
4029 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4030 const LookupResult &R,
4031 bool HasTrailingLParen);
4032
4033 ExprResult
4034 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4035 const DeclarationNameInfo &NameInfo,
4036 bool IsAddressOfOperand, const Scope *S,
4037 TypeSourceInfo **RecoveryTSI = nullptr);
4038
4039 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4040 SourceLocation TemplateKWLoc,
4041 const DeclarationNameInfo &NameInfo,
4042 const TemplateArgumentListInfo *TemplateArgs);
4043
4044 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4045 LookupResult &R,
4046 bool NeedsADL,
4047 bool AcceptInvalidDecl = false);
4048 ExprResult BuildDeclarationNameExpr(
4049 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4050 NamedDecl *FoundD = nullptr,
4051 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4052 bool AcceptInvalidDecl = false);
4053
4054 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4055 DeclarationNameInfo &SuffixInfo,
4056 ArrayRef<Expr *> Args,
4057 SourceLocation LitEndLoc,
4058 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4059
4060 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4061 PredefinedExpr::IdentType IT);
4062 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4063 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4064
4065 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4066
4067 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4068 ExprResult ActOnCharacterConstant(const Token &Tok,
4069 Scope *UDLScope = nullptr);
4070 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4071 ExprResult ActOnParenListExpr(SourceLocation L,
4072 SourceLocation R,
4073 MultiExprArg Val);
4074
4075 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4076 /// fragments (e.g. "foo" "bar" L"baz").
4077 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4078 Scope *UDLScope = nullptr);
4079
4080 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4081 SourceLocation DefaultLoc,
4082 SourceLocation RParenLoc,
4083 Expr *ControllingExpr,
4084 ArrayRef<ParsedType> ArgTypes,
4085 ArrayRef<Expr *> ArgExprs);
4086 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4087 SourceLocation DefaultLoc,
4088 SourceLocation RParenLoc,
4089 Expr *ControllingExpr,
4090 ArrayRef<TypeSourceInfo *> Types,
4091 ArrayRef<Expr *> Exprs);
4092
4093 // Binary/Unary Operators. 'Tok' is the token for the operator.
4094 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4095 Expr *InputExpr);
4096 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4097 UnaryOperatorKind Opc, Expr *Input);
4098 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4099 tok::TokenKind Op, Expr *Input);
4100
4101 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4102
4103 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4104 SourceLocation OpLoc,
4105 UnaryExprOrTypeTrait ExprKind,
4106 SourceRange R);
4107 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4108 UnaryExprOrTypeTrait ExprKind);
4109 ExprResult
4110 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4111 UnaryExprOrTypeTrait ExprKind,
4112 bool IsType, void *TyOrEx,
4113 SourceRange ArgRange);
4114
4115 ExprResult CheckPlaceholderExpr(Expr *E);
4116 bool CheckVecStepExpr(Expr *E);
4117
4118 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4119 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4120 SourceRange ExprRange,
4121 UnaryExprOrTypeTrait ExprKind);
4122 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4123 SourceLocation OpLoc,
4124 IdentifierInfo &Name,
4125 SourceLocation NameLoc,
4126 SourceLocation RParenLoc);
4127 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4128 tok::TokenKind Kind, Expr *Input);
4129
4130 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4131 Expr *Idx, SourceLocation RLoc);
4132 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4133 Expr *Idx, SourceLocation RLoc);
4134 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4135 Expr *LowerBound, SourceLocation ColonLoc,
4136 Expr *Length, SourceLocation RBLoc);
4137
4138 // This struct is for use by ActOnMemberAccess to allow
4139 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4140 // changing the access operator from a '.' to a '->' (to see if that is the
4141 // change needed to fix an error about an unknown member, e.g. when the class
4142 // defines a custom operator->).
4143 struct ActOnMemberAccessExtraArgs {
4144 Scope *S;
4145 UnqualifiedId &Id;
4146 Decl *ObjCImpDecl;
4147 };
4148
4149 ExprResult BuildMemberReferenceExpr(
4150 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4151 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4152 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4153 const TemplateArgumentListInfo *TemplateArgs,
4154 const Scope *S,
4155 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4156
4157 ExprResult
4158 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4159 bool IsArrow, const CXXScopeSpec &SS,
4160 SourceLocation TemplateKWLoc,
4161 NamedDecl *FirstQualifierInScope, LookupResult &R,
4162 const TemplateArgumentListInfo *TemplateArgs,
4163 const Scope *S,
4164 bool SuppressQualifierCheck = false,
4165 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4166
4167 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4168 SourceLocation OpLoc,
4169 const CXXScopeSpec &SS, FieldDecl *Field,
4170 DeclAccessPair FoundDecl,
4171 const DeclarationNameInfo &MemberNameInfo);
4172
4173 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4174
4175 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4176 const CXXScopeSpec &SS,
4177 const LookupResult &R);
4178
4179 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4180 bool IsArrow, SourceLocation OpLoc,
4181 const CXXScopeSpec &SS,
4182 SourceLocation TemplateKWLoc,
4183 NamedDecl *FirstQualifierInScope,
4184 const DeclarationNameInfo &NameInfo,
4185 const TemplateArgumentListInfo *TemplateArgs);
4186
4187 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4188 SourceLocation OpLoc,
4189 tok::TokenKind OpKind,
4190 CXXScopeSpec &SS,
4191 SourceLocation TemplateKWLoc,
4192 UnqualifiedId &Member,
4193 Decl *ObjCImpDecl);
4194
4195 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4196 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4197 FunctionDecl *FDecl,
4198 const FunctionProtoType *Proto,
4199 ArrayRef<Expr *> Args,
4200 SourceLocation RParenLoc,
4201 bool ExecConfig = false);
4202 void CheckStaticArrayArgument(SourceLocation CallLoc,
4203 ParmVarDecl *Param,
4204 const Expr *ArgExpr);
4205
4206 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4207 /// This provides the location of the left/right parens and a list of comma
4208 /// locations.
4209 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4210 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4211 Expr *ExecConfig = nullptr,
4212 bool IsExecConfig = false);
4213 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4214 SourceLocation LParenLoc,
4215 ArrayRef<Expr *> Arg,
4216 SourceLocation RParenLoc,
4217 Expr *Config = nullptr,
4218 bool IsExecConfig = false);
4219
4220 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4221 MultiExprArg ExecConfig,
4222 SourceLocation GGGLoc);
4223
4224 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4225 Declarator &D, ParsedType &Ty,
4226 SourceLocation RParenLoc, Expr *CastExpr);
4227 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4228 TypeSourceInfo *Ty,
4229 SourceLocation RParenLoc,
4230 Expr *Op);
4231 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4232
4233 /// \brief Build an altivec or OpenCL literal.
4234 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4235 SourceLocation RParenLoc, Expr *E,
4236 TypeSourceInfo *TInfo);
4237
4238 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4239
4240 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4241 ParsedType Ty,
4242 SourceLocation RParenLoc,
4243 Expr *InitExpr);
4244
4245 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4246 TypeSourceInfo *TInfo,
4247 SourceLocation RParenLoc,
4248 Expr *LiteralExpr);
4249
4250 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4251 MultiExprArg InitArgList,
4252 SourceLocation RBraceLoc);
4253
4254 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4255 SourceLocation Loc,
4256 bool GNUSyntax,
4257 ExprResult Init);
4258
4259private:
4260 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4261
4262public:
4263 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4264 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4265 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4266 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4267 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4268 Expr *LHSExpr, Expr *RHSExpr);
4269
4270 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4271
4272 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4273 /// in the case of a the GNU conditional expr extension.
4274 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4275 SourceLocation ColonLoc,
4276 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4277
4278 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4279 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4280 LabelDecl *TheDecl);
4281
4282 void ActOnStartStmtExpr();
4283 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4284 SourceLocation RPLoc); // "({..})"
4285 void ActOnStmtExprError();
4286
4287 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4288 struct OffsetOfComponent {
4289 SourceLocation LocStart, LocEnd;
4290 bool isBrackets; // true if [expr], false if .ident
4291 union {
4292 IdentifierInfo *IdentInfo;
4293 Expr *E;
4294 } U;
4295 };
4296
4297 /// __builtin_offsetof(type, a.b[123][456].c)
4298 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4299 TypeSourceInfo *TInfo,
4300 ArrayRef<OffsetOfComponent> Components,
4301 SourceLocation RParenLoc);
4302 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4303 SourceLocation BuiltinLoc,
4304 SourceLocation TypeLoc,
4305 ParsedType ParsedArgTy,
4306 ArrayRef<OffsetOfComponent> Components,
4307 SourceLocation RParenLoc);
4308
4309 // __builtin_choose_expr(constExpr, expr1, expr2)
4310 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4311 Expr *CondExpr, Expr *LHSExpr,
4312 Expr *RHSExpr, SourceLocation RPLoc);
4313
4314 // __builtin_va_arg(expr, type)
4315 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4316 SourceLocation RPLoc);
4317 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4318 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4319
4320 // __null
4321 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4322
4323 bool CheckCaseExpression(Expr *E);
4324
4325 /// \brief Describes the result of an "if-exists" condition check.
4326 enum IfExistsResult {
4327 /// \brief The symbol exists.
4328 IER_Exists,
4329
4330 /// \brief The symbol does not exist.
4331 IER_DoesNotExist,
4332
4333 /// \brief The name is a dependent name, so the results will differ
4334 /// from one instantiation to the next.
4335 IER_Dependent,
4336
4337 /// \brief An error occurred.
4338 IER_Error
4339 };
4340
4341 IfExistsResult
4342 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4343 const DeclarationNameInfo &TargetNameInfo);
4344
4345 IfExistsResult
4346 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4347 bool IsIfExists, CXXScopeSpec &SS,
4348 UnqualifiedId &Name);
4349
4350 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4351 bool IsIfExists,
4352 NestedNameSpecifierLoc QualifierLoc,
4353 DeclarationNameInfo NameInfo,
4354 Stmt *Nested);
4355 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4356 bool IsIfExists,
4357 CXXScopeSpec &SS, UnqualifiedId &Name,
4358 Stmt *Nested);
4359
4360 //===------------------------- "Block" Extension ------------------------===//
4361
4362 /// ActOnBlockStart - This callback is invoked when a block literal is
4363 /// started.
4364 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4365
4366 /// ActOnBlockArguments - This callback allows processing of block arguments.
4367 /// If there are no arguments, this is still invoked.
4368 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4369 Scope *CurScope);
4370
4371 /// ActOnBlockError - If there is an error parsing a block, this callback
4372 /// is invoked to pop the information about the block from the action impl.
4373 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4374
4375 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4376 /// literal was successfully completed. ^(int x){...}
4377 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4378 Scope *CurScope);
4379
4380 //===---------------------------- Clang Extensions ----------------------===//
4381
4382 /// __builtin_convertvector(...)
4383 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4384 SourceLocation BuiltinLoc,
4385 SourceLocation RParenLoc);
4386
4387 //===---------------------------- OpenCL Features -----------------------===//
4388
4389 /// __builtin_astype(...)
4390 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4391 SourceLocation BuiltinLoc,
4392 SourceLocation RParenLoc);
4393
4394 //===---------------------------- C++ Features --------------------------===//
4395
4396 // Act on C++ namespaces
4397 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4398 SourceLocation NamespaceLoc,
4399 SourceLocation IdentLoc,
4400 IdentifierInfo *Ident,
4401 SourceLocation LBrace,
4402 AttributeList *AttrList,
4403 UsingDirectiveDecl * &UsingDecl);
4404 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4405
4406 NamespaceDecl *getStdNamespace() const;
4407 NamespaceDecl *getOrCreateStdNamespace();
4408
4409 NamespaceDecl *lookupStdExperimentalNamespace();
4410
4411 CXXRecordDecl *getStdBadAlloc() const;
4412 EnumDecl *getStdAlignValT() const;
4413
4414 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4415 /// it is and Element is not NULL, assigns the element type to Element.
4416 bool isStdInitializerList(QualType Ty, QualType *Element);
4417
4418 /// \brief Looks for the std::initializer_list template and instantiates it
4419 /// with Element, or emits an error if it's not found.
4420 ///
4421 /// \returns The instantiated template, or null on error.
4422 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4423
4424 /// \brief Determine whether Ctor is an initializer-list constructor, as
4425 /// defined in [dcl.init.list]p2.
4426 bool isInitListConstructor(const FunctionDecl *Ctor);
4427
4428 Decl *ActOnUsingDirective(Scope *CurScope,
4429 SourceLocation UsingLoc,
4430 SourceLocation NamespcLoc,
4431 CXXScopeSpec &SS,
4432 SourceLocation IdentLoc,
4433 IdentifierInfo *NamespcName,
4434 AttributeList *AttrList);
4435
4436 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4437
4438 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4439 SourceLocation NamespaceLoc,
4440 SourceLocation AliasLoc,
4441 IdentifierInfo *Alias,
4442 CXXScopeSpec &SS,
4443 SourceLocation IdentLoc,
4444 IdentifierInfo *Ident);
4445
4446 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4447 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4448 const LookupResult &PreviousDecls,
4449 UsingShadowDecl *&PrevShadow);
4450 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4451 NamedDecl *Target,
4452 UsingShadowDecl *PrevDecl);
4453
4454 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4455 bool HasTypenameKeyword,
4456 const CXXScopeSpec &SS,
4457 SourceLocation NameLoc,
4458 const LookupResult &Previous);
4459 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4460 bool HasTypename,
4461 const CXXScopeSpec &SS,
4462 const DeclarationNameInfo &NameInfo,
4463 SourceLocation NameLoc);
4464
4465 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4466 SourceLocation UsingLoc,
4467 bool HasTypenameKeyword,
4468 SourceLocation TypenameLoc,
4469 CXXScopeSpec &SS,
4470 DeclarationNameInfo NameInfo,
4471 SourceLocation EllipsisLoc,
4472 AttributeList *AttrList,
4473 bool IsInstantiation);
4474 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4475 ArrayRef<NamedDecl *> Expansions);
4476
4477 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4478
4479 /// Given a derived-class using shadow declaration for a constructor and the
4480 /// correspnding base class constructor, find or create the implicit
4481 /// synthesized derived class constructor to use for this initialization.
4482 CXXConstructorDecl *
4483 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4484 ConstructorUsingShadowDecl *DerivedShadow);
4485
4486 Decl *ActOnUsingDeclaration(Scope *CurScope,
4487 AccessSpecifier AS,
4488 SourceLocation UsingLoc,
4489 SourceLocation TypenameLoc,
4490 CXXScopeSpec &SS,
4491 UnqualifiedId &Name,
4492 SourceLocation EllipsisLoc,
4493 AttributeList *AttrList);
4494 Decl *ActOnAliasDeclaration(Scope *CurScope,
4495 AccessSpecifier AS,
4496 MultiTemplateParamsArg TemplateParams,
4497 SourceLocation UsingLoc,
4498 UnqualifiedId &Name,
4499 AttributeList *AttrList,
4500 TypeResult Type,
4501 Decl *DeclFromDeclSpec);
4502
4503 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4504 /// including handling of its default argument expressions.
4505 ///
4506 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4507 ExprResult
4508 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4509 NamedDecl *FoundDecl,
4510 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4511 bool HadMultipleCandidates, bool IsListInitialization,
4512 bool IsStdInitListInitialization,
4513 bool RequiresZeroInit, unsigned ConstructKind,
4514 SourceRange ParenRange);
4515
4516 /// Build a CXXConstructExpr whose constructor has already been resolved if
4517 /// it denotes an inherited constructor.
4518 ExprResult
4519 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4520 CXXConstructorDecl *Constructor, bool Elidable,
4521 MultiExprArg Exprs,
4522 bool HadMultipleCandidates, bool IsListInitialization,
4523 bool IsStdInitListInitialization,
4524 bool RequiresZeroInit, unsigned ConstructKind,
4525 SourceRange ParenRange);
4526
4527 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4528 // the constructor can be elidable?
4529 ExprResult
4530 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4531 NamedDecl *FoundDecl,
4532 CXXConstructorDecl *Constructor, bool Elidable,
4533 MultiExprArg Exprs, bool HadMultipleCandidates,
4534 bool IsListInitialization,
4535 bool IsStdInitListInitialization, bool RequiresZeroInit,
4536 unsigned ConstructKind, SourceRange ParenRange);
4537
4538 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4539
4540
4541 /// Instantiate or parse a C++ default argument expression as necessary.
4542 /// Return true on error.
4543 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4544 ParmVarDecl *Param);
4545
4546 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4547 /// the default expr if needed.
4548 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4549 FunctionDecl *FD,
4550 ParmVarDecl *Param);
4551
4552 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4553 /// constructed variable.
4554 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4555
4556 /// \brief Helper class that collects exception specifications for
4557 /// implicitly-declared special member functions.
4558 class ImplicitExceptionSpecification {
4559 // Pointer to allow copying
4560 Sema *Self;
4561 // We order exception specifications thus:
4562 // noexcept is the most restrictive, but is only used in C++11.
4563 // throw() comes next.
4564 // Then a throw(collected exceptions)
4565 // Finally no specification, which is expressed as noexcept(false).
4566 // throw(...) is used instead if any called function uses it.
4567 ExceptionSpecificationType ComputedEST;
4568 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4569 SmallVector<QualType, 4> Exceptions;
4570
4571 void ClearExceptions() {
4572 ExceptionsSeen.clear();
4573 Exceptions.clear();
4574 }
4575
4576 public:
4577 explicit ImplicitExceptionSpecification(Sema &Self)
4578 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4579 if (!Self.getLangOpts().CPlusPlus11)
4580 ComputedEST = EST_DynamicNone;
4581 }
4582
4583 /// \brief Get the computed exception specification type.
4584 ExceptionSpecificationType getExceptionSpecType() const {
4585 assert(ComputedEST != EST_ComputedNoexcept &&((ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 4586, __PRETTY_FUNCTION__))
4586 "noexcept(expr) should not be a possible result")((ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/include/clang/Sema/Sema.h"
, 4586, __PRETTY_FUNCTION__))
;
4587 return ComputedEST;
4588 }
4589
4590 /// \brief The number of exceptions in the exception specification.
4591 unsigned size() const { return Exceptions.size(); }
4592
4593 /// \brief The set of exceptions in the exception specification.
4594 const QualType *data() const { return Exceptions.data(); }
4595
4596 /// \brief Integrate another called method into the collected data.
4597 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4598
4599 /// \brief Integrate an invoked expression into the collected data.
4600 void CalledExpr(Expr *E);
4601
4602 /// \brief Overwrite an EPI's exception specification with this
4603 /// computed exception specification.
4604 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4605 FunctionProtoType::ExceptionSpecInfo ESI;
4606 ESI.Type = getExceptionSpecType();
4607 if (ESI.Type == EST_Dynamic) {
4608 ESI.Exceptions = Exceptions;
4609 } else if (ESI.Type == EST_None) {
4610 /// C++11 [except.spec]p14:
4611 /// The exception-specification is noexcept(false) if the set of
4612 /// potential exceptions of the special member function contains "any"
4613 ESI.Type = EST_ComputedNoexcept;
4614 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4615 tok::kw_false).get();
4616 }
4617 return ESI;
4618 }
4619 };
4620
4621 /// \brief Determine what sort of exception specification a defaulted
4622 /// copy constructor of a class will have.
4623 ImplicitExceptionSpecification
4624 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4625 CXXMethodDecl *MD);
4626
4627 /// \brief Determine what sort of exception specification a defaulted
4628 /// default constructor of a class will have, and whether the parameter
4629 /// will be const.
4630 ImplicitExceptionSpecification
4631 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4632
4633 /// \brief Determine what sort of exception specification a defautled
4634 /// copy assignment operator of a class will have, and whether the
4635 /// parameter will be const.
4636 ImplicitExceptionSpecification
4637 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4638
4639 /// \brief Determine what sort of exception specification a defaulted move
4640 /// constructor of a class will have.
4641 ImplicitExceptionSpecification
4642 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4643
4644 /// \brief Determine what sort of exception specification a defaulted move
4645 /// assignment operator of a class will have.
4646 ImplicitExceptionSpecification
4647 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4648
4649 /// \brief Determine what sort of exception specification a defaulted
4650 /// destructor of a class will have.
4651 ImplicitExceptionSpecification
4652 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4653
4654 /// \brief Determine what sort of exception specification an inheriting
4655 /// constructor of a class will have.
4656 ImplicitExceptionSpecification
4657 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4658 CXXConstructorDecl *CD);
4659
4660 /// \brief Evaluate the implicit exception specification for a defaulted
4661 /// special member function.
4662 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4663
4664 /// \brief Check the given exception-specification and update the
4665 /// exception specification information with the results.
4666 void checkExceptionSpecification(bool IsTopLevel,
4667 ExceptionSpecificationType EST,
4668 ArrayRef<ParsedType> DynamicExceptions,
4669 ArrayRef<SourceRange> DynamicExceptionRanges,
4670 Expr *NoexceptExpr,
4671 SmallVectorImpl<QualType> &Exceptions,
4672 FunctionProtoType::ExceptionSpecInfo &ESI);
4673
4674 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4675 /// parse an exception specification to work around a libstdc++ bug.
4676 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4677
4678 /// \brief Add an exception-specification to the given member function
4679 /// (or member function template). The exception-specification was parsed
4680 /// after the method itself was declared.
4681 void actOnDelayedExceptionSpecification(Decl *Method,
4682 ExceptionSpecificationType EST,
4683 SourceRange SpecificationRange,
4684 ArrayRef<ParsedType> DynamicExceptions,
4685 ArrayRef<SourceRange> DynamicExceptionRanges,
4686 Expr *NoexceptExpr);
4687
4688 class InheritedConstructorInfo;
4689
4690 /// \brief Determine if a special member function should have a deleted
4691 /// definition when it is defaulted.
4692 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4693 InheritedConstructorInfo *ICI = nullptr,
4694 bool Diagnose = false);
4695
4696 /// \brief Declare the implicit default constructor for the given class.
4697 ///
4698 /// \param ClassDecl The class declaration into which the implicit
4699 /// default constructor will be added.
4700 ///
4701 /// \returns The implicitly-declared default constructor.
4702 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4703 CXXRecordDecl *ClassDecl);
4704
4705 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4706 /// defining this constructor as the default constructor.
4707 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4708 CXXConstructorDecl *Constructor);
4709
4710 /// \brief Declare the implicit destructor for the given class.
4711 ///
4712 /// \param ClassDecl The class declaration into which the implicit
4713 /// destructor will be added.
4714 ///
4715 /// \returns The implicitly-declared destructor.
4716 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4717
4718 /// DefineImplicitDestructor - Checks for feasibility of
4719 /// defining this destructor as the default destructor.
4720 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4721 CXXDestructorDecl *Destructor);
4722
4723 /// \brief Build an exception spec for destructors that don't have one.
4724 ///
4725 /// C++11 says that user-defined destructors with no exception spec get one
4726 /// that looks as if the destructor was implicitly declared.
4727 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4728 CXXDestructorDecl *Destructor);
4729
4730 /// \brief Define the specified inheriting constructor.
4731 void DefineInheritingConstructor(SourceLocation UseLoc,
4732 CXXConstructorDecl *Constructor);
4733
4734 /// \brief Declare the implicit copy constructor for the given class.
4735 ///
4736 /// \param ClassDecl The class declaration into which the implicit
4737 /// copy constructor will be added.
4738 ///
4739 /// \returns The implicitly-declared copy constructor.
4740 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4741
4742 /// DefineImplicitCopyConstructor - Checks for feasibility of
4743 /// defining this constructor as the copy constructor.
4744 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4745 CXXConstructorDecl *Constructor);
4746
4747 /// \brief Declare the implicit move constructor for the given class.
4748 ///
4749 /// \param ClassDecl The Class declaration into which the implicit
4750 /// move constructor will be added.
4751 ///
4752 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4753 /// declared.
4754 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4755
4756 /// DefineImplicitMoveConstructor - Checks for feasibility of
4757 /// defining this constructor as the move constructor.
4758 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4759 CXXConstructorDecl *Constructor);
4760
4761 /// \brief Declare the implicit copy assignment operator for the given class.
4762 ///
4763 /// \param ClassDecl The class declaration into which the implicit
4764 /// copy assignment operator will be added.
4765 ///
4766 /// \returns The implicitly-declared copy assignment operator.
4767 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4768
4769 /// \brief Defines an implicitly-declared copy assignment operator.
4770 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4771 CXXMethodDecl *MethodDecl);
4772
4773 /// \brief Declare the implicit move assignment operator for the given class.
4774 ///
4775 /// \param ClassDecl The Class declaration into which the implicit
4776 /// move assignment operator will be added.
4777 ///
4778 /// \returns The implicitly-declared move assignment operator, or NULL if it
4779 /// wasn't declared.
4780 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4781
4782 /// \brief Defines an implicitly-declared move assignment operator.
4783 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4784 CXXMethodDecl *MethodDecl);
4785
4786 /// \brief Force the declaration of any implicitly-declared members of this
4787 /// class.
4788 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4789
4790 /// \brief Check a completed declaration of an implicit special member.
4791 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4792
4793 /// \brief Determine whether the given function is an implicitly-deleted
4794 /// special member function.
4795 bool isImplicitlyDeleted(FunctionDecl *FD);
4796
4797 /// \brief Check whether 'this' shows up in the type of a static member
4798 /// function after the (naturally empty) cv-qualifier-seq would be.
4799 ///
4800 /// \returns true if an error occurred.
4801 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4802
4803 /// \brief Whether this' shows up in the exception specification of a static
4804 /// member function.
4805 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4806
4807 /// \brief Check whether 'this' shows up in the attributes of the given
4808 /// static member function.
4809 ///
4810 /// \returns true if an error occurred.
4811 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4812
4813 /// MaybeBindToTemporary - If the passed in expression has a record type with
4814 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4815 /// it simply returns the passed in expression.
4816 ExprResult MaybeBindToTemporary(Expr *E);
4817
4818 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4819 MultiExprArg ArgsPtr,
4820 SourceLocation Loc,
4821 SmallVectorImpl<Expr*> &ConvertedArgs,
4822 bool AllowExplicit = false,
4823 bool IsListInitialization = false);
4824
4825 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4826 SourceLocation NameLoc,
4827 IdentifierInfo &Name);
4828
4829 ParsedType getDestructorName(SourceLocation TildeLoc,
4830 IdentifierInfo &II, SourceLocation NameLoc,
4831 Scope *S, CXXScopeSpec &SS,
4832 ParsedType ObjectType,
4833 bool EnteringContext);
4834
4835 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4836 ParsedType ObjectType);
4837
4838 // Checks that reinterpret casts don't have undefined behavior.
4839 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4840 bool IsDereference, SourceRange Range);
4841
4842 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4843 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4844 tok::TokenKind Kind,
4845 SourceLocation LAngleBracketLoc,
4846 Declarator &D,
4847 SourceLocation RAngleBracketLoc,
4848 SourceLocation LParenLoc,
4849 Expr *E,
4850 SourceLocation RParenLoc);
4851
4852 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4853 tok::TokenKind Kind,
4854 TypeSourceInfo *Ty,
4855 Expr *E,
4856 SourceRange AngleBrackets,
4857 SourceRange Parens);
4858
4859 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4860 SourceLocation TypeidLoc,
4861 TypeSourceInfo *Operand,
4862 SourceLocation RParenLoc);
4863 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4864 SourceLocation TypeidLoc,
4865 Expr *Operand,
4866 SourceLocation RParenLoc);
4867
4868 /// ActOnCXXTypeid - Parse typeid( something ).
4869 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4870 SourceLocation LParenLoc, bool isType,
4871 void *TyOrExpr,
4872 SourceLocation RParenLoc);
4873
4874 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4875 SourceLocation TypeidLoc,
4876 TypeSourceInfo *Operand,
4877 SourceLocation RParenLoc);
4878 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4879 SourceLocation TypeidLoc,
4880 Expr *Operand,
4881 SourceLocation RParenLoc);
4882
4883 /// ActOnCXXUuidof - Parse __uuidof( something ).
4884 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4885 SourceLocation LParenLoc, bool isType,
4886 void *TyOrExpr,
4887 SourceLocation RParenLoc);
4888
4889 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4890 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4891 tok::TokenKind Operator,
4892 SourceLocation EllipsisLoc, Expr *RHS,
4893 SourceLocation RParenLoc);
4894 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4895 BinaryOperatorKind Operator,
4896 SourceLocation EllipsisLoc, Expr *RHS,
4897 SourceLocation RParenLoc);
4898 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4899 BinaryOperatorKind Operator);
4900
4901 //// ActOnCXXThis - Parse 'this' pointer.
4902 ExprResult ActOnCXXThis(SourceLocation loc);
4903
4904 /// \brief Try to retrieve the type of the 'this' pointer.
4905 ///
4906 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4907 QualType getCurrentThisType();
4908
4909 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4910 /// current context not being a non-static member function. In such cases,
4911 /// this provides the type used for 'this'.
4912 QualType CXXThisTypeOverride;
4913
4914 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4915 /// to be used, with the given qualifiers on the current class type.
4916 class CXXThisScopeRAII {
4917 Sema &S;
4918 QualType OldCXXThisTypeOverride;
4919 bool Enabled;
4920
4921 public:
4922 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4923 /// using the given declaration (which is either a class template or a
4924 /// class) along with the given qualifiers.
4925 /// along with the qualifiers placed on '*this'.
4926 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4927 bool Enabled = true);
4928
4929 ~CXXThisScopeRAII();
4930 };
4931
4932 /// \brief Make sure the value of 'this' is actually available in the current
4933 /// context, if it is a potentially evaluated context.
4934 ///
4935 /// \param Loc The location at which the capture of 'this' occurs.
4936 ///
4937 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4938 /// capture list.
4939 ///
4940 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4941 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4942 /// This is useful when enclosing lambdas must speculatively capture
4943 /// 'this' that may or may not be used in certain specializations of
4944 /// a nested generic lambda (depending on whether the name resolves to
4945 /// a non-static member function or a static function).
4946 /// \return returns 'true' if failed, 'false' if success.
4947 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4948 bool BuildAndDiagnose = true,
4949 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4950 bool ByCopy = false);
4951
4952 /// \brief Determine whether the given type is the type of *this that is used
4953 /// outside of the body of a member function for a type that is currently
4954 /// being defined.
4955 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4956
4957 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4958 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4959
4960
4961 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4962 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4963
4964 ExprResult
4965 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4966 SourceLocation AtLoc, SourceLocation RParen);
4967
4968 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4969 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4970
4971 //// ActOnCXXThrow - Parse throw expressions.
4972 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4973 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4974 bool IsThrownVarInScope);
4975 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4976
4977 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4978 /// Can be interpreted either as function-style casting ("int(x)")
4979 /// or class type construction ("ClassType(x,y,z)")
4980 /// or creation of a value-initialized type ("int()").
4981 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4982 SourceLocation LParenLoc,
4983 MultiExprArg Exprs,
4984 SourceLocation RParenLoc);
4985
4986 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4987 SourceLocation LParenLoc,
4988 MultiExprArg Exprs,
4989 SourceLocation RParenLoc);
4990
4991 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4992 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4993 SourceLocation PlacementLParen,
4994 MultiExprArg PlacementArgs,
4995 SourceLocation PlacementRParen,
4996 SourceRange TypeIdParens, Declarator &D,
4997 Expr *Initializer);
4998 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4999 SourceLocation PlacementLParen,
5000 MultiExprArg PlacementArgs,
5001 SourceLocation PlacementRParen,
5002 SourceRange TypeIdParens,
5003 QualType AllocType,
5004 TypeSourceInfo *AllocTypeInfo,
5005 Expr *ArraySize,
5006 SourceRange DirectInitRange,
5007 Expr *Initializer);
5008
5009 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5010 SourceRange R);
5011 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5012 bool UseGlobal, QualType AllocType, bool IsArray,
5013 bool &PassAlignment, MultiExprArg PlaceArgs,
5014 FunctionDecl *&OperatorNew,
5015 FunctionDecl *&OperatorDelete);
5016 void DeclareGlobalNewDelete();
5017 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5018 ArrayRef<QualType> Params);
5019
5020 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5021 DeclarationName Name, FunctionDecl* &Operator,
5022 bool Diagnose = true);
5023 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5024 bool CanProvideSize,
5025 bool Overaligned,
5026 DeclarationName Name);
5027 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5028 CXXRecordDecl *RD);
5029
5030 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5031 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5032 bool UseGlobal, bool ArrayForm,
5033 Expr *Operand);
5034 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5035 bool IsDelete, bool CallCanBeVirtual,
5036 bool WarnOnNonAbstractTypes,
5037 SourceLocation DtorLoc);
5038
5039 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5040 Expr *Operand, SourceLocation RParen);
5041 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5042 SourceLocation RParen);
5043
5044 /// \brief Parsed one of the type trait support pseudo-functions.
5045 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5046 ArrayRef<ParsedType> Args,
5047 SourceLocation RParenLoc);
5048 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5049 ArrayRef<TypeSourceInfo *> Args,
5050 SourceLocation RParenLoc);
5051
5052 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5053 /// pseudo-functions.
5054 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5055 SourceLocation KWLoc,
5056 ParsedType LhsTy,
5057 Expr *DimExpr,
5058 SourceLocation RParen);
5059
5060 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5061 SourceLocation KWLoc,
5062 TypeSourceInfo *TSInfo,
5063 Expr *DimExpr,
5064 SourceLocation RParen);
5065
5066 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5067 /// pseudo-functions.
5068 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5069 SourceLocation KWLoc,
5070 Expr *Queried,
5071 SourceLocation RParen);
5072
5073 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5074 SourceLocation KWLoc,
5075 Expr *Queried,
5076 SourceLocation RParen);
5077
5078 ExprResult ActOnStartCXXMemberReference(Scope *S,
5079 Expr *Base,
5080 SourceLocation OpLoc,
5081 tok::TokenKind OpKind,
5082 ParsedType &ObjectType,
5083 bool &MayBePseudoDestructor);
5084
5085 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5086 SourceLocation OpLoc,
5087 tok::TokenKind OpKind,
5088 const CXXScopeSpec &SS,
5089 TypeSourceInfo *ScopeType,
5090 SourceLocation CCLoc,
5091 SourceLocation TildeLoc,
5092 PseudoDestructorTypeStorage DestroyedType);
5093
5094 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5095 SourceLocation OpLoc,
5096 tok::TokenKind OpKind,
5097 CXXScopeSpec &SS,
5098 UnqualifiedId &FirstTypeName,
5099 SourceLocation CCLoc,
5100 SourceLocation TildeLoc,
5101 UnqualifiedId &SecondTypeName);
5102
5103 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5104 SourceLocation OpLoc,
5105 tok::TokenKind OpKind,
5106 SourceLocation TildeLoc,
5107 const DeclSpec& DS);
5108
5109 /// MaybeCreateExprWithCleanups - If the current full-expression
5110 /// requires any cleanups, surround it with a ExprWithCleanups node.
5111 /// Otherwise, just returns the passed-in expression.
5112 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5113 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5114 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5115
5116 MaterializeTemporaryExpr *
5117 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5118 bool BoundToLvalueReference);
5119
5120 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5121 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5122 : SourceLocation());
5123 }
5124 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5125 bool DiscardedValue = false,
5126 bool IsConstexpr = false,
5127 bool IsLambdaInitCaptureInitializer = false);
5128 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5129
5130 // Marks SS invalid if it represents an incomplete type.
5131 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5132
5133 DeclContext *computeDeclContext(QualType T);
5134 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5135 bool EnteringContext = false);
5136 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5137 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5138
5139 /// \brief The parser has parsed a global nested-name-specifier '::'.
5140 ///
5141 /// \param CCLoc The location of the '::'.
5142 ///
5143 /// \param SS The nested-name-specifier, which will be updated in-place
5144 /// to reflect the parsed nested-name-specifier.
5145 ///
5146 /// \returns true if an error occurred, false otherwise.
5147 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5148
5149 /// \brief The parser has parsed a '__super' nested-name-specifier.
5150 ///
5151 /// \param SuperLoc The location of the '__super' keyword.
5152 ///
5153 /// \param ColonColonLoc The location of the '::'.
5154 ///
5155 /// \param SS The nested-name-specifier, which will be updated in-place
5156 /// to reflect the parsed nested-name-specifier.
5157 ///
5158 /// \returns true if an error occurred, false otherwise.
5159 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5160 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5161
5162 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5163 bool *CanCorrect = nullptr);
5164 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5165
5166 /// \brief Keeps information about an identifier in a nested-name-spec.
5167 ///
5168 struct NestedNameSpecInfo {
5169 /// \brief The type of the object, if we're parsing nested-name-specifier in
5170 /// a member access expression.
5171 ParsedType ObjectType;
5172
5173 /// \brief The identifier preceding the '::'.
5174 IdentifierInfo *Identifier;
5175
5176 /// \brief The location of the identifier.
5177 SourceLocation IdentifierLoc;
5178
5179 /// \brief The location of the '::'.
5180 SourceLocation CCLoc;
5181
5182 /// \brief Creates info object for the most typical case.
5183 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5184 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5185 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5186 CCLoc(ColonColonLoc) {
5187 }
5188
5189 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5190 SourceLocation ColonColonLoc, QualType ObjectType)
5191 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5192 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5193 }
5194 };
5195
5196 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5197 NestedNameSpecInfo &IdInfo);
5198
5199 bool BuildCXXNestedNameSpecifier(Scope *S,
5200 NestedNameSpecInfo &IdInfo,
5201 bool EnteringContext,
5202 CXXScopeSpec &SS,
5203 NamedDecl *ScopeLookupResult,
5204 bool ErrorRecoveryLookup,
5205 bool *IsCorrectedToColon = nullptr,
5206 bool OnlyNamespace = false);
5207
5208 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5209 ///
5210 /// \param S The scope in which this nested-name-specifier occurs.
5211 ///
5212 /// \param IdInfo Parser information about an identifier in the
5213 /// nested-name-spec.
5214 ///
5215 /// \param EnteringContext Whether we're entering the context nominated by
5216 /// this nested-name-specifier.
5217 ///
5218 /// \param SS The nested-name-specifier, which is both an input
5219 /// parameter (the nested-name-specifier before this type) and an
5220 /// output parameter (containing the full nested-name-specifier,
5221 /// including this new type).
5222 ///
5223 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5224 /// error recovery. In this case do not emit error message.
5225 ///
5226 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5227 /// are allowed. The bool value pointed by this parameter is set to 'true'
5228 /// if the identifier is treated as if it was followed by ':', not '::'.
5229 ///
5230 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5231 ///
5232 /// \returns true if an error occurred, false otherwise.
5233 bool ActOnCXXNestedNameSpecifier(Scope *S,
5234 NestedNameSpecInfo &IdInfo,
5235 bool EnteringContext,
5236 CXXScopeSpec &SS,
5237 bool ErrorRecoveryLookup = false,
5238 bool *IsCorrectedToColon = nullptr,
5239 bool OnlyNamespace = false);
5240
5241 ExprResult ActOnDecltypeExpression(Expr *E);
5242
5243 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5244 const DeclSpec &DS,
5245 SourceLocation ColonColonLoc);
5246
5247 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5248 NestedNameSpecInfo &IdInfo,
5249 bool EnteringContext);
5250
5251 /// \brief The parser has parsed a nested-name-specifier
5252 /// 'template[opt] template-name < template-args >::'.
5253 ///
5254 /// \param S The scope in which this nested-name-specifier occurs.
5255 ///
5256 /// \param SS The nested-name-specifier, which is both an input
5257 /// parameter (the nested-name-specifier before this type) and an
5258 /// output parameter (containing the full nested-name-specifier,
5259 /// including this new type).
5260 ///
5261 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5262 /// \param TemplateName the template name.
5263 /// \param TemplateNameLoc The location of the template name.
5264 /// \param LAngleLoc The location of the opening angle bracket ('<').
5265 /// \param TemplateArgs The template arguments.
5266 /// \param RAngleLoc The location of the closing angle bracket ('>').
5267 /// \param CCLoc The location of the '::'.
5268 ///
5269 /// \param EnteringContext Whether we're entering the context of the
5270 /// nested-name-specifier.
5271 ///
5272 ///
5273 /// \returns true if an error occurred, false otherwise.
5274 bool ActOnCXXNestedNameSpecifier(Scope *S,
5275 CXXScopeSpec &SS,
5276 SourceLocation TemplateKWLoc,
5277 TemplateTy TemplateName,
5278 SourceLocation TemplateNameLoc,
5279 SourceLocation LAngleLoc,
5280 ASTTemplateArgsPtr TemplateArgs,
5281 SourceLocation RAngleLoc,
5282 SourceLocation CCLoc,
5283 bool EnteringContext);
5284
5285 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5286 /// that the parser can use later to reconstruct the given
5287 /// nested-name-specifier.
5288 ///
5289 /// \param SS A nested-name-specifier.
5290 ///
5291 /// \returns A pointer containing all of the information in the
5292 /// nested-name-specifier \p SS.
5293 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5294
5295 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5296 /// the nested-name-specifier structure.
5297 ///
5298 /// \param Annotation The annotation pointer, produced by
5299 /// \c SaveNestedNameSpecifierAnnotation().
5300 ///
5301 /// \param AnnotationRange The source range corresponding to the annotation.
5302 ///
5303 /// \param SS The nested-name-specifier that will be updated with the contents
5304 /// of the annotation pointer.
5305 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5306 SourceRange AnnotationRange,
5307 CXXScopeSpec &SS);
5308
5309 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5310
5311 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5312 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5313 /// After this method is called, according to [C++ 3.4.3p3], names should be
5314 /// looked up in the declarator-id's scope, until the declarator is parsed and
5315 /// ActOnCXXExitDeclaratorScope is called.
5316 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5317 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5318
5319 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5320 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5321 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5322 /// Used to indicate that names should revert to being looked up in the
5323 /// defining scope.
5324 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5325
5326 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5327 /// initializer for the declaration 'Dcl'.
5328 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5329 /// static data member of class X, names should be looked up in the scope of
5330 /// class X.
5331 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5332
5333 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5334 /// initializer for the declaration 'Dcl'.
5335 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5336
5337 /// \brief Create a new lambda closure type.
5338 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5339 TypeSourceInfo *Info,
5340 bool KnownDependent,
5341 LambdaCaptureDefault CaptureDefault);
5342
5343 /// \brief Start the definition of a lambda expression.
5344 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5345 SourceRange IntroducerRange,
5346 TypeSourceInfo *MethodType,
5347 SourceLocation EndLoc,
5348 ArrayRef<ParmVarDecl *> Params,
5349 bool IsConstexprSpecified);
5350
5351 /// \brief Endow the lambda scope info with the relevant properties.
5352 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5353 CXXMethodDecl *CallOperator,
5354 SourceRange IntroducerRange,
5355 LambdaCaptureDefault CaptureDefault,
5356 SourceLocation CaptureDefaultLoc,
5357 bool ExplicitParams,
5358 bool ExplicitResultType,
5359 bool Mutable);
5360
5361 /// \brief Perform initialization analysis of the init-capture and perform
5362 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5363 /// not being used to initialize a reference.
5364 ParsedType actOnLambdaInitCaptureInitialization(
5365 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5366 LambdaCaptureInitKind InitKind, Expr *&Init) {
5367 return ParsedType::make(buildLambdaInitCaptureInitialization(
5368 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5369 }
5370 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5371 IdentifierInfo *Id,
5372 bool DirectInit, Expr *&Init);
5373
5374 /// \brief Create a dummy variable within the declcontext of the lambda's
5375 /// call operator, for name lookup purposes for a lambda init capture.
5376 ///
5377 /// CodeGen handles emission of lambda captures, ignoring these dummy
5378 /// variables appropriately.
5379 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5380 QualType InitCaptureType,
5381 IdentifierInfo *Id,
5382 unsigned InitStyle, Expr *Init);
5383
5384 /// \brief Build the implicit field for an init-capture.
5385 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5386
5387 /// \brief Note that we have finished the explicit captures for the
5388 /// given lambda.
5389 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5390
5391 /// \brief Introduce the lambda parameters into scope.
5392 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5393
5394 /// \brief Deduce a block or lambda's return type based on the return
5395 /// statements present in the body.
5396 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5397
5398 /// ActOnStartOfLambdaDefinition - This is called just before we start
5399 /// parsing the body of a lambda; it analyzes the explicit captures and
5400 /// arguments, and sets up various data-structures for the body of the
5401 /// lambda.
5402 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5403 Declarator &ParamInfo, Scope *CurScope);
5404
5405 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5406 /// is invoked to pop the information about the lambda.
5407 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5408 bool IsInstantiation = false);
5409
5410 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5411 /// was successfully completed.
5412 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5413 Scope *CurScope);
5414
5415 /// \brief Does copying/destroying the captured variable have side effects?
5416 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5417
5418 /// \brief Diagnose if an explicit lambda capture is unused.
5419 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5420
5421 /// \brief Complete a lambda-expression having processed and attached the
5422 /// lambda body.
5423 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5424 sema::LambdaScopeInfo *LSI);
5425
5426 /// \brief Define the "body" of the conversion from a lambda object to a
5427 /// function pointer.
5428 ///
5429 /// This routine doesn't actually define a sensible body; rather, it fills
5430 /// in the initialization expression needed to copy the lambda object into
5431 /// the block, and IR generation actually generates the real body of the
5432 /// block pointer conversion.
5433 void DefineImplicitLambdaToFunctionPointerConversion(
5434 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5435
5436 /// \brief Define the "body" of the conversion from a lambda object to a
5437 /// block pointer.
5438 ///
5439 /// This routine doesn't actually define a sensible body; rather, it fills
5440 /// in the initialization expression needed to copy the lambda object into
5441 /// the block, and IR generation actually generates the real body of the
5442 /// block pointer conversion.
5443 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5444 CXXConversionDecl *Conv);
5445
5446 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5447 SourceLocation ConvLocation,
5448 CXXConversionDecl *Conv,
5449 Expr *Src);
5450
5451 // ParseObjCStringLiteral - Parse Objective-C string literals.
5452 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5453 ArrayRef<Expr *> Strings);
5454
5455 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5456
5457 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5458 /// numeric literal expression. Type of the expression will be "NSNumber *"
5459 /// or "id" if NSNumber is unavailable.
5460 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5461 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5462 bool Value);
5463 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5464
5465 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5466 /// '@' prefixed parenthesized expression. The type of the expression will
5467 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5468 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5469 /// "const char *" or C structure with attribute 'objc_boxable'.
5470 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5471
5472 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5473 Expr *IndexExpr,
5474 ObjCMethodDecl *getterMethod,
5475 ObjCMethodDecl *setterMethod);
5476
5477 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5478 MutableArrayRef<ObjCDictionaryElement> Elements);
5479
5480 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5481 TypeSourceInfo *EncodedTypeInfo,
5482 SourceLocation RParenLoc);
5483 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5484 CXXConversionDecl *Method,
5485 bool HadMultipleCandidates);
5486
5487 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5488 SourceLocation EncodeLoc,
5489 SourceLocation LParenLoc,
5490 ParsedType Ty,
5491 SourceLocation RParenLoc);
5492
5493 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5494 ExprResult ParseObjCSelectorExpression(Selector Sel,
5495 SourceLocation AtLoc,
5496 SourceLocation SelLoc,
5497 SourceLocation LParenLoc,
5498 SourceLocation RParenLoc,
5499 bool WarnMultipleSelectors);
5500
5501 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5502 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5503 SourceLocation AtLoc,
5504 SourceLocation ProtoLoc,
5505 SourceLocation LParenLoc,
5506 SourceLocation ProtoIdLoc,
5507 SourceLocation RParenLoc);
5508
5509 //===--------------------------------------------------------------------===//
5510 // C++ Declarations
5511 //
5512 Decl *ActOnStartLinkageSpecification(Scope *S,
5513 SourceLocation ExternLoc,
5514 Expr *LangStr,
5515 SourceLocation LBraceLoc);
5516 Decl *ActOnFinishLinkageSpecification(Scope *S,
5517 Decl *LinkageSpec,
5518 SourceLocation RBraceLoc);
5519
5520
5521 //===--------------------------------------------------------------------===//
5522 // C++ Classes
5523 //
5524 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5525 const CXXScopeSpec *SS = nullptr);
5526 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5527
5528 bool ActOnAccessSpecifier(AccessSpecifier Access,
5529 SourceLocation ASLoc,
5530 SourceLocation ColonLoc,
5531 AttributeList *Attrs = nullptr);
5532
5533 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5534 Declarator &D,
5535 MultiTemplateParamsArg TemplateParameterLists,
5536 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5537 InClassInitStyle InitStyle);
5538
5539 void ActOnStartCXXInClassMemberInitializer();
5540 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5541 SourceLocation EqualLoc,
5542 Expr *Init);
5543
5544 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5545 Scope *S,
5546 CXXScopeSpec &SS,
5547 IdentifierInfo *MemberOrBase,
5548 ParsedType TemplateTypeTy,
5549 const DeclSpec &DS,
5550 SourceLocation IdLoc,
5551 SourceLocation LParenLoc,
5552 ArrayRef<Expr *> Args,
5553 SourceLocation RParenLoc,
5554 SourceLocation EllipsisLoc);
5555
5556 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5557 Scope *S,
5558 CXXScopeSpec &SS,
5559 IdentifierInfo *MemberOrBase,
5560 ParsedType TemplateTypeTy,
5561 const DeclSpec &DS,
5562 SourceLocation IdLoc,
5563 Expr *InitList,
5564 SourceLocation EllipsisLoc);
5565
5566 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5567 Scope *S,
5568 CXXScopeSpec &SS,
5569 IdentifierInfo *MemberOrBase,
5570 ParsedType TemplateTypeTy,
5571 const DeclSpec &DS,
5572 SourceLocation IdLoc,
5573 Expr *Init,
5574 SourceLocation EllipsisLoc);
5575
5576 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5577 Expr *Init,
5578 SourceLocation IdLoc);
5579
5580 MemInitResult BuildBaseInitializer(QualType BaseType,
5581 TypeSourceInfo *BaseTInfo,
5582 Expr *Init,
5583 CXXRecordDecl *ClassDecl,
5584 SourceLocation EllipsisLoc);
5585
5586 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5587 Expr *Init,
5588 CXXRecordDecl *ClassDecl);
5589
5590 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5591 CXXCtorInitializer *Initializer);
5592
5593 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5594 ArrayRef<CXXCtorInitializer *> Initializers = None);
5595
5596 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5597
5598
5599 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5600 /// mark all the non-trivial destructors of its members and bases as
5601 /// referenced.
5602 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5603 CXXRecordDecl *Record);
5604
5605 /// \brief The list of classes whose vtables have been used within
5606 /// this translation unit, and the source locations at which the
5607 /// first use occurred.
5608 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5609
5610 /// \brief The list of vtables that are required but have not yet been
5611 /// materialized.
5612 SmallVector<VTableUse, 16> VTableUses;
5613
5614 /// \brief The set of classes whose vtables have been used within
5615 /// this translation unit, and a bit that will be true if the vtable is
5616 /// required to be emitted (otherwise, it should be emitted only if needed
5617 /// by code generation).
5618 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5619
5620 /// \brief Load any externally-stored vtable uses.
5621 void LoadExternalVTableUses();
5622
5623 /// \brief Note that the vtable for the given class was used at the
5624 /// given location.
5625 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5626 bool DefinitionRequired = false);
5627
5628 /// \brief Mark the exception specifications of all virtual member functions
5629 /// in the given class as needed.
5630 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5631 const CXXRecordDecl *RD);
5632
5633 /// MarkVirtualMembersReferenced - Will mark all members of the given
5634 /// CXXRecordDecl referenced.
5635 void MarkVirtualMembersReferenced(SourceLocation Loc,
5636 const CXXRecordDecl *RD);
5637
5638 /// \brief Define all of the vtables that have been used in this
5639 /// translation unit and reference any virtual members used by those
5640 /// vtables.
5641 ///
5642 /// \returns true if any work was done, false otherwise.
5643 bool DefineUsedVTables();
5644
5645 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5646
5647 void ActOnMemInitializers(Decl *ConstructorDecl,
5648 SourceLocation ColonLoc,
5649 ArrayRef<CXXCtorInitializer*> MemInits,
5650 bool AnyErrors);
5651
5652 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5653 /// ensure that referenceDLLExportedClassMethods is called some point later
5654 /// when all outer classes of Class are complete.
5655 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5656
5657 void referenceDLLExportedClassMethods();
5658
5659 void propagateDLLAttrToBaseClassTemplate(
5660 CXXRecordDecl *Class, Attr *ClassAttr,
5661 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5662 SourceLocation BaseLoc);
5663
5664 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5665 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5666 Decl *TagDecl,
5667 SourceLocation LBrac,
5668 SourceLocation RBrac,
5669 AttributeList *AttrList);
5670 void ActOnFinishCXXMemberDecls();
5671 void ActOnFinishCXXNonNestedClass(Decl *D);
5672
5673 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5674 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5675 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5676 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5677 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5678 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5679 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5680 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5681 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5682 CachedTokens &Toks);
5683 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5684 bool IsInsideALocalClassWithinATemplateFunction();
5685
5686 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5687 Expr *AssertExpr,
5688 Expr *AssertMessageExpr,
5689 SourceLocation RParenLoc);
5690 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5691 Expr *AssertExpr,
5692 StringLiteral *AssertMessageExpr,
5693 SourceLocation RParenLoc,
5694 bool Failed);
5695
5696 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5697 SourceLocation FriendLoc,
5698 TypeSourceInfo *TSInfo);
5699 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5700 MultiTemplateParamsArg TemplateParams);
5701 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5702 MultiTemplateParamsArg TemplateParams);
5703
5704 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5705 StorageClass& SC);
5706 void CheckConstructor(CXXConstructorDecl *Constructor);
5707 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5708 StorageClass& SC);
5709 bool CheckDestructor(CXXDestructorDecl *Destructor);
5710 void CheckConversionDeclarator(Declarator &D, QualType &R,
5711 StorageClass& SC);
5712 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5713 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5714 StorageClass &SC);
5715 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5716
5717 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5718 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5719 const FunctionProtoType *T);
5720 void CheckDelayedMemberExceptionSpecs();
5721
5722 //===--------------------------------------------------------------------===//
5723 // C++ Derived Classes
5724 //
5725
5726 /// ActOnBaseSpecifier - Parsed a base specifier
5727 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5728 SourceRange SpecifierRange,
5729 bool Virtual, AccessSpecifier Access,
5730 TypeSourceInfo *TInfo,
5731 SourceLocation EllipsisLoc);
5732
5733 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5734 SourceRange SpecifierRange,
5735 ParsedAttributes &Attrs,
5736 bool Virtual, AccessSpecifier Access,
5737 ParsedType basetype,
5738 SourceLocation BaseLoc,
5739 SourceLocation EllipsisLoc);
5740
5741 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5742 MutableArrayRef<CXXBaseSpecifier *> Bases);
5743 void ActOnBaseSpecifiers(Decl *ClassDecl,
5744 MutableArrayRef<CXXBaseSpecifier *> Bases);
5745
5746 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5747 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5748 CXXBasePaths &Paths);
5749
5750 // FIXME: I don't like this name.
5751 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5752
5753 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5754 SourceLocation Loc, SourceRange Range,
5755 CXXCastPath *BasePath = nullptr,
5756 bool IgnoreAccess = false);
5757 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5758 unsigned InaccessibleBaseID,
5759 unsigned AmbigiousBaseConvID,
5760 SourceLocation Loc, SourceRange Range,
5761 DeclarationName Name,
5762 CXXCastPath *BasePath,
5763 bool IgnoreAccess = false);
5764
5765 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5766
5767 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5768 const CXXMethodDecl *Old);
5769
5770 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5771 /// covariant, according to C++ [class.virtual]p5.
5772 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5773 const CXXMethodDecl *Old);
5774
5775 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5776 /// spec is a subset of base spec.
5777 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5778 const CXXMethodDecl *Old);
5779
5780 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5781
5782 /// CheckOverrideControl - Check C++11 override control semantics.
5783 void CheckOverrideControl(NamedDecl *D);
5784
5785 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5786 /// not used in the declaration of an overriding method.
5787 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5788
5789 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5790 /// overrides a virtual member function marked 'final', according to
5791 /// C++11 [class.virtual]p4.
5792 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5793 const CXXMethodDecl *Old);
5794
5795
5796 //===--------------------------------------------------------------------===//
5797 // C++ Access Control
5798 //
5799
5800 enum AccessResult {
5801 AR_accessible,
5802 AR_inaccessible,
5803 AR_dependent,
5804 AR_delayed
5805 };
5806
5807 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5808 NamedDecl *PrevMemberDecl,
5809 AccessSpecifier LexicalAS);
5810
5811 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5812 DeclAccessPair FoundDecl);
5813 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5814 DeclAccessPair FoundDecl);
5815 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5816 SourceRange PlacementRange,
5817 CXXRecordDecl *NamingClass,
5818 DeclAccessPair FoundDecl,
5819 bool Diagnose = true);
5820 AccessResult CheckConstructorAccess(SourceLocation Loc,
5821 CXXConstructorDecl *D,
5822 DeclAccessPair FoundDecl,
5823 const InitializedEntity &Entity,
5824 bool IsCopyBindingRefToTemp = false);
5825 AccessResult CheckConstructorAccess(SourceLocation Loc,
5826 CXXConstructorDecl *D,
5827 DeclAccessPair FoundDecl,
5828 const InitializedEntity &Entity,
5829 const PartialDiagnostic &PDiag);
5830 AccessResult CheckDestructorAccess(SourceLocation Loc,
5831 CXXDestructorDecl *Dtor,
5832 const PartialDiagnostic &PDiag,
5833 QualType objectType = QualType());
5834 AccessResult CheckFriendAccess(NamedDecl *D);
5835 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5836 CXXRecordDecl *NamingClass,
5837 DeclAccessPair Found);
5838 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5839 Expr *ObjectExpr,
5840 Expr *ArgExpr,
5841 DeclAccessPair FoundDecl);
5842 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5843 DeclAccessPair FoundDecl);
5844 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5845 QualType Base, QualType Derived,
5846 const CXXBasePath &Path,
5847 unsigned DiagID,
5848 bool ForceCheck = false,
5849 bool ForceUnprivileged = false);
5850 void CheckLookupAccess(const LookupResult &R);
5851 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5852 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5853 AccessSpecifier access,
5854 QualType objectType);
5855
5856 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5857 const MultiLevelTemplateArgumentList &TemplateArgs);
5858 void PerformDependentDiagnostics(const DeclContext *Pattern,
5859 const MultiLevelTemplateArgumentList &TemplateArgs);
5860
5861 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5862
5863 /// \brief When true, access checking violations are treated as SFINAE
5864 /// failures rather than hard errors.
5865 bool AccessCheckingSFINAE;
5866
5867 enum AbstractDiagSelID {
5868 AbstractNone = -1,
5869 AbstractReturnType,
5870 AbstractParamType,
5871 AbstractVariableType,
5872 AbstractFieldType,
5873 AbstractIvarType,
5874 AbstractSynthesizedIvarType,
5875 AbstractArrayType
5876 };
5877
5878 bool isAbstractType(SourceLocation Loc, QualType T);
5879 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5880 TypeDiagnoser &Diagnoser);
5881 template <typename... Ts>
5882 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5883 const Ts &...Args) {
5884 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5885 return RequireNonAbstractType(Loc, T, Diagnoser);
5886 }
5887
5888 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5889
5890 //===--------------------------------------------------------------------===//
5891 // C++ Overloaded Operators [C++ 13.5]
5892 //
5893
5894 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5895
5896 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5897
5898 //===--------------------------------------------------------------------===//
5899 // C++ Templates [C++ 14]
5900 //
5901 void FilterAcceptableTemplateNames(LookupResult &R,
5902 bool AllowFunctionTemplates = true);
5903 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5904 bool AllowFunctionTemplates = true);
5905
5906 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5907 QualType ObjectType, bool EnteringContext,
5908 bool &MemberOfUnknownSpecialization);
5909
5910 TemplateNameKind isTemplateName(Scope *S,
5911 CXXScopeSpec &SS,
5912 bool hasTemplateKeyword,
5913 UnqualifiedId &Name,
5914 ParsedType ObjectType,
5915 bool EnteringContext,
5916 TemplateTy &Template,
5917 bool &MemberOfUnknownSpecialization);
5918
5919 /// Determine whether a particular identifier might be the name in a C++1z
5920 /// deduction-guide declaration.
5921 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5922 SourceLocation NameLoc,
5923 ParsedTemplateTy *Template = nullptr);
5924
5925 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5926 SourceLocation IILoc,
5927 Scope *S,
5928 const CXXScopeSpec *SS,
5929 TemplateTy &SuggestedTemplate,
5930 TemplateNameKind &SuggestedKind);
5931
5932 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5933 NamedDecl *Instantiation,
5934 bool InstantiatedFromMember,
5935 const NamedDecl *Pattern,
5936 const NamedDecl *PatternDef,
5937 TemplateSpecializationKind TSK,
5938 bool Complain = true);
5939
5940 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5941 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5942
5943 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5944 SourceLocation EllipsisLoc,
5945 SourceLocation KeyLoc,
5946 IdentifierInfo *ParamName,
5947 SourceLocation ParamNameLoc,
5948 unsigned Depth, unsigned Position,
5949 SourceLocation EqualLoc,
5950 ParsedType DefaultArg);
5951
5952 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5953 SourceLocation Loc);
5954 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5955
5956 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5957 unsigned Depth,
5958 unsigned Position,
5959 SourceLocation EqualLoc,
5960 Expr *DefaultArg);
5961 Decl *ActOnTemplateTemplateParameter(Scope *S,
5962 SourceLocation TmpLoc,
5963 TemplateParameterList *Params,
5964 SourceLocation EllipsisLoc,
5965 IdentifierInfo *ParamName,
5966 SourceLocation ParamNameLoc,
5967 unsigned Depth,
5968 unsigned Position,
5969 SourceLocation EqualLoc,
5970 ParsedTemplateArgument DefaultArg);
5971
5972 TemplateParameterList *
5973 ActOnTemplateParameterList(unsigned Depth,
5974 SourceLocation ExportLoc,
5975 SourceLocation TemplateLoc,
5976 SourceLocation LAngleLoc,
5977 ArrayRef<Decl *> Params,
5978 SourceLocation RAngleLoc,
5979 Expr *RequiresClause);
5980
5981 /// \brief The context in which we are checking a template parameter list.
5982 enum TemplateParamListContext {
5983 TPC_ClassTemplate,
5984 TPC_VarTemplate,
5985 TPC_FunctionTemplate,
5986 TPC_ClassTemplateMember,
5987 TPC_FriendClassTemplate,
5988 TPC_FriendFunctionTemplate,
5989 TPC_FriendFunctionTemplateDefinition,
5990 TPC_TypeAliasTemplate
5991 };
5992
5993 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5994 TemplateParameterList *OldParams,
5995 TemplateParamListContext TPC);
5996 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5997 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5998 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5999 ArrayRef<TemplateParameterList *> ParamLists,
6000 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6001
6002 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6003 SourceLocation KWLoc, CXXScopeSpec &SS,
6004 IdentifierInfo *Name, SourceLocation NameLoc,
6005 AttributeList *Attr,
6006 TemplateParameterList *TemplateParams,
6007 AccessSpecifier AS,
6008 SourceLocation ModulePrivateLoc,
6009 SourceLocation FriendLoc,
6010 unsigned NumOuterTemplateParamLists,
6011 TemplateParameterList **OuterTemplateParamLists,
6012 SkipBodyInfo *SkipBody = nullptr);
6013
6014 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6015 QualType NTTPType,
6016 SourceLocation Loc);
6017
6018 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6019 TemplateArgumentListInfo &Out);
6020
6021 void NoteAllFoundTemplates(TemplateName Name);
6022
6023 QualType CheckTemplateIdType(TemplateName Template,
6024 SourceLocation TemplateLoc,
6025 TemplateArgumentListInfo &TemplateArgs);
6026
6027 TypeResult
6028 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6029 TemplateTy Template, IdentifierInfo *TemplateII,
6030 SourceLocation TemplateIILoc,
6031 SourceLocation LAngleLoc,
6032 ASTTemplateArgsPtr TemplateArgs,
6033 SourceLocation RAngleLoc,
6034 bool IsCtorOrDtorName = false,
6035 bool IsClassName = false);
6036
6037 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6038 /// such as \c class T::template apply<U>.
6039 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6040 TypeSpecifierType TagSpec,
6041 SourceLocation TagLoc,
6042 CXXScopeSpec &SS,
6043 SourceLocation TemplateKWLoc,
6044 TemplateTy TemplateD,
6045 SourceLocation TemplateLoc,
6046 SourceLocation LAngleLoc,
6047 ASTTemplateArgsPtr TemplateArgsIn,
6048 SourceLocation RAngleLoc);
6049
6050 DeclResult ActOnVarTemplateSpecialization(
6051 Scope *S, Declarator &D, TypeSourceInfo *DI,
6052 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6053 StorageClass SC, bool IsPartialSpecialization);
6054
6055 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6056 SourceLocation TemplateLoc,
6057 SourceLocation TemplateNameLoc,
6058 const TemplateArgumentListInfo &TemplateArgs);
6059
6060 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6061 const DeclarationNameInfo &NameInfo,
6062 VarTemplateDecl *Template,
6063 SourceLocation TemplateLoc,
6064 const TemplateArgumentListInfo *TemplateArgs);
6065
6066 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6067 SourceLocation TemplateKWLoc,
6068 LookupResult &R,
6069 bool RequiresADL,
6070 const TemplateArgumentListInfo *TemplateArgs);
6071
6072 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6073 SourceLocation TemplateKWLoc,
6074 const DeclarationNameInfo &NameInfo,
6075 const TemplateArgumentListInfo *TemplateArgs);
6076
6077 TemplateNameKind ActOnDependentTemplateName(
6078 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6079 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6080 TemplateTy &Template, bool AllowInjectedClassName = false);
6081
6082 DeclResult
6083 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6084 SourceLocation KWLoc,
6085 SourceLocation ModulePrivateLoc,
6086 TemplateIdAnnotation &TemplateId,
6087 AttributeList *Attr,
6088 MultiTemplateParamsArg TemplateParameterLists,
6089 SkipBodyInfo *SkipBody = nullptr);
6090
6091 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6092 TemplateDecl *PrimaryTemplate,
6093 unsigned NumExplicitArgs,
6094 ArrayRef<TemplateArgument> Args);
6095 void CheckTemplatePartialSpecialization(
6096 ClassTemplatePartialSpecializationDecl *Partial);
6097 void CheckTemplatePartialSpecialization(
6098 VarTemplatePartialSpecializationDecl *Partial);
6099
6100 Decl *ActOnTemplateDeclarator(Scope *S,
6101 MultiTemplateParamsArg TemplateParameterLists,
6102 Declarator &D);
6103
6104 bool
6105 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6106 TemplateSpecializationKind NewTSK,
6107 NamedDecl *PrevDecl,
6108 TemplateSpecializationKind PrevTSK,
6109 SourceLocation PrevPtOfInstantiation,
6110 bool &SuppressNew);
6111
6112 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6113 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6114 LookupResult &Previous);
6115
6116 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6117 TemplateArgumentListInfo *ExplicitTemplateArgs,
6118 LookupResult &Previous);
6119 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6120 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6121
6122 DeclResult
6123 ActOnExplicitInstantiation(Scope *S,
6124 SourceLocation ExternLoc,
6125 SourceLocation TemplateLoc,
6126 unsigned TagSpec,
6127 SourceLocation KWLoc,
6128 const CXXScopeSpec &SS,
6129 TemplateTy Template,
6130 SourceLocation TemplateNameLoc,
6131 SourceLocation LAngleLoc,
6132 ASTTemplateArgsPtr TemplateArgs,
6133 SourceLocation RAngleLoc,
6134 AttributeList *Attr);
6135
6136 DeclResult
6137 ActOnExplicitInstantiation(Scope *S,
6138 SourceLocation ExternLoc,
6139 SourceLocation TemplateLoc,
6140 unsigned TagSpec,
6141 SourceLocation KWLoc,
6142 CXXScopeSpec &SS,
6143 IdentifierInfo *Name,
6144 SourceLocation NameLoc,
6145 AttributeList *Attr);
6146
6147 DeclResult ActOnExplicitInstantiation(Scope *S,
6148 SourceLocation ExternLoc,
6149 SourceLocation TemplateLoc,
6150 Declarator &D);
6151
6152 TemplateArgumentLoc
6153 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6154 SourceLocation TemplateLoc,
6155 SourceLocation RAngleLoc,
6156 Decl *Param,
6157 SmallVectorImpl<TemplateArgument>
6158 &Converted,
6159 bool &HasDefaultArg);
6160
6161 /// \brief Specifies the context in which a particular template
6162 /// argument is being checked.
6163 enum CheckTemplateArgumentKind {
6164 /// \brief The template argument was specified in the code or was
6165 /// instantiated with some deduced template arguments.
6166 CTAK_Specified,
6167
6168 /// \brief The template argument was deduced via template argument
6169 /// deduction.
6170 CTAK_Deduced,
6171
6172 /// \brief The template argument was deduced from an array bound
6173 /// via template argument deduction.
6174 CTAK_DeducedFromArrayBound
6175 };
6176
6177 bool CheckTemplateArgument(NamedDecl *Param,
6178 TemplateArgumentLoc &Arg,
6179 NamedDecl *Template,
6180 SourceLocation TemplateLoc,
6181 SourceLocation RAngleLoc,
6182 unsigned ArgumentPackIndex,
6183 SmallVectorImpl<TemplateArgument> &Converted,
6184 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6185
6186 /// \brief Check that the given template arguments can be be provided to
6187 /// the given template, converting the arguments along the way.
6188 ///
6189 /// \param Template The template to which the template arguments are being
6190 /// provided.
6191 ///
6192 /// \param TemplateLoc The location of the template name in the source.
6193 ///
6194 /// \param TemplateArgs The list of template arguments. If the template is
6195 /// a template template parameter, this function may extend the set of
6196 /// template arguments to also include substituted, defaulted template
6197 /// arguments.
6198 ///
6199 /// \param PartialTemplateArgs True if the list of template arguments is
6200 /// intentionally partial, e.g., because we're checking just the initial
6201 /// set of template arguments.
6202 ///
6203 /// \param Converted Will receive the converted, canonicalized template
6204 /// arguments.
6205 ///
6206 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6207 /// contain the converted forms of the template arguments as written.
6208 /// Otherwise, \p TemplateArgs will not be modified.
6209 ///
6210 /// \returns true if an error occurred, false otherwise.
6211 bool CheckTemplateArgumentList(TemplateDecl *Template,
6212 SourceLocation TemplateLoc,
6213 TemplateArgumentListInfo &TemplateArgs,
6214 bool PartialTemplateArgs,
6215 SmallVectorImpl<TemplateArgument> &Converted,
6216 bool UpdateArgsWithConversions = true);
6217
6218 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6219 TemplateArgumentLoc &Arg,
6220 SmallVectorImpl<TemplateArgument> &Converted);
6221
6222 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6223 TypeSourceInfo *Arg);
6224 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6225 QualType InstantiatedParamType, Expr *Arg,
6226 TemplateArgument &Converted,
6227 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6228 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6229 TemplateArgumentLoc &Arg,
6230 unsigned ArgumentPackIndex);
6231
6232 ExprResult
6233 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6234 QualType ParamType,
6235 SourceLocation Loc);
6236 ExprResult
6237 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6238 SourceLocation Loc);
6239
6240 /// \brief Enumeration describing how template parameter lists are compared
6241 /// for equality.
6242 enum TemplateParameterListEqualKind {
6243 /// \brief We are matching the template parameter lists of two templates
6244 /// that might be redeclarations.
6245 ///
6246 /// \code
6247 /// template<typename T> struct X;
6248 /// template<typename T> struct X;
6249 /// \endcode
6250 TPL_TemplateMatch,
6251
6252 /// \brief We are matching the template parameter lists of two template
6253 /// template parameters as part of matching the template parameter lists
6254 /// of two templates that might be redeclarations.
6255 ///
6256 /// \code
6257 /// template<template<int I> class TT> struct X;
6258 /// template<template<int Value> class Other> struct X;
6259 /// \endcode
6260 TPL_TemplateTemplateParmMatch,
6261
6262 /// \brief We are matching the template parameter lists of a template
6263 /// template argument against the template parameter lists of a template
6264 /// template parameter.
6265 ///
6266 /// \code
6267 /// template<template<int Value> class Metafun> struct X;
6268 /// template<int Value> struct integer_c;
6269 /// X<integer_c> xic;
6270 /// \endcode
6271 TPL_TemplateTemplateArgumentMatch
6272 };
6273
6274 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6275 TemplateParameterList *Old,
6276 bool Complain,
6277 TemplateParameterListEqualKind Kind,
6278 SourceLocation TemplateArgLoc
6279 = SourceLocation());
6280
6281 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6282
6283 /// \brief Called when the parser has parsed a C++ typename
6284 /// specifier, e.g., "typename T::type".
6285 ///
6286 /// \param S The scope in which this typename type occurs.
6287 /// \param TypenameLoc the location of the 'typename' keyword
6288 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6289 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6290 /// \param IdLoc the location of the identifier.
6291 TypeResult
6292 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6293 const CXXScopeSpec &SS, const IdentifierInfo &II,
6294 SourceLocation IdLoc);
6295
6296 /// \brief Called when the parser has parsed a C++ typename
6297 /// specifier that ends in a template-id, e.g.,
6298 /// "typename MetaFun::template apply<T1, T2>".
6299 ///
6300 /// \param S The scope in which this typename type occurs.
6301 /// \param TypenameLoc the location of the 'typename' keyword
6302 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6303 /// \param TemplateLoc the location of the 'template' keyword, if any.
6304 /// \param TemplateName The template name.
6305 /// \param TemplateII The identifier used to name the template.
6306 /// \param TemplateIILoc The location of the template name.
6307 /// \param LAngleLoc The location of the opening angle bracket ('<').
6308 /// \param TemplateArgs The template arguments.
6309 /// \param RAngleLoc The location of the closing angle bracket ('>').
6310 TypeResult
6311 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6312 const CXXScopeSpec &SS,
6313 SourceLocation TemplateLoc,
6314 TemplateTy TemplateName,
6315 IdentifierInfo *TemplateII,
6316 SourceLocation TemplateIILoc,
6317 SourceLocation LAngleLoc,
6318 ASTTemplateArgsPtr TemplateArgs,
6319 SourceLocation RAngleLoc);
6320
6321 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6322 SourceLocation KeywordLoc,
6323 NestedNameSpecifierLoc QualifierLoc,
6324 const IdentifierInfo &II,
6325 SourceLocation IILoc);
6326
6327 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6328 SourceLocation Loc,
6329 DeclarationName Name);
6330 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6331
6332 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6333 bool RebuildTemplateParamsInCurrentInstantiation(
6334 TemplateParameterList *Params);
6335
6336 std::string
6337 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6338 const TemplateArgumentList &Args);
6339
6340 std::string
6341 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6342 const TemplateArgument *Args,
6343 unsigned NumArgs);
6344
6345 //===--------------------------------------------------------------------===//
6346 // C++ Variadic Templates (C++0x [temp.variadic])
6347 //===--------------------------------------------------------------------===//
6348
6349 /// Determine whether an unexpanded parameter pack might be permitted in this
6350 /// location. Useful for error recovery.
6351 bool isUnexpandedParameterPackPermitted();
6352
6353 /// \brief The context in which an unexpanded parameter pack is
6354 /// being diagnosed.
6355 ///
6356 /// Note that the values of this enumeration line up with the first
6357 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6358 enum UnexpandedParameterPackContext {
6359 /// \brief An arbitrary expression.
6360 UPPC_Expression = 0,
6361
6362 /// \brief The base type of a class type.
6363 UPPC_BaseType,
6364
6365 /// \brief The type of an arbitrary declaration.
6366 UPPC_DeclarationType,
6367
6368 /// \brief The type of a data member.
6369 UPPC_DataMemberType,
6370
6371 /// \brief The size of a bit-field.
6372 UPPC_BitFieldWidth,
6373
6374 /// \brief The expression in a static assertion.
6375 UPPC_StaticAssertExpression,
6376
6377 /// \brief The fixed underlying type of an enumeration.
6378 UPPC_FixedUnderlyingType,
6379
6380 /// \brief The enumerator value.
6381 UPPC_EnumeratorValue,
6382
6383 /// \brief A using declaration.
6384 UPPC_UsingDeclaration,
6385
6386 /// \brief A friend declaration.
6387 UPPC_FriendDeclaration,
6388
6389 /// \brief A declaration qualifier.
6390 UPPC_DeclarationQualifier,
6391
6392 /// \brief An initializer.
6393 UPPC_Initializer,
6394
6395 /// \brief A default argument.
6396 UPPC_DefaultArgument,
6397
6398 /// \brief The type of a non-type template parameter.
6399 UPPC_NonTypeTemplateParameterType,
6400
6401 /// \brief The type of an exception.
6402 UPPC_ExceptionType,
6403
6404 /// \brief Partial specialization.
6405 UPPC_PartialSpecialization,
6406
6407 /// \brief Microsoft __if_exists.
6408 UPPC_IfExists,
6409
6410 /// \brief Microsoft __if_not_exists.
6411 UPPC_IfNotExists,
6412
6413 /// \brief Lambda expression.
6414 UPPC_Lambda,
6415
6416 /// \brief Block expression,
6417 UPPC_Block
6418 };
6419
6420 /// \brief Diagnose unexpanded parameter packs.
6421 ///
6422 /// \param Loc The location at which we should emit the diagnostic.
6423 ///
6424 /// \param UPPC The context in which we are diagnosing unexpanded
6425 /// parameter packs.
6426 ///
6427 /// \param Unexpanded the set of unexpanded parameter packs.
6428 ///
6429 /// \returns true if an error occurred, false otherwise.
6430 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6431 UnexpandedParameterPackContext UPPC,
6432 ArrayRef<UnexpandedParameterPack> Unexpanded);
6433
6434 /// \brief If the given type contains an unexpanded parameter pack,
6435 /// diagnose the error.
6436 ///
6437 /// \param Loc The source location where a diagnostc should be emitted.
6438 ///
6439 /// \param T The type that is being checked for unexpanded parameter
6440 /// packs.
6441 ///
6442 /// \returns true if an error occurred, false otherwise.
6443 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6444 UnexpandedParameterPackContext UPPC);
6445
6446 /// \brief If the given expression contains an unexpanded parameter
6447 /// pack, diagnose the error.
6448 ///
6449 /// \param E The expression that is being checked for unexpanded
6450 /// parameter packs.
6451 ///
6452 /// \returns true if an error occurred, false otherwise.
6453 bool DiagnoseUnexpandedParameterPack(Expr *E,
6454 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6455
6456 /// \brief If the given nested-name-specifier contains an unexpanded
6457 /// parameter pack, diagnose the error.
6458 ///
6459 /// \param SS The nested-name-specifier that is being checked for
6460 /// unexpanded parameter packs.
6461 ///
6462 /// \returns true if an error occurred, false otherwise.
6463 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6464 UnexpandedParameterPackContext UPPC);
6465
6466 /// \brief If the given name contains an unexpanded parameter pack,
6467 /// diagnose the error.
6468 ///
6469 /// \param NameInfo The name (with source location information) that
6470 /// is being checked for unexpanded parameter packs.
6471 ///
6472 /// \returns true if an error occurred, false otherwise.
6473 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6474 UnexpandedParameterPackContext UPPC);
6475
6476 /// \brief If the given template name contains an unexpanded parameter pack,
6477 /// diagnose the error.
6478 ///
6479 /// \param Loc The location of the template name.
6480 ///
6481 /// \param Template The template name that is being checked for unexpanded
6482 /// parameter packs.
6483 ///
6484 /// \returns true if an error occurred, false otherwise.
6485 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6486 TemplateName Template,
6487 UnexpandedParameterPackContext UPPC);
6488
6489 /// \brief If the given template argument contains an unexpanded parameter
6490 /// pack, diagnose the error.
6491 ///
6492 /// \param Arg The template argument that is being checked for unexpanded
6493 /// parameter packs.
6494 ///
6495 /// \returns true if an error occurred, false otherwise.
6496 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6497 UnexpandedParameterPackContext UPPC);
6498
6499 /// \brief Collect the set of unexpanded parameter packs within the given
6500 /// template argument.
6501 ///
6502 /// \param Arg The template argument that will be traversed to find
6503 /// unexpanded parameter packs.
6504 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6505 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6506
6507 /// \brief Collect the set of unexpanded parameter packs within the given
6508 /// template argument.
6509 ///
6510 /// \param Arg The template argument that will be traversed to find
6511 /// unexpanded parameter packs.
6512 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6513 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6514
6515 /// \brief Collect the set of unexpanded parameter packs within the given
6516 /// type.
6517 ///
6518 /// \param T The type that will be traversed to find
6519 /// unexpanded parameter packs.
6520 void collectUnexpandedParameterPacks(QualType T,
6521 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6522
6523 /// \brief Collect the set of unexpanded parameter packs within the given
6524 /// type.
6525 ///
6526 /// \param TL The type that will be traversed to find
6527 /// unexpanded parameter packs.
6528 void collectUnexpandedParameterPacks(TypeLoc TL,
6529 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6530
6531 /// \brief Collect the set of unexpanded parameter packs within the given
6532 /// nested-name-specifier.
6533 ///
6534 /// \param NNS The nested-name-specifier that will be traversed to find
6535 /// unexpanded parameter packs.
6536 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6537 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6538
6539 /// \brief Collect the set of unexpanded parameter packs within the given
6540 /// name.
6541 ///
6542 /// \param NameInfo The name that will be traversed to find
6543 /// unexpanded parameter packs.
6544 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6545 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6546
6547 /// \brief Invoked when parsing a template argument followed by an
6548 /// ellipsis, which creates a pack expansion.
6549 ///
6550 /// \param Arg The template argument preceding the ellipsis, which
6551 /// may already be invalid.
6552 ///
6553 /// \param EllipsisLoc The location of the ellipsis.
6554 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6555 SourceLocation EllipsisLoc);
6556
6557 /// \brief Invoked when parsing a type followed by an ellipsis, which
6558 /// creates a pack expansion.
6559 ///
6560 /// \param Type The type preceding the ellipsis, which will become
6561 /// the pattern of the pack expansion.
6562 ///
6563 /// \param EllipsisLoc The location of the ellipsis.
6564 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6565
6566 /// \brief Construct a pack expansion type from the pattern of the pack
6567 /// expansion.
6568 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6569 SourceLocation EllipsisLoc,
6570 Optional<unsigned> NumExpansions);
6571
6572 /// \brief Construct a pack expansion type from the pattern of the pack
6573 /// expansion.
6574 QualType CheckPackExpansion(QualType Pattern,
6575 SourceRange PatternRange,
6576 SourceLocation EllipsisLoc,
6577 Optional<unsigned> NumExpansions);
6578
6579 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6580 /// creates a pack expansion.
6581 ///
6582 /// \param Pattern The expression preceding the ellipsis, which will become
6583 /// the pattern of the pack expansion.
6584 ///
6585 /// \param EllipsisLoc The location of the ellipsis.
6586 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6587
6588 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6589 /// creates a pack expansion.
6590 ///
6591 /// \param Pattern The expression preceding the ellipsis, which will become
6592 /// the pattern of the pack expansion.
6593 ///
6594 /// \param EllipsisLoc The location of the ellipsis.
6595 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6596 Optional<unsigned> NumExpansions);
6597
6598 /// \brief Determine whether we could expand a pack expansion with the
6599 /// given set of parameter packs into separate arguments by repeatedly
6600 /// transforming the pattern.
6601 ///
6602 /// \param EllipsisLoc The location of the ellipsis that identifies the
6603 /// pack expansion.
6604 ///
6605 /// \param PatternRange The source range that covers the entire pattern of
6606 /// the pack expansion.
6607 ///
6608 /// \param Unexpanded The set of unexpanded parameter packs within the
6609 /// pattern.
6610 ///
6611 /// \param ShouldExpand Will be set to \c true if the transformer should
6612 /// expand the corresponding pack expansions into separate arguments. When
6613 /// set, \c NumExpansions must also be set.
6614 ///
6615 /// \param RetainExpansion Whether the caller should add an unexpanded
6616 /// pack expansion after all of the expanded arguments. This is used
6617 /// when extending explicitly-specified template argument packs per
6618 /// C++0x [temp.arg.explicit]p9.
6619 ///
6620 /// \param NumExpansions The number of separate arguments that will be in
6621 /// the expanded form of the corresponding pack expansion. This is both an
6622 /// input and an output parameter, which can be set by the caller if the
6623 /// number of expansions is known a priori (e.g., due to a prior substitution)
6624 /// and will be set by the callee when the number of expansions is known.
6625 /// The callee must set this value when \c ShouldExpand is \c true; it may
6626 /// set this value in other cases.
6627 ///
6628 /// \returns true if an error occurred (e.g., because the parameter packs
6629 /// are to be instantiated with arguments of different lengths), false
6630 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6631 /// must be set.
6632 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6633 SourceRange PatternRange,
6634 ArrayRef<UnexpandedParameterPack> Unexpanded,
6635 const MultiLevelTemplateArgumentList &TemplateArgs,
6636 bool &ShouldExpand,
6637 bool &RetainExpansion,
6638 Optional<unsigned> &NumExpansions);
6639
6640 /// \brief Determine the number of arguments in the given pack expansion
6641 /// type.
6642 ///
6643 /// This routine assumes that the number of arguments in the expansion is
6644 /// consistent across all of the unexpanded parameter packs in its pattern.
6645 ///
6646 /// Returns an empty Optional if the type can't be expanded.
6647 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6648 const MultiLevelTemplateArgumentList &TemplateArgs);
6649
6650 /// \brief Determine whether the given declarator contains any unexpanded
6651 /// parameter packs.
6652 ///
6653 /// This routine is used by the parser to disambiguate function declarators
6654 /// with an ellipsis prior to the ')', e.g.,
6655 ///
6656 /// \code
6657 /// void f(T...);
6658 /// \endcode
6659 ///
6660 /// To determine whether we have an (unnamed) function parameter pack or
6661 /// a variadic function.
6662 ///
6663 /// \returns true if the declarator contains any unexpanded parameter packs,
6664 /// false otherwise.
6665 bool containsUnexpandedParameterPacks(Declarator &D);
6666
6667 /// \brief Returns the pattern of the pack expansion for a template argument.
6668 ///
6669 /// \param OrigLoc The template argument to expand.
6670 ///
6671 /// \param Ellipsis Will be set to the location of the ellipsis.
6672 ///
6673 /// \param NumExpansions Will be set to the number of expansions that will
6674 /// be generated from this pack expansion, if known a priori.
6675 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6676 TemplateArgumentLoc OrigLoc,
6677 SourceLocation &Ellipsis,
6678 Optional<unsigned> &NumExpansions) const;
6679
6680 /// Given a template argument that contains an unexpanded parameter pack, but
6681 /// which has already been substituted, attempt to determine the number of
6682 /// elements that will be produced once this argument is fully-expanded.
6683 ///
6684 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6685 /// avoid actually expanding the pack where possible.
6686 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6687
6688 //===--------------------------------------------------------------------===//
6689 // C++ Template Argument Deduction (C++ [temp.deduct])
6690 //===--------------------------------------------------------------------===//
6691
6692 /// Adjust the type \p ArgFunctionType to match the calling convention,
6693 /// noreturn, and optionally the exception specification of \p FunctionType.
6694 /// Deduction often wants to ignore these properties when matching function
6695 /// types.
6696 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6697 bool AdjustExceptionSpec = false);
6698
6699 /// \brief Describes the result of template argument deduction.
6700 ///
6701 /// The TemplateDeductionResult enumeration describes the result of
6702 /// template argument deduction, as returned from
6703 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6704 /// structure provides additional information about the results of
6705 /// template argument deduction, e.g., the deduced template argument
6706 /// list (if successful) or the specific template parameters or
6707 /// deduced arguments that were involved in the failure.
6708 enum